content stringlengths 5 1.05M |
|---|
from __future__ import annotations
from typing import Any, Callable, Generator, NoReturn, Union
import numpy as np
import pandas
import pytest
from pandas import Series
from pandas.api.extensions import ExtensionArray, ExtensionDtype
from pandas.tests.extension import base
import skfda
from skfda.representation.grid... |
def add(a,b):
print(f"ADDING {a} + {b}")
return a+b
def subtract(a,b):
print(f"SUBTRACTING {a} - {b}")
return a - b
def multiply(a,b):
print (f"MULTIPLYING {a} * {b}")
return a * b
def divide(a,b):
print(f"DIVIDING {a} / {b}")
return a/b
print("Let's do some math with just functions!")
a... |
#! /usr/bin/python3.7
import cv2
import time
import numpy as np
import threading
import hilens
from utils import *
# IPC摄像头处理线程
def camera_thread(camera_address, server_url):
# 初始化IPC
camera = hilens.VideoCapture(camera_address)
# 初始化模型
helmet_model_path = hilens.get_model_dir() + "helmet_templat... |
import pytest
import numpy as np
from itertools import product
# from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_allclose
from mutar import MultiLevelLasso
@pytest.mark.parametrize("fit_intercept, normalize, alpha, positive",
product([False, Tr... |
#!/usr/bin/env python
import glob
from setuptools import setup
import re
version = re.search("__version__ = '([^']+)'",
open('livewires/__init__.py').read()).group(1)
setup(
name="LiveWires",
version=version,
install_requires=['pygame'],
description="LiveWires package provides res... |
'''
Created on Aug 14, 2016
@author: rafacarv
'''
|
import json
import pytest
@pytest.fixture
def token_info_path(tmp_path):
path = tmp_path.joinpath("token.info")
path.touch()
with path.open("w") as f:
json.dump({"token_name": "my_token", "address": "my_address", "block": 0}, f)
return path
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2018-12-17 11:20
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('froide_exam', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
... |
from typing import Any, Union
import numpy as np
from torch.utils.tensorboard import SummaryWriter
from determined import tensorboard
class TorchWriter(tensorboard.MetricWriter):
"""
TorchWriter uses PyTorch file writers and summary operations to write
out tfevent files containing scalar batch metrics. ... |
import random, sys
import time
from gmpy2 import mpz, powmod, f_div, invert, is_prime, random_state, mpz_urandomb, rint_round, log2, gcd
from termcolor import colored
import matplotlib.pyplot as plt
rand = random_state(random.randrange(sys.maxsize))
# private key: (lambda, mu)
class PrivateKey(object):
def __in... |
class StreamInfo:
def __init__(
self,
started_at, ended_at, duration,
viewers, game, host, live,
preview, status_text
):
self.started_at = started_at
self.ended_at = ended_at
self.duration = duration
self.viewers = viewers
self.game = game
... |
def create_table(df):
wrap = lambda s, tag, option="": "<" + tag + " " + option + ">" + s + "</" + tag + ">"
wrap_list = lambda lst, tag: "".join(map(lambda s: wrap(str(s), tag), lst))
table = ""
table += wrap(wrap("z", "th") +
wrap("X=0","th","colspan='2'") +
wr... |
import aiohttp
import asyncio
from alpaca_trade_api.entity_v2 import BarsV2, QuotesV2, TradesV2, \
EntityList, TradeV2, QuoteV2
import pandas as pd
from alpaca_trade_api.common import URL, get_data_url
class AsyncRest:
def __init__(self,
key_id: str = None,
secret_key: str =... |
#!/usr/bin/python3
# Heavily modified for my own purposes (c) Joni Saksholm <joni@saksholm.fi>
#
# based on https://github.com/gabrielgbs97/hhc_n8i8op_mqtt
import paho.mqtt.client as mqtt
import time, re, socket, yaml, sys
from _thread import start_new_thread
from datetime import datetime
config = yaml.safe_load(open... |
#!/usr/bin/env python3
import os,sys, socket, pty
def main():
if not len(sys.argv) == 4:
print("Simple socket-based bind server; serve an arbitrary program")
print("USAGE: ./%s <prog> <ip> <port>" % sys.argv[0])
sys.exit()
self,prog,ip,port = sys.argv
sx = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
sx... |
#!/usr/bin/env python
import sys
from lib.ansible_base import AnsibleBaseRunner
__all__ = [
'AnsibleVaultRunner'
]
class AnsibleVaultRunner(AnsibleBaseRunner):
"""
Runs Ansible vault commands: encrypt/decrypt.
See: https://docs.ansible.com/playbooks_vault.html
"""
BINARY_NAME = 'ansible-vaul... |
import curses
from curses import wrapper
from curses.textpad import Textbox, rectangle
from time import sleep
def TextBoxes(stdscr):
curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLUE)
curses.init_pair(2, curses.COLOR_YELLOW, curses.COLOR_WHITE)
a1 = curses.color_pair(1)
a2 = curses.color_pair... |
from abc import ABC
__all__ = ['AnyMatrix']
class AnyMatrix(ABC):
pass
|
import json
from collections import OrderedDict
from django.template.loader import render_to_string
from django.utils.encoding import force_str
from debug_toolbar.middleware import _HTML_TYPES
from debug_toolbar.middleware import DebugToolbarMiddleware as BaseMiddleware
from debug_toolbar.toolbar import DebugToolbar
... |
from .exceptions import *
import random
class GuessAttempt(object):
def __init__(self, guess_letter, hit=False, miss=False):
self.guess_letter = guess_letter
self.hit = hit
self.miss = miss
if hit is True and miss is True:
raise InvalidGuessAttempt
def is_hit(self)... |
from PySide6.QtCore import QRect
from PySide6.QtWidgets import QLabel, QGraphicsDropShadowEffect
from Project.UI.CommonWidgets.CommonFonts import create_font
class Label(QLabel):
def __init__(self, parent, x_pos, y_pos, text, is_light=False):
super(Label, self).__init__(parent)
self.setGeometry(QR... |
from typing import List
from sqlalchemy.orm import Session
import models
import schemas
from utils import hash as hashfile
def create_user(db: Session, user: schemas.UserCreate):
# db_user = models.User(**user.dict())
user_dict = user.dict()
hash = hashfile.hash_password_passlib(user_dict["password"])
... |
import time
from flask import Flask
from flask import send_file
import redis
app = Flask(__name__)
cache = redis.Redis(host='redis', port=6379)
def get_hit_count():
retries = 5
while True:
try:
return cache.get('hits')
except redis.exceptions.ConnectionError as exc:
if ... |
from __future__ import annotations
import jax
import jax.numpy as jnp
from flax.optim.dynamic_scale import DynamicScale
import chex
def get_dtype_and_dynamic_scale(precision: int = 32) -> tuple[chex.ArrayDType, DynamicScale | None]:
"""Returns suitable dtype and dynamic_scale estimated from precision.
Args:... |
from sympy import *
import re
x = Symbol('x')
y = Symbol('y')
z = Symbol('z')
# if (tipo==1){ alert("numerador");}
# if (tipo==2){ alert("numerador raiz");}
# if (tipo==3){ alert("numerador e denominador");}
# if (tipo==4){ alert("numerador raiz e denominador");}
# if (tipo==5){ alert("numerador raiz e denominador ra... |
from flask import render_template, request, redirect, url_for, abort
from run import app
from models import Category, Pitch, User, Comment
from datetime import date
from run import db
from flask_login import login_user, logout_user, login_required, current_user
from forms import LoginForm, RegistrationForm
from run imp... |
#!/usr/bin/env python3
"""
Manage Naccess runs to calculate surface accessibility for SWISS-Model PDB downloads
"""
import argparse
import subprocess
import os
import sys
from pathlib import Path
import pandas as pd
from Bio.PDB import PDBParser
from Bio.PDB.NACCESS import process_rsa_data
from Bio.PDB.PDBIO import PD... |
#!/usr/bin/env python
"""
SHIELDS-PTM run setup script for SEP access
"""
import argparse
import glob
import os
import re
import subprocess
from contextlib import contextmanager
import numpy as np
from ptm_python import ptm_input
@contextmanager
def cd(newdir):
"""Context-managed 'change directory' """
prevd... |
from cygraphblas_ss.lib.ss import *
|
'''
337. House Robber III
The thief has found himself a new place for his thievery again.
There is only one entrance to this area, called the "root." Besides the root, each house has one and only one parent house.
After a tour, the smart thief realized that "all houses in this place forms a binary tree".
It will automa... |
# Copyright (c) 2018-2019, NVIDIA CORPORATION
# Copyright (c) 2017- Facebook, Inc
#
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above ... |
import logging
import logging.config
from envyaml import EnvYAML
from os import environ, path
logger = logging.getLogger(__name__)
CONFIG_PATH = path.join(environ.get("CONFIG_PATH", ""))
def get_config():
try:
configuration = EnvYAML(CONFIG_PATH)
return configuration
except Exception as e... |
import os
import pytest
from motor.motor_asyncio import AsyncIOMotorClient
from pymongo.errors import PyMongoError
from dbdaora import MongoDataSource, MongodbSortedSetRepository
@pytest.fixture
def fallback_data_source(event_loop):
auth = os.environ.get('MONGO_AUTH', 'mongo:mongo')
client = AsyncIOMotorCli... |
### fileSearch_1.0 ###
## Made by Gabriel Sumabat
##########
##Imports#
##########
import os
###################
## MAIN FUNCTION ##
###################
version = "1.0"
## Welcoming Message
print ("Welcome to fileSearch "+version+"! \n")
##Infite loop
while 1:
## Find Folder
pathValid... |
import numpy as np
import gym
class Environment():
def __init__(self, env_params, FLAGS):
self.env = gym.make(env_params["env_name"])
self.set_seed(FLAGS.seed)
# target range / obj range
self.target_range = self.env.env.target_range = env_params["target_range"]
self.obj_ra... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-08-20 17:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projeto101', '0011_auto_20160820_0847'),
]
operations = [
migrations.AddFiel... |
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host = "localhost"))
channel = connection.channel()
channel.exchange_declare(exchange = "logs", type = "fanout")
result = channel.queue_declare(exclusive = True)
queue_name = result.method.queue
channel.queue_bind(exchange = "logs", queue = ... |
""" Class definition for the DataTransfer object."""
from six.moves import zip
import numpy as np
from openmdao.util.array_util import to_slice
from openmdao.core.mpi_wrap import MPI
from openmdao.core.fileref import FileRef
class DataTransfer(object):
"""
An object that performs data transfer between a sou... |
import os
import sys
from .buche import *
from .repr import *
from .event import *
from .debug import *
from .repl import *
def _print_flush(x):
print(x, flush=True)
def smart_breakpoint():
if os.environ.get('BUCHE'):
os.environ['PYTHONBREAKPOINT'] = 'buche.breakpoint'
H = hrepr.H
master = Master... |
#!/usr/bin/env python3
"""
Author: banhao@gmail.com
Version: 4.8.4
Issue Date: August 14,2021
Release Note: Add "skip_buy_currency" parameter to bypass the currencies that without enough history data which cause the indicators error.
Issue Date: June 04,2021
Release Note: Dynamic reload "variable", any changes in va... |
import unittest
from unittest import TestCase
from ..youtubetools import (get_upcoming_livestreams,
get_livestreaming_details)
class Test(TestCase):
# @unittest.skip
def test_get_upcoming_livestreams(self):
channel_id = "UCJEwPH-wbOTa341mZyJ9NSw"
ls = get_upcoming_l... |
from rest_framework import routers
router = routers.DefaultRouter(trailing_slash=True)
# Add rest api there
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: penghuailiang
# @Date : 2019-10-04
"""
light cnn
用来生成256维人脸特征
"""
|
# Copyright 2021, OpenCensus Authors
#
# 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 w... |
import json
import requests
import logging
import emoji
logging.basicConfig(level=logging.INFO,
format='%(asctime)s-%(name)s-%(levelname)s-%(message)s')
logger = logging.getLogger()
with open('token.txt', 'r') as f:
TOKEN = json.load(f)['token']
GET_UPDATES = "getUpdates"
SEND_MESSAGE = "se... |
from os import environ
import warnings
from google.cloud import datastore
import yaml
def from_datastore(kind):
client = datastore.Client()
entities = list(client.query(kind=kind).fetch(limit=1))
if len(entities) == 0:
raise ValueError("Cloud Datastore has no entities with kind {}".format(
... |
# database => http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
# pip install pygeoip => this repo deprecated yet still works
# pip install dpkt => packet creation / parsing, with definitions for the basic TCP/IP protocols
# pip install scapy => packet creation / parsing
# pip install IPy =... |
from collections import OrderedDict
from hypothesis import HealthCheck, given, settings
from hypothesis.strategies \
import characters, composite, lists, sampled_from, text
from io import StringIO
from operator import add
from pytest import raises
from po import ParseError, Reader, T... |
import os
import random
import logging
from datetime import datetime
import discord
from discord.utils import get
from discord.ext import commands
from dotenv import load_dotenv
logging.basicConfig(level=logging.ERROR)
logger = logging.getLogger(__name__)
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.... |
from typing import Dict, List, Any
import torch
from conv_net import ConvNet
from ml_gym.blueprints.constructables import ModelRegistryConstructable
from ml_gym.blueprints.blue_prints import BluePrint
from ml_gym.gym.jobs import AbstractGymJob, GymJobFactory
from ml_gym.batching.batch import DatasetBatch
from dataclass... |
"""
This module help to play skyscrappers game.
"""
import doctest
def read_input(path: str) -> list:
"""
Read game board file from path.
Return list of str.
>>> read_input("check.txt")
['***21**', '412453*', '423145*', '*543215', '*35214*', '*41532*', '*2*1***']
"""
list_of_lines = []
... |
# coding: utf-8
"""
Data module
"""
import os
import sys
import random
import torch
from torchtext import data
from torchtext.data import Dataset, Iterator
import socket
from signjoey.dataset import SignTranslationDataset
from signjoey.vocabulary import (
build_vocab,
Vocabulary,
UNK_TOKEN,
EOS_TOKEN,
... |
# Copyright 2017 Google LLC
#
# 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, ... |
# Copyright 2017 Huawei Technologies Co.,LTD.
# All Rights Reserved.
#
# 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
#
# Unl... |
"""
Trains the network on the EMNIST dataset.
"""
from tqdm import tqdm
from collections import defaultdict
import numpy as np
import ocr.network as network
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt
import os
import torch as th
import torch.nn as nn
import logging
import cv2
... |
from django.core.urlresolvers import reverse
from base.tests import BaseTestCase
class AdminListViewTest(BaseTestCase):
def setUp(self):
super(AdminListViewTest, self).setUp()
self.url = reverse('admin_list_view')
def test_get(self):
response = self.client.get(self.url)
self... |
# -*- coding: utf-8 -*-
"""
# Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
#
# This file was generated and any changes will be overwritten.
"""
from __future__ import unicode_literals
from ..graph_object_base im... |
import logging
import pprint
import typing
import requests
import yaml
from .requestor import Requestor
log = logging.getLogger(__name__)
class OpenAPIKeyWord:
OPENAPI = "openapi"
INFO = "info"
SERVERS = "servers"
URL = "url"
DESCRIPTION = "description"
VARIABLES = "variables"
PATHS =... |
from app.models import CTFd_configs
from app.models import SSHTunnel_configs
######################################################################
# #
# APPLICATIVO MIDDLEWARE #
# ... |
from flask import Flask, render_template, request, jsonify
import RPi.GPIO as GPIO
import time
import os
import subprocess
import json
import sqlite3
import re
import sys
from datetime import datetime, date
app = Flask(__name__)
GPIO.setwarnings(False)
dbname='/home/pi/database/centralheating.db'
var = (time.strftim... |
#!/usr/bin/env python
from adb import *
e = evaluateJS
import thread
import time
expected = ['3', 'Map', '0', '1', '2', '1.0.0']
obtained = []
def myFilter(line):
l = filterLogcat(line)
global obtained
obtained += (l,)
return l
# if there's more than one attached device, one needs to be specified
#... |
# -*- coding: utf8 -*-
# ============LICENSE_START=======================================================
# org.onap.vvp/validation-scripts
# ===================================================================
# Copyright © 2017 AT&T Intellectual Property. All rights reserved.
# ========================================... |
# -*- coding:utf-8 -*-
# @author: lw_guo
# @time: 2020/12/9
import time
from freefree.app.libs.enums import PendingStatus
class DriftCollection:
def __init__(self, drifts, current_user_id):
"""A collection of `DriftView` objects
based on a drift record and user id
:param drifts: the record... |
from typing import List
class Solution1:
def singleNumber(self, nums: List[int]) -> int:
h = {}
for n in nums:
h[n] = h.get(n, 0) + 1
for k, v in h.items():
if v == 1:
return k
class Solution2:
# worst than Solution1
def singleNumber(self, ... |
from Tkinter import *
import Image, ImageTk, time, os
from utils import Data, abs_path
photograph = 'rad.jpg' # full path required
class rad:
xmax = 255
ymax = 100
xlabel = 'Channel Number'
ylabel = 'Count'
size = [100,100]
running = False
scale = None
def __init__(self, paren... |
# Zip - Unindo iteráveis
# Zip_longest - Itertools
from itertools import zip_longest, count
# O Zip une os Iteraveis com a mesma quantidade descartando o que sobra.
#Exemplos de ZIP
cidades = ['São Paulo','Belo horizonte','Salvador','Campinas']
estados = ['SP','MG','BA']
cid_est = zip(cidades, estados)
print(cid_est)... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-LOG 蓝鲸日志平台 available.
Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
BK-LOG 蓝鲸日志平台 is licensed under the MIT License.
License for BK-LOG 蓝鲸日志平台:
------------------------------------------------... |
from __future__ import annotations
from enum import Enum
from typing import TypeVar, Type
import pymongo as mongo
from bson.objectid import ObjectId
from .models.mongo_document_base import MongoDocumentBase, SerializableObject
class Collection(Enum):
APPLICATION_LOG = 'application_log'
WORKSPACE = "workspa... |
binaryformat = "{:04b}"
types = {"literal": 4}
def read_file(fn):
bits = []
with open(fn, "r") as fh:
data = fh.read().strip()
for crumb in [int(i, 16) for i in data]:
bits.extend([int(i) for i in binaryformat.format(crumb)])
return bits
def get_version(parsed):
versio... |
#from .inbound_handlers import *
from .opt_tests import *
from .migration import *
from .test_dbaccessors import *
from .test_all_backends import *
from corehq.apps.domain.calculations import num_mobile_users
from corehq.apps.domain.models import Domain
from corehq.apps.sms.api import send_sms_to_verified_number, send... |
import minimalmodbus
import serial
import os
import time
delay=60
instrument = minimalmodbus.Instrument('/dev/ttyUSB0',1)
instrument.serial.baudrate= 9600
instrument.serial.bytesize = 8
instrument.serial.parity = 'N'
instrument.serial.stopbits = 1
instrument.serial.timeout = 0.5
#instrument.debug = True
'''
f = open(... |
from typing import Tuple, Dict, Any
import numpy as np
import scipy.signal as scs
from mne.preprocessing.ecg import qrs_detector
def estimate_hr_and_peaks(sampling_frequency, signal):
peaks = qrs_detector(sampling_frequency, signal, filter_length='3.5s')
# noinspection PyTypeChecker
instantaneous_rates =... |
import argparse
import os
import json
from PIL import Image
from random import random
from tqdm import tqdm
def convert_page_to_columns(input_dir, train_output_dir, val_output_dir, train_ratio):
input_gt = os.path.join(input_dir, 'book_pages_tags_vertical_3.txt')
pic_gt = []
with open(input_gt, 'r', encod... |
"""
Local classifier per node approach.
Numeric and string output labels are both handled.
"""
from copy import deepcopy
import networkx as nx
import numpy as np
import ray
from sklearn.base import BaseEstimator
from sklearn.utils.validation import check_array, check_is_fitted
from hiclass import BinaryPolicy
from h... |
from settings import db
from models.user import UserModel
import sys
sys.path.append('../')
class UserRepository():
"""
ユーザーデータベースへの操作全般を扱うクラス
"""
def add(self, uid: int, access_token: str, access_token_secret: str):
"""
ユーザーを追加する
Parameters
----------
uid : i... |
import os
from pathlib import Path
from bauh.api.constants import DESKTOP_ENTRIES_DIR, CONFIG_PATH
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
WEB_PATH = '{}/.local/share/bauh/web'.format(Path.home())
INSTALLED_PATH = '{}/installed'.format(WEB_PATH)
ENV_PATH = '{}/env'.format(WEB_PATH)
NODE_DIR_PATH = '{}/n... |
from allauth.socialaccount.providers.salesforce.provider import SalesforceProvider
class CustomSalesforceProvider(SalesforceProvider):
package = "metecho.oauth2.salesforce"
def get_auth_params(self, request, action):
ret = super().get_auth_params(request, action)
# This will ensure that even ... |
# built-in
import re
import tokenize
from pathlib import Path
# external
import pytest
from typing import Union, List
# project
from flake8_length._parser import TRUNCATE_TO, get_lines_info
def to_tokens(lines: List[str]):
readline = (line.encode() for line in lines).__next__
return list(tokenize.tokenize(re... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 17 21:06:56 2017
@author: Isik
"""
import Reader_Writer as RW
from enum import Enum
CONST_CHUNK_SIZE = 1024
CONST_NUM_BITS_ASCII = 8
class lzw(RW.Reader_Writer):
""" Lempel-Ziv-Welch compression & decompression.
Properties:
FileFormat:
... |
#!/usr/bin/python
import kaldi_io
import sys
import os
from os.path import join, isdir
from numpy.random import permutation
import itertools
import keras
import numpy as np
from keras.preprocessing.sequence import pad_sequences
import queue
from threading import Thread
import random
import glob
import sys
sys.path.i... |
from django import forms
from django.forms import modelformset_factory
from .models import *
# Form for gathering recipe information when creating own recipe
class MyRecipeInfoForm(forms.ModelForm):
title = forms.CharField(widget=forms.TextInput(attrs={
'class': 'form-control',
'placeholder... |
from rest_framework.permissions import BasePermission,SAFE_METHODS
class IsUserOrReadOnly(BasePermission):
def has_object_permission(self,request,view,obj):
if request.method in SAFE_METHODS:
return True
return obj.user == request.user |
# -*- coding: utf-8 -*-
class DuobeiSDKException(Exception):
pass
class DuobeiSDKInvalidParamException(DuobeiSDKException):
pass
class DuobeiSDKServerException(DuobeiSDKException):
pass
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__version__ = '0.0.0'
###################################################################################################
# Add package directory to sys.path
###################################################################################################
import os, inspe... |
#!/usr/bin/python
import math
from olypy.oid import to_oid
import olymap.utilities as u
from olymap.utilities import get_oid, get_name, get_subkind
import pathlib
def get_email(v):
return v.get('PL', {}).get('em', [None])[0]
def get_fast_study(v):
return v.get('PL', {}).get('fs', [None])[0]
def get_firs... |
class BasePayload(object):
_name = "Default"
_code = None
_activated = False
_conf = None
_stager_path = ""
def setHandler(self, IP, PORT):
d = dict()
d['SERVER'] = IP
d['PORT'] = PORT
self.setCode(d)
def setActivated(self, status):
... |
import warnings
from pymatgen import Structure
A_PER_BOHR = 0.52917720859
A3_PER_BOHR3 = A_PER_BOHR ** 3
EV_PER_RY = 13.6056917253
class PWOutput(object):
'''
Class which parses pw.x standard output into useful physical and
simulation properties
:param stdout_string: python string (decoded) of th... |
# https://dsp.stackexchange.com/q/76560/50076 ################################
# -*- coding: utf-8 -*-
import numpy as np
from numpy.fft import ifft, ifftshift
from kymatio.scattering1d.filter_bank import morlet_1d
from ssqueezepy.visuals import plot as _plot, plotscat
def plot(*args, **kw):
if 'title' in kw:
... |
from typing import List
from starlette.responses import HTMLResponse
from starlette.websockets import WebSocket, WebSocketDisconnect
from fastapi import FastAPI, Request, Depends,Response, HTTPException, status, APIRouter
from fastapi.responses import HTMLResponse,JSONResponse
from app.db.mongodb import get_mongo_co... |
load("@bazel_tools//tools/build_defs/repo:git.bzl", "git_repository")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file")
def planner_rules_mcts_dependencies():
_maybe(
git_repository,
name = "bark_project",
commit = "9649bc11b304d42b62293352c8a4052789d553a2",... |
sum =0
n = 99
while n>0:
sum = sum+n
n=n-2
if n<10:
break
print(sum)
#----------
for x in range(101):
if x%2==0:
continue
else:
print(x)
#----------
y = 0
while True:
print(y)
y=y+1
|
# Copyright 2019 ZTE Corporation.
#
# 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 ... |
import numpy as np
import tensorflow as tf
from django.conf import settings
from tensorflow.core.framework.tensor_pb2 import TensorProto
from ..AbstractInference import AbstractInference
from skimage.transform import resize
from dicom_to_cnn.model.reader.Nifti import Nifti
from dicom_to_cnn.model.post_processing.mi... |
from PyFlow.Core import NodeBase
from PyFlow.Core.Common import *
class makeArray(NodeBase):
def __init__(self, name):
super(makeArray, self).__init__(name)
self.arrayData = self.createInputPin('data', 'AnyPin', structure=PinStructure.Array, constraint="1")
self.arrayData.enableOptions(Pin... |
import pinocchio as pio
from example_robot_data import loadSolo
import hppfcl
import numpy as np
import matplotlib.pyplot as plt
import time
from numpy.linalg import norm
from solo12_legs_collisions_utils import initSolo, addCapsule
robot, rmodel, rdata, gmodel, gdata = initSolo()
robot_config = np.zeros(robot.q0.shap... |
from abaqusGui import *
from abaqusConstants import ALL
import osutils
import os
import batchCrackDb
import sharedFunctions
import info
class BatchCrackDb_plugin(AFXForm):
"""
"""
(ID_LOAD_BUTTON,
ID_LAST) = range(AFXForm.ID_LAST, AFXForm.ID_LAST+2)
def __init__(self, owner):
"""
... |
#!/usr/bin/env python
nums = input("Enter two numbers: (num1 num2)")
num1 = int(nums.split(" ")[0])
num2 = int(nums.split(" ")[1])
if num1 > num2:
print("%d %d" % (num1,num2))
elif num1 < num2:
print("%d %d" % (num2,num1))
else:
print("num1 equal num2!")
|
"""
used to validate marketplace transaction buying goods listed
"""
class GoodsBuyerValidator:
pass
|
import re
"""
Our definition of a secure filename is:
- The filename must start with an English letters or a number (a-zA-Z0-9).
- The filename can **only** contain English letters, numbers and symbols among these four: `-_()`.
- The filename must end with a proper file extension among `.jpg`, `.jpeg`, `.png` and `.gif... |
# -*- coding: utf-8 -*-
"""
Title: Constants-File
Author: Anton ELmiger
Created: 2020-06-23
Information: all parameters of the whole image processing are stored in this module
and can be administrated and modified here
"""
######################### MODE CONSTS #########################
MODE = "vi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.