content stringlengths 5 1.05M |
|---|
from fastapi import FastAPI
from fastapi import responses
from fastapi.responses import JSONResponse
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from webService.fatigueWebWrapper.Payload import FatiguePayload
from webService.fatigueWebWrapper.wrapper import FatigueWebWrapper
from webService.stress... |
import os
import argparse
import io
import struct
from typing import Union
from enum import Enum
class ZIPTag(Enum):
S_ZIPFILERECORD = 0x04034b50
S_ZIPDATADESCR = 0x08074b50
S_ZIPDIRENTRY = 0x02014b50
S_ZIPDIGITALSIG = 0x05054b50
S_ZIP64ENDLOCATORRECORD = 0x06064b50
S_ZIP64ENDLOCATOR = 0x07064... |
from os import mkdir
from os.path import exists
def create_dataset_directories(parent_dir: str, classes: [str]) -> [str]:
"""
Checks, whether directories exist, in which training samples can be stored
at. If not, new directories are getting generated.
@param parent_dir: Directory, at which a new clas... |
expected_output = {
"address_family":{
"ipv4":{
"bfd_sessions_down":0,
"bfd_sessions_inactive":1,
"bfd_sessions_up":0,
"intf_down":1,
"intf_up":1,
"num_bfd_sessions":1,
"num_intf":2,
"state":{
"all":{
"sessions":2,... |
import torch
def covariance(x):
x = x - x.mean(dim=0) # It use to be x -= x.mean(dim=0), stupid! this will change the input tensor!!!
return x.t().matmul(x) / (x.size(0) - 1)
def corrcoef(x=None, c=None):
# breakpoint()
c = covariance(x) if c is None else c
std = c.diagonal(0).sqrt()
# breakp... |
from pydantic import BaseModel
class Nmap_input(BaseModel):
url: str
class Config:
orm_mode = True |
import numpy as np
import pyqtgraph as pg
from qtpy.QtWidgets import QProgressBar, QVBoxLayout
class ImageSize:
height = 0
width = 0
gap_index = 0
def __init__(self, width=0, height=0):
gap_index = np.int(height/2)
self.gap_index = gap_index
self.width = width
self.hei... |
from .button import Button
from .background import Background
import pygame
class Menu:
def __init__(self):
self.background = None
self.images = {}
self.buttons = {}
def create_buttons(self, screen):
self.buttons = {}
start = (480, 700)
size = (200, 50)
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2015-12-30 14:46
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency... |
# coding=utf-8
from typing import Optional
def clear(string: str, delchars: Optional[str] = "") -> str:
"""
Clears string by removing unwanted spaces, HTML-tags, special and specified characters
Args:
string (str): String you want to clear
delchars (Optional[str]): Characters you want to... |
import os.path
import itertools
import Tools
import random
import numpy as np
import scipy
import scipy.stats
NBTESTS = 10
VECDIM = [12,14,20]
def entropyTest(config,nb):
inputs = []
outputs = []
vecDim = VECDIM[nb % len(VECDIM)]
dims=np.array([NBTESTS,vecDim])
for _ in range(0,NBTESTS):
... |
# ==========================================================================
# Only for a given set of 10 companies the data is being extracted/collected
# to make predictions as they are independent and are also likely to sample
# lot of variation from engineering, beverages, mdicine, investment banking
# etc and the... |
from week7.baseSort.cmp.insert.InsertionSort import insertSort
"""
桶排序
通过最大值最小值以及桶默认大小 计算需要的桶个数
遍历每个桶 对每个桶进行插入排序
遍历桶将数据按顺序保存到原始数组
"""
def bucketSort(arr):
_max = max(arr)
_min = min(arr)
_len = len(arr)
_pox = 2
_size = ((_max - _min) >> _pox) + 1 # 默认每个桶存放2**_pox个数据 则计算需要的桶个数
buckets = [[] ... |
from rest_framework import serializers
from apps.contents.models import SPUSpecification, SPU
class SPUSpecSerializer(serializers.ModelSerializer):
"""
商品规格表的序列化器
"""
# 指定spu的名称 通过模型类的外键
spu = serializers.StringRelatedField(read_only=True)
# 指定spu的id值 通过表字段
spu_id = serializers.IntegerF... |
# -*- coding: utf-8 -*-
from .headers import (get_csq, get_header)
from .get_info import (get_most_severe_consequence, get_omim_number,
get_cytoband_coord, get_gene_info, get_gene_symbols)
from .ped import get_individuals, get_cases
from .phenomizer import hpo_genes
from .constants import IMPACT_... |
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from .models import Author, Book
# Create your views here.
class AuthorListView(ListView):
model = Author
class AuthorDetailView(DetailView):
model = Author
class BookListView(ListView):
model = Book
class Boo... |
from distutils.core import setup
PACKAGE = "inmembrane"
DESCRIPTION = "A bioinformatic pipeline for proteome annotation \
to predict if a protein is exposed on the surface of a bacteria."
AUTHOR = "Andrew Perry & Bosco Ho"
AUTHOR_EMAIL = "[email protected]"
URL = "http://github.com/boscoh/inmembrane"
# Must be a ... |
from functools import wraps
def flatten_list(method):
@wraps(method)
def inner(*args):
return list(method(*args))
return inner
def flatten_dict(method):
@wraps(method)
def inner(*args):
return dict(method(*args))
return inner
|
import platform
import time
from datetime import datetime as dt
win_hosts_path = r'/c/Windows/System32/Drivers/etc/hosts'
osx_linux_hosts_path = r'etc/hosts'
temp_path = r'hosts'
redirect = '127.0.0.1'
websites = ['www.example.com', 'example.com']
if (platform.system() == 'Windows'):
hosts_path = win_hosts_path... |
import distutils.core
from distutils.core import setup
version_number = "0.1"
setup(
name="qvalue",
version=version_number,
description="Converts p-values in q-values in order to account for multiple hypotheses testing, see (Storey and Tibshirani, 2003)",
long_description=open("README.md").read(),
... |
"""
Simple linear regression example in TensorFlow
This program tries to predict the number of thefts from
the number of fire in the city of Chicago
"""
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import xlrd
DATA_FILE = '../data/fire_theft.xls'
# Phase 1: Assemble the graph
# Step 1:... |
# pylint: disable=invalid-name
from Page import Page
from WebUtils.Funcs import htmlEncode as enc
class Inspector(Page):
def writeContent(self):
req = self.request()
self.write('Path:<br>\n')
self.write(f'<code>{enc(req.extraURLPath())}</code><p>\n')
self.write('Variables:<br>\n'... |
"""Functions for computing atomic structure of proteins."""
import logging
# %%
# Graphein
# Author: Arian Jamasb <[email protected]>
# License: MIT
# Project Website: https://github.com/a-r-j/graphein
# Code Repository: https://github.com/a-r-j/graphein
from typing import Any, Dict
import networkx as nx
import numpy a... |
from __future__ import annotations
from typing import Any
from rich.console import Group
from rich.progress import BarColumn, Progress
from rich.rule import Rule
from rich.table import Table
from rich.text import Text
from .. import styles
from .paginated_table import PaginatedTableRenderable
class ExecutorStatusT... |
import pytest
pytestmark = pytest.mark.asyncio
async def test_indices(cms_requester):
async with cms_requester as requester:
resp, status = await requester(
'GET',
'/db/guillotina/@indices'
)
assert 'Item' in resp['types']
assert 'title' in resp['types']['I... |
from distutils.core import setup
setup(name='ParrotD3MWrapper',
version='1.0.3',
description='A thin wrapper for interacting with New Knowledge time series prediction tool Parrot',
packages=['ParrotD3MWrapper'],
install_requires=["typing",
"Sloth==2.0.3"],
dependency_links=[
"git+ht... |
"""Functions to make predictions using the deep learning model"""
import numpy as np
from . import config as cf
from pathlib import Path
import gdown
from fastai.vision import load_learner
from skimage import measure
def fetch_learner(path=Path(__file__).parents[1], model=cf.MODEL):
"""
Returns learner if ... |
#!/usr/bin/env python3
from unittest import TestCase
from kubernetes.client.models.v1_object_meta import V1ObjectMeta
from kubernetes.client.models.v1_node import V1Node
from kubernetes.client.models.v1_node_spec import V1NodeSpec
from kubernetes.client.models.v1_node_status import V1NodeStatus
from kubernetes.client.... |
from .bulk_email import BulkEmail
from .logger import Logger
import sys
if len(sys.argv) != 4:
print("Usage: python -m bulkemail bulkemail/recipients.txt bulkemail/subject.txt bulkemail/body.txt")
exit(1)
if __name__ == '__main__':
# init logger
logger = Logger.getLogger()
with open(sys.argv[1], '... |
import pytest
from flowpipe import Graph, Node
@Node(outputs=["out"])
def DemoNode(in_):
return {"out": in_}
def _nested_graph():
"""Create this nested subgraph:
+---------------+ +---------------+ +---------------+ +---------------+
| DemoNode | | DemoNode... |
#!/usr/bin/env python
# coding: utf-8
from xumm.resource import XummResource
from typing import Callable, Any
from xumm.ws_client import WSClient
from ..xumm_api import (
XummGetPayloadResponse as XummPayload,
XummPostPayloadResponse as CreatedPayload,
)
class PayloadAndSubscription(XummResource):
"""
... |
# Fibonacci Numbers
# Find the nth fibonacci number.
# Fibonacci numbers, commonly denoted Fn form a sequence,
# called the Fibonacci sequence, such that each number is the sum
# of the two preceding ones, starting from 0 and 1.
# There are a lot of ways to find the fibonacci numbers but we will
# look at the DP app... |
import struct
from mod_pywebsocket import stream
def web_socket_do_extra_handshake(request):
pass
def web_socket_transfer_data(request):
line = request.ws_stream.receive_message()
if line is None:
return
if line == '-':
data = ''
elif line == '--':
data = 'X'
else:
... |
from tarpan.shared.compare import model_weights
def test_weights():
weights = model_weights(deviances=[[1, 2, 3], [2, 3, 4], [7, 8, 9]])
actual_weights = [
round(weight, 5)
for weight in weights
]
assert actual_weights == [0.81749, 0.18241, 0.0001]
|
from django.db import models
from django.utils import timezone
class Sector(models.Model):
name = models.CharField(max_length = 50, db_index = True)
updated_at = models.DateTimeField(auto_now = True)
class Meta:
unique_together = ('name',)
class Market(models.Model):
name = models.CharField(max_length = ... |
#Programa printa maior idade escrita.
m=0
i1=int(input("Digite uma idade: "))
if(i1>m):
m=i1
i2=int(input("Digite uma idade: "))
if(i2>m):
m=i2
i3=int(input("Digite uma idade: "))
if(i3>m):
m=i3
i4=int(input("Digite uma idade: "))
if(i4>m):
m=i4
i5=int(input("Digite uma idade: "))
if(... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com [email protected]
from unittest.mock import patch
import pytest
from preggy import ex... |
from fastapi.testclient import TestClient
def test_create_tag(client: TestClient) -> None:
res = client.post("/api/tags/", json={"name": "tag name"})
assert res.status_code == 200
assert res.json()["name"] == "tag name"
def test_create_multiple_tags(client: TestClient) -> None:
res = client.post("/a... |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.db import connection
from .models import Task
from .forms import TaskForm
def task_list(request):
user = request.GET.get('user', "me")
query = "SELECT * from sqli_task WHERE owner ='" + user + "'"
cu... |
'''
Exception class
'''
class PAException(Exception):
'''
Custom exception class
'''
def __init__(self, status_code, message, errorCode):
super(PAException, self).__init__(message)
self.status_code = status_code
self.errorCode = errorCode
|
from ctypes import c_double, cdll, c_int, c_byte
from numpy.ctypeslib import ndpointer
# load library
lib = cdll.LoadLibrary("libtest.so")
# define args types
lib.ExportedFunction.argtypes = [c_double]*3 + [c_int]
# define a lovely function
def lovely_python_function(s0, s1, s2, N):
lib.ExportedFunction.restype =... |
##############################################################################
#
# Copyright (c) 2001 Zope Corporation and Contributors. All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFT... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
from __future__ import division # Standardmäßig float division - Ganzzahldivision kann man explizit mit '//' durchführen
import math
import numpy as np
from scipy.spatial import cKDTree,KDTree
from time import time
from pprint import pprint
size = 100
def benchmark... |
from sys import setrecursionlimit
"""
Give, he can hop 1 step, 2 step, or 3 step at a time
1 <= N <= 30 at least one step is there
Time : O(3^n) exponential
"""
def ways_to_reach(stairs) -> int:
# Base Case -> not particular to this question, as here it is given the N >= 1
if stairs == 0:
retu... |
from unittest import TestCase
from web3 import HTTPProvider, Web3, Account
from zksync_sdk.zksync import ZkSync
class TestZkSyncContract(TestCase):
private_key = "0xa045b52470d306ff78e91b0d2d92f90f7504189125a46b69423dc673fd6b4f3e"
def setUp(self) -> None:
self.account = Account.from_key(self.privat... |
from PIL import Image
from src.predictionAlgorithms.baseAlgorithm import BaseAlgorithm
from src.utilities.imageAnalysis.pixelsRainStrengthConverter import PixelsRainStrengthConverter
import numpy as np
from os import listdir, curdir
class CNN4L(BaseAlgorithm):
model = None
name = 'CNN 4 Layers'
def __ini... |
# Auto-generated. Do not edit.
from opendp._convert import *
from opendp._lib import *
from opendp.mod import *
from opendp.typing import *
__all__ = [
"make_cast",
"make_cast_default",
"make_is_equal",
"make_is_null",
"make_cast_inherent",
"make_cast_metric",
"make_clamp",
"make_unclam... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 1 15:33:37 2021
@author: shubhransu
"""
num = int(input("Enter any number"))
if num % 2 == 0:
print("NUmber is Even ")
else:
print("Number is odd")
|
# Copyright (c) 2010-2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... |
"""
Lambda handler for wanwu requests
"""
import json
from collections import namedtuple
Request = namedtuple(
'Request',
[
'method', # str 'GET' or 'POST'
'path', # str
'body', # None|str
'query', # dict
'headers', # dict
],
)
Response = namedtuple(
'Resp... |
import re
import time
import argparse
import collections
import unicodedata
def parseArgs():
parser = argparse.ArgumentParser()
egroup = parser.add_mutually_exclusive_group(required=True)
egroup.add_argument('-C', '--counting-words', action='store_true',
help='outputs the total number of w... |
from numpy import random, dot, exp, array
class NeuralNetwork:
def __init__(self):
random.seed(1)
self.weights = 2 * random.random((3, 1)) - 1
def train(self, inputs, outputs, num):
for iteration in range(num):
output = self.think(inputs)
error = outputs - ou... |
def prepare_options_for_plugin(module, readopt):
"""Resets P::e.options with options from the C++ "read_options"
block *readopt* labeled for *module*.
"""
import psi4
options = psi4.core.get_options()
options.set_read_globals(True)
options.add_int("PBP_C_POW",0);
readopt(module, option... |
from enum import Enum
class EnableStateEnum(Enum):
Enable = 2
Disable = 3
Shut_Down = 4
Offline = 6
Test = 7
Defer = 8
Quiesce = 9
Starting = 10
class HealthStateEnum(Enum):
OK = 5
Major_Failure = 20
Critical_Failure = 25
class OperationalStatusEnum(Enum):
Creating_... |
from neo4j.v1 import GraphDatabase, basic_auth
from datetime import datetime
import re
job_1 = {
"title": "Senior .NET Developers",
"category": "\u0418\u0422 - \u0420\u0430\u0437\u0440\u0430\u0431\u043e\u0442\u043a\u0430/\u043f\u043e\u0434\u0434\u0440\u044a\u0436\u043a\u0430 \u043d\u0430 \u0441\u043e\u0444\u0... |
import argparse as ap
import hail
from pprint import pprint
import time
from hail_scripts.v01.utils.add_clinvar import download_and_import_latest_clinvar_vcf, CLINVAR_VDS_PATH
from hail_scripts.v01.utils.vds_utils import write_vds
p = ap.ArgumentParser()
p.add_argument("-g", "--genome-version", help="Genome build: 37... |
from itertools import permutations
def find_maximix_arrangement(n, k):
chars = [chr(i) for i in range(65, 65 + n)]
maximum = 2 * n - 3
count = 0
for order in permutations(chars):
order = "".join(order)
if solve_order(order, n) == maximum:
count += 1
if cou... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-06-28 20:17
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('acquisitions', '0011_auto_20160628_2013'),
]
operations = [
migrations.Alter... |
'''
==================================================================================================
Script to calculate the IPA dielectric function of two-phase binary alloys (A_{1-x}B_{x})
==================================================================================================
method:
-- average: mixture... |
class Service(object):
def __init__(self, host):
self._host = host
def start(self, service):
return self.do(service, 'start')
def stop(self, service):
return self.do(service, 'stop')
def restart(self, service):
return self.do(service, 'restart')
def status(self, s... |
import rouge
from typing import List
def evaluate_rouge(hypo_texts: List[str], ref_texts: List[str]) -> dict:
print('Evaluating ROUGE...')
rouge_scorer = rouge.Rouge()
averaged_scores = rouge_scorer.get_scores(hyps=hypo_texts, refs=ref_texts, avg=True)
results = {}
for k, v in avera... |
# -*- coding: utf-8 -
#
# This file is part of gunicorn released under the MIT license.
# See the NOTICE for more information.
import io
import logging
import os
import re
import sys
from gunicorn.http.message import HEADER_RE
from gunicorn.http.errors import InvalidHeader, InvalidHeaderName
from gunicorn import SERV... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 29 11:28:56 2018
@author: wdm
"""
import cv2
import numpy as np
import SimpleITK as sitk
from argparse import ArgumentParser
from matplotlib import pyplot as plt
'''
img = sitk.GetArrayFromImage(sitk.ReadImage('./data/liver_image/test/LZH-Prob.nii... |
'''
Created on Sun 04/28/2020 18:42:19
Hangman Game
@author: MarsCandyBars
'''
import random
#All functions contain pictures for each
#phase of the game
def pic1():
print("""\
______
| |
| |
|
|
|
... |
"""seed location
Revision ID: 7a620d7c68a9
Revises: ef9349c42eaa
Create Date: 2021-08-12 13:17:06.427729
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '7a620d7c68a9'
down_revision = 'ef9349c42eaa'
branch_labels = None
depends_on = None
location_table = sa.t... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-05 05:57
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('FoBusinessProcess', '0007_businessprocess_fo_client_legal_entity'),
]
operations = [
... |
import pytest
import numpy as np
import pandas as pd
from numpy.testing import assert_equal, assert_allclose
from sciparse import sampling_period, title_to_quantity, \
to_standard_quantity, frequency_bin_size, quantity_to_title, \
dict_to_string, string_to_dict, is_scalar, column_from_unit, \
... |
"""
Expand the length of the password fields in the galaxy_user table to allow for other hasing schemes
"""
from sqlalchemy import *
from migrate import *
import logging
log = logging.getLogger( __name__ )
def upgrade( migrate_engine ):
meta = MetaData( bind=migrate_engine )
user = Table( 'galaxy_user', meta... |
"""Debugging support."""
# Copyright 2021 The IREE Authors
#
# Licensed under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
from typing import Optional
import logging
import os
import shutil
import s... |
from fabric.api import run
from cbagent.collectors.libstats.remotestats import (
RemoteStats, multi_node_task)
class IOstat(RemoteStats):
METRICS = (
("rps", "r/s", 1),
("wps", "w/s", 1),
("rbps", "rkB/s", 1024), # kB -> B
("wbps", "wkB/s", 1024), # kB -> B
("avgqu... |
from manpy.simulation.imports import (
Machine,
BatchSource,
Exit,
Batch,
BatchDecomposition,
BatchReassembly,
Queue,
)
from manpy.simulation.Globals import runSimulation
# define the objects of the model
S = BatchSource(
"S",
"Source",
interArrivalTime={"Fixed": {"mean": 1.5}},... |
from math import sqrt, exp
from scipy.stats import norm
from opfu.bsm import N, bsm_price, d1, d2
def N_d(x):
return norm.pdf(x)
def delta(S0, K, r=0.01, sigma=0.1, T=1, ds=0, is_call=True):
if ds == 0:
# the theortical result
if is_call:
return N(d1(S0, K, r, sigma, T))
... |
SPLUNK_SERVICE_BLOCK = 'splunk-services'
SPLUNK_SERVICE_NAME = 'name'
SPLUNK_SERVICE_HOST = 'host'
SPLUNK_SERVICE_PORT = 'port'
SPLUNK_SERVICE_USERNAME = 'username'
SPLUNK_SERVICE_PASSWORD = 'password'
SPLUNK_QUERY_RESPONSE = 'response'
SPLUNK_QUERY_RESULTS = 'query_results'
SPLUNK_QUERY_SERVICE = 'service'
SPLUNK_QUER... |
from django.shortcuts import render,redirect,get_object_or_404
from django.http import HttpResponse
from orders.models import Order
from products.models import Product
from users.models import User
from django.core.paginator import Paginator
from django.contrib import messages
from django.conf import settings
from spee... |
import os
basedir = os.path.abspath(os.path.dirname(__file__))
class Config(object):
DEBUG = False
TESTING = False
CSRF_ENABLED = True
JWT_ALGORITHM = 'HS256'
JWT_SECRET_KEY = 'You and me knows very well it is secret'
JWT_BLACKLIST_ENABLED = True
JWT_BLACKLIST_TOKEN_CHECKS = ['access', 're... |
"""
This provides a small set of effect handlers in NumPyro that are modeled
after Pyro's `poutine <http://docs.pyro.ai/en/stable/poutine.html>`_ module.
For a tutorial on effect handlers more generally, readers are encouraged to
read `Poutine: A Guide to Programming with Effect Handlers in Pyro
<http://pyro.ai/example... |
# Copyright (c) 2011-2016 Rackspace US, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
import gym
from core.config import BaseConfig
class ClassicControlConfig(BaseConfig):
def __init__(self):
super(ClassicControlConfig, self).__init__(max_env_steps=int(2e5),
start_step=int(1e4),
lr=1e-3,
... |
from contextlib import contextmanager
import nose
from pysics import *
@contextmanager
def manage_world():
world = World((0, 0), True)
yield world
@contextmanager
def manage_static_body(world, *args, **kwargs):
body = world.create_static_body(*args, **kwargs)
yield body
world.destroy_body(body)
@... |
# pylint: disable=unused-argument
import glob
from dataclasses import asdict, dataclass
from datetime import datetime
from typing import List, Optional
import aiofiles
from redis import Redis
from sanic import Blueprint, Sanic, exceptions
from sanic.response import json
from sanic_ext import openapi
from sanic_jwt imp... |
from enum import Enum
from collections import namedtuple
def take_while(predicate, iterator):
for i in iterator:
yield i
if not predicate(i):
break
class TokenType(Enum):
TEXT = 0
VARIABLE = 1
INPUT = 2
CONDITIONAL = 3
BLOCK = 4
Token = namedtuple('Token', ['typ... |
from elasticsearch import Elasticsearch
es = Elasticsearch()
# Get all the documents
doc={"query":{"match_all":{}}}
res=es.search(index="users",body=doc,size=10)
print(res['hits']['hits'][9]['_source'])
# Get Ronald Goodman
doc={"query":{"match":{"name":"Ronald Goodman"}}}
res=es.search(index="users",body=doc,siz... |
'''
Knowledge extractor module.
'''
import artm
import inspect
import operator
import os
import numpy as np
import pandas as pd
import sys
from sklearn.manifold import MDS
from sklearn.metrics import pairwise_distances
from knowledge_extractor.utils import text_prepare
class TopicModel(object):
def __init__(sel... |
from pathlib import Path
from unittest import TestCase
from eyecite import annotate, clean_text, get_citations
class AnnotateTest(TestCase):
def test_annotate(self):
def straighten_quotes(text):
return text.replace("’", "'")
def lower_annotator(before, text, after):
retur... |
# Copyright (c) 2020 The Khronos Group Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
class Sortable():
def sort(self, var, order, sorting):
class Sorting():
def __int__(self, var, order):
self._var
self._order
self._hash
@property
def var(self):
return self._var
@property
def order(self) -> TypeQLArg.Order.ASC:
return self.ord... |
from __future__ import annotations
import pytest
@pytest.fixture
def abc(tmpdir):
a = tmpdir.join("file_a")
a.write("a text")
b = tmpdir.join("file_b")
b.write("b text")
c = tmpdir.join("file_c")
c.write("c text")
yield a, b, c
def test_multiple_files(run, abc):
a, b, c = abc
w... |
# -*- coding: utf-8 -*-
#
# Unit test for the actions module.
#
# Copyright (c) 2015 carlosperate https://github.com/carlosperate/
# Licensed under the Apache License, Version 2.0 (the "License"):
# http://www.apache.org/licenses/LICENSE-2.0
#
from __future__ import unicode_literals, absolute_import, print_function
i... |
min = 0
max = 200
for i in range(min, max):
if i % 2 == 0:
print i, |
import pytest
from mtgjson.jsonproxy import JSONProxy
@pytest.fixture
def data():
return {'foo': 'bar', 'int': 42, 'boolean': True, 'sublist': [1, 2, 3], }
@pytest.fixture
def prox(data):
return JSONProxy(data)
def test_getattr_works(prox):
assert prox.foo == 'bar'
assert prox.int == 42
asser... |
import socket
from _thread import *
import pickle
from game import Game
server = "10.11.250.207"
port = 5555
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.bind((server, port))
except socket.error as e:
str(e)
s.listen(2)
print("Waiting for a connection, Server Started")
con... |
import logging
import os
import platform
import select
import socket
import struct
import sys
import threading
import time
from weakref import proxy
from pydicom.uid import ExplicitVRLittleEndian, ImplicitVRLittleEndian, \
ExplicitVRBigEndian, UID
from pynetdicom.ACSEprovider import ACSEServ... |
#!/usr/bin/env python
"""
helpers.py
"""
import sys
import torch
import random
import numpy as np
import scipy.sparse as sp
def set_seeds(seed):
_ = random.seed(seed + 1)
_ = np.random.seed(seed + 2)
_ = torch.manual_seed(seed + 3)
_ = torch.cuda.manual_seed(seed + 4)
class SimpleEarlyStopping:
... |
#
# @lc app=leetcode.cn id=190 lang=python3
#
# [190] reverse-bits
#
None
# @lc code=end |
#!/usr/bin/env python
print "Content-type:text/html"
print
print "<html><head><title> Test URL Encoding </title></head><body>"
print "<a href=\"http://localhost:8888/test_urlencode.py?first=Jack&last=Trades\">Link</a>"
print "</body></html>" |
from simple_playgrounds.engine import Engine
from simple_playgrounds.playground.layouts import SingleRoom
from simple_playgrounds.element.elements.conditioning import ColorChanging, FlipReward
from simple_playgrounds.element.elements.activable import RewardOnActivation
from simple_playgrounds.common.timer import Perio... |
import gc
import random
import logging
import time
import sys
import os
import pandas as pd
import numpy as np
import config.constants as constants
import viz.plot_util as plot_util
def set_seed(seed=0):
random.seed(seed)
np.random.seed(seed)
def trigger_gc(logger):
"""
Trigger GC
"""
logg... |
# Object Classification with TensorRT using a pretrained EfficientNetB2 CNN on ImageNet.
# Please see References.md in this repository.
# This script will take images from camera and predict the class of object.
# Please refer to the LICENSE file in this repository.
# Licensed under the Apache License, Version 2.0 (th... |
import RPi.GPIO as GPIO
import random
import time
# import cv2 as cv
import numpy as np
rPin =26
gPin =19
bPin =13
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(rPin, GPIO.OUT)
GPIO.setup(gPin, GPIO.OUT)
GPIO.setup(bPin, GPIO.OUT)
GPIO.output(rPin, GPIO.LOW)
GPIO.output(gPin, GPIO.LOW)
GPIO.output(bPi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.