code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
from typing import List import sys from ..day import Day class Board: def __init__(self, data: List[List]) -> None: self.__data = data self.__marked_numbers = [] self.__won = False def mark(self, number): if self.__won: return self.__marked_numbers.appen...
aoc/day4/day.py
from typing import List import sys from ..day import Day class Board: def __init__(self, data: List[List]) -> None: self.__data = data self.__marked_numbers = [] self.__won = False def mark(self, number): if self.__won: return self.__marked_numbers.appen...
0.52756
0.246244
from __future__ import print_function, division import os from ._node import DirNode, LinkedDir, CyclicLinkedDir from ._path import RecursionPath, DirEntryReplacement def assert_dir_entry_equal(de1, de2): # TODO check has attributes assert de1.path == de2.path assert de1.name == de2.name for method,...
src/scantree/test_utils.py
from __future__ import print_function, division import os from ._node import DirNode, LinkedDir, CyclicLinkedDir from ._path import RecursionPath, DirEntryReplacement def assert_dir_entry_equal(de1, de2): # TODO check has attributes assert de1.path == de2.path assert de1.name == de2.name for method,...
0.2819
0.308464
r""" ===================================================== Panel Connections (:mod:`compmech.panel.connections`) ===================================================== .. currentmodule:: compmech.panel.connections Connection between panel domains. Each panel domain has its own set of Bardell approximation functions. B...
compmech/panel/connections/__init__.py
r""" ===================================================== Panel Connections (:mod:`compmech.panel.connections`) ===================================================== .. currentmodule:: compmech.panel.connections Connection between panel domains. Each panel domain has its own set of Bardell approximation functions. B...
0.861115
0.55658
import matplotlib.pyplot as plt from scipy.stats import norm def group_res(data, group_cols, statistic): """Splits dataframe into dictionary based on grouping :param data: input data to be split :param group_cols: group columns for data :param statistic: statistic to be calculated ...
resample/utility.py
import matplotlib.pyplot as plt from scipy.stats import norm def group_res(data, group_cols, statistic): """Splits dataframe into dictionary based on grouping :param data: input data to be split :param group_cols: group columns for data :param statistic: statistic to be calculated ...
0.829388
0.831383
import argparse from query_type import QueryType import socket import time import ipaddress from serializer import Serializer from deserializer import Deserializer class DNSClient: def __init__(self, params): self.name = params.name self.address = params.address self.maxRetr...
dns_client.py
import argparse from query_type import QueryType import socket import time import ipaddress from serializer import Serializer from deserializer import Deserializer class DNSClient: def __init__(self, params): self.name = params.name self.address = params.address self.maxRetr...
0.327023
0.049912
from typing import Callable, Optional import gurobipy import lightgbm as lgb import opti import pandas as pd from mbo.algorithm import Algorithm from entmoot.optimizer import Optimizer from entmoot.optimizer.gurobi_utils import get_core_gurobi_model from entmoot.space.space import Categorical, Integer, Real, Space ...
entmoot/optimizer/entmootopti.py
from typing import Callable, Optional import gurobipy import lightgbm as lgb import opti import pandas as pd from mbo.algorithm import Algorithm from entmoot.optimizer import Optimizer from entmoot.optimizer.gurobi_utils import get_core_gurobi_model from entmoot.space.space import Categorical, Integer, Real, Space ...
0.850267
0.407569
from __future__ import absolute_import, division, print_function import re import os import subprocess import tempfile import requests def to_snake_case(s, sep="_"): # type: (str, str) -> str p = r"\1" + sep + r"\2" s1 = re.sub("(.)([A-Z][a-z]+)", p, s) return re.sub("([a-z0-9])([A-Z])", p, s1).low...
spotify_tensorflow/luigi/utils.py
from __future__ import absolute_import, division, print_function import re import os import subprocess import tempfile import requests def to_snake_case(s, sep="_"): # type: (str, str) -> str p = r"\1" + sep + r"\2" s1 = re.sub("(.)([A-Z][a-z]+)", p, s) return re.sub("([a-z0-9])([A-Z])", p, s1).low...
0.663342
0.14627
from contextlib import contextmanager from crl.interactivesessions._terminalpools import _TerminalPools from ._process import ( _AsyncProcessWithoutPty, _ForegroundProcessWithoutPty, _BackgroundProcessWithoutPty, _NoCommBackgroudProcess) from ._targetproperties import _TargetProperties __copyright__ =...
src/crl/interactivesessions/_runnerintarget.py
from contextlib import contextmanager from crl.interactivesessions._terminalpools import _TerminalPools from ._process import ( _AsyncProcessWithoutPty, _ForegroundProcessWithoutPty, _BackgroundProcessWithoutPty, _NoCommBackgroudProcess) from ._targetproperties import _TargetProperties __copyright__ =...
0.650689
0.070304
from abc import ABC, abstractmethod from io import StringIO from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union, overload from pydantic import root_validator from typing_extensions import Literal from vkbottle_types.objects import ( AudioAudio, DocsDoc, MessagesForward, MessagesMessa...
vkbottle/tools/dev/mini_types/base/message.py
from abc import ABC, abstractmethod from io import StringIO from typing import TYPE_CHECKING, Any, Callable, List, Optional, Union, overload from pydantic import root_validator from typing_extensions import Literal from vkbottle_types.objects import ( AudioAudio, DocsDoc, MessagesForward, MessagesMessa...
0.846006
0.12408
from __future__ import print_function import argparse import codecs import fnmatch import os import sys import yamale import yaml def find_question_files(root_directory): """Yield all YAML files recursively.""" for root, _, files in os.walk(root_directory): for basename in fnmatch.filter(files, "[!_]...
spec/validate_question.py
from __future__ import print_function import argparse import codecs import fnmatch import os import sys import yamale import yaml def find_question_files(root_directory): """Yield all YAML files recursively.""" for root, _, files in os.walk(root_directory): for basename in fnmatch.filter(files, "[!_]...
0.434941
0.179981
from collections import namedtuple import numpy as np from roifile import ImagejRoi from skimage.draw import polygon, polygon_perimeter from tifffile import TiffFile, TiffWriter from . import REGION_BACKGROUND, REGION_BORDER, REGION_FOREGROUND TiffWriter = TiffWriter TiffInfo = namedtuple('TiffInfo', 'pages, w, h, ...
junn/io/tiffmasks.py
from collections import namedtuple import numpy as np from roifile import ImagejRoi from skimage.draw import polygon, polygon_perimeter from tifffile import TiffFile, TiffWriter from . import REGION_BACKGROUND, REGION_BORDER, REGION_FOREGROUND TiffWriter = TiffWriter TiffInfo = namedtuple('TiffInfo', 'pages, w, h, ...
0.70202
0.336331
import sys, os, xml.sax, re from xml.dom.minidom import parse, parseString, getDOMImplementation SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) SCRIPT_NAME = os.path.splitext(os.path.split(__file__)[1])[0] DESCRIPTION = 'Merge two idlak output files to have matching initial / end breaks' FRAMESHIFT=0.005 # ...
idlak-egs/tts_tangle_arctic/s2/local/merge_breaks.py
import sys, os, xml.sax, re from xml.dom.minidom import parse, parseString, getDOMImplementation SCRIPT_DIR = os.path.dirname(os.path.realpath(__file__)) SCRIPT_NAME = os.path.splitext(os.path.split(__file__)[1])[0] DESCRIPTION = 'Merge two idlak output files to have matching initial / end breaks' FRAMESHIFT=0.005 # ...
0.126326
0.088939
from __future__ import absolute_import import os import vcr import unittest from hatchbuck.api import HatchbuckAPI, HatchbuckAPIAuthenticationError class TestSearchContacts(unittest.TestCase): def setUp(self): # Fake key can be used with existing cassettes self.test_api_key = os.environ.get("HATC...
tests/test_search_contacts.py
from __future__ import absolute_import import os import vcr import unittest from hatchbuck.api import HatchbuckAPI, HatchbuckAPIAuthenticationError class TestSearchContacts(unittest.TestCase): def setUp(self): # Fake key can be used with existing cassettes self.test_api_key = os.environ.get("HATC...
0.500732
0.132318
import gzip import json from typing import cast from unittest.mock import Mock import pytest from pytest_wdl.config import UserConfiguration from pytest_wdl.core import ( DefaultDataFile, DataDirs, DataManager, DataResolver, create_data_file ) from pytest_wdl.localizers import LinkLocalizer, UrlLocalizer from py...
tests/test_core.py
import gzip import json from typing import cast from unittest.mock import Mock import pytest from pytest_wdl.config import UserConfiguration from pytest_wdl.core import ( DefaultDataFile, DataDirs, DataManager, DataResolver, create_data_file ) from pytest_wdl.localizers import LinkLocalizer, UrlLocalizer from py...
0.67822
0.314129
import os import glob import shutil import tarfile import argparse import mapred_utils as util if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--folder', default=os.getcwd(), help='The "save folder" of the map/reduce task being backed up') parser.add_argument('--name', ...
external_packages/matlab/non_default_packages/Gaussian_Process/deck/+dk/+mapred/python/mapred_backup.py
import os import glob import shutil import tarfile import argparse import mapred_utils as util if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--folder', default=os.getcwd(), help='The "save folder" of the map/reduce task being backed up') parser.add_argument('--name', ...
0.099284
0.077518
import requests import pyexcel as pe from bs4 import BeautifulSoup from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import csv import re from datetime import datetime class Text: def __init__(self, body): self.body = body def calculate_sentiment(self, analyzer): vs = analyz...
scraping.py
import requests import pyexcel as pe from bs4 import BeautifulSoup from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer import csv import re from datetime import datetime class Text: def __init__(self, body): self.body = body def calculate_sentiment(self, analyzer): vs = analyz...
0.299515
0.220384
import dash_core_components as dcc import dash_html_components as html def render(title="Earnings Overview", xl_size=8, lg_size=7, dropdown_id="dropdownMenuLink", graph=dcc.Graph()): return html.Div( className=f'col-xl-{xl_size} col-lg-{lg_size}', children=html.Div( className='card sha...
SB_Admin_2/templates/layouts/graph_wrapper.py
import dash_core_components as dcc import dash_html_components as html def render(title="Earnings Overview", xl_size=8, lg_size=7, dropdown_id="dropdownMenuLink", graph=dcc.Graph()): return html.Div( className=f'col-xl-{xl_size} col-lg-{lg_size}', children=html.Div( className='card sha...
0.505859
0.0686
import typing, math, os import multiprocessing, tempfile, pickle def divideChunks(lis: typing.Iterable, n_size: int) -> typing.Iterator: for i in range(0, len(lis), n_size): yield lis[i:i + n_size] def inferWorkers() -> int: workers = multiprocessing.cpu_count() - 1 return workers def lisJobParallel(f...
b64ImConverter/multiProcess.py
import typing, math, os import multiprocessing, tempfile, pickle def divideChunks(lis: typing.Iterable, n_size: int) -> typing.Iterator: for i in range(0, len(lis), n_size): yield lis[i:i + n_size] def inferWorkers() -> int: workers = multiprocessing.cpu_count() - 1 return workers def lisJobParallel(f...
0.363082
0.283639
from .conf import settings import urllib.request import urllib.error import logging import sys import time log = logging.getLogger('svp_integration') def list_request(path): try: response = urllib.request.urlopen(settings.svp_url + "?" + path) return response.read().decode('utf-8').replace('\r\n',...
plex_mpv_shim/svp_integration.py
from .conf import settings import urllib.request import urllib.error import logging import sys import time log = logging.getLogger('svp_integration') def list_request(path): try: response = urllib.request.urlopen(settings.svp_url + "?" + path) return response.read().decode('utf-8').replace('\r\n',...
0.181372
0.071106
import sys import numpy as np import pylab as pl import scipy.signal from UFL.common import DataInputOutput, DataNormalization, Visualization from UFL.PCA import PCA from UFL.SoftICA import SoftICA from UFL.Softmax import Softmax def convolveAndPool(images, W, poolDim): ''' Returns the convolution of the features gi...
examples/SelfTaughtLearning.py
import sys import numpy as np import pylab as pl import scipy.signal from UFL.common import DataInputOutput, DataNormalization, Visualization from UFL.PCA import PCA from UFL.SoftICA import SoftICA from UFL.Softmax import Softmax def convolveAndPool(images, W, poolDim): ''' Returns the convolution of the features gi...
0.534612
0.601974
import numpy as np import pyqtgraph as pg import time import csv import sys import thorlabs_apt as apt from PyQt5.Qsci import QsciScintilla, QsciLexerPython from spyre import Spyrelet, Task, Element from spyre.widgets.task import TaskWidget from spyre.plotting import LinePlotWidget from spyre.widgets.rangespace impor...
spyre/spyre/spyrelets/fiberpulling_spyrelet.py
import numpy as np import pyqtgraph as pg import time import csv import sys import thorlabs_apt as apt from PyQt5.Qsci import QsciScintilla, QsciLexerPython from spyre import Spyrelet, Task, Element from spyre.widgets.task import TaskWidget from spyre.plotting import LinePlotWidget from spyre.widgets.rangespace impor...
0.222785
0.242441
import unittest from pkg_resources import resource_filename import numpy as np try: import fitsio missing_fitsio = False except ImportError: missing_fitsio = True from desisim import lya_spectra class TestLya(unittest.TestCase): @classmethod def setUpClass(cls): cls.infile = resource...
py/desisim/test/test_lya.py
import unittest from pkg_resources import resource_filename import numpy as np try: import fitsio missing_fitsio = False except ImportError: missing_fitsio = True from desisim import lya_spectra class TestLya(unittest.TestCase): @classmethod def setUpClass(cls): cls.infile = resource...
0.561455
0.449695
import numpy as np import ref from .img import Transform def getPreds(hm): assert len(hm.shape) == 4, 'Input must be a 4-D tensor' res = hm.shape[2] hm = hm.reshape(hm.shape[0], hm.shape[1], hm.shape[2] * hm.shape[3]) idx = np.argmax(hm, axis = 2) preds = np.zeros((hm.shape[0], hm.shape[1], 2)) ...
utils/eval.py
import numpy as np import ref from .img import Transform def getPreds(hm): assert len(hm.shape) == 4, 'Input must be a 4-D tensor' res = hm.shape[2] hm = hm.reshape(hm.shape[0], hm.shape[1], hm.shape[2] * hm.shape[3]) idx = np.argmax(hm, axis = 2) preds = np.zeros((hm.shape[0], hm.shape[1], 2)) ...
0.356671
0.634685
import requests from ..classes import Champion class DataDragonAPI: def __init__(self): self.latest = self.get_versions()[0] def get_versions(self): """ Get a list of all versions. :rtype: List[str] """ list = requests.get('https://ddragon.leagueoflegends.com/...
riot_apy/apis/DataDragonAPI.py
import requests from ..classes import Champion class DataDragonAPI: def __init__(self): self.latest = self.get_versions()[0] def get_versions(self): """ Get a list of all versions. :rtype: List[str] """ list = requests.get('https://ddragon.leagueoflegends.com/...
0.611034
0.2227
AppId = "8c6cc7b45d2568fb668be6e05b6e5a3b" # locale parameter(url postfix) LocaleParam = "&gcc=KR&locale=ko_KR" PlatformPCParam = "&platformType=PC" # API: Post Info API # APIPostUrl("POST-ID"): str # APIPostReferer("POST-ID"): dict def APIPostUrl(post): return "https://www.vlive.tv/globalv-web/vam-web/post/v1....
vlivepy/variables.py
AppId = "8c6cc7b45d2568fb668be6e05b6e5a3b" # locale parameter(url postfix) LocaleParam = "&gcc=KR&locale=ko_KR" PlatformPCParam = "&platformType=PC" # API: Post Info API # APIPostUrl("POST-ID"): str # APIPostReferer("POST-ID"): dict def APIPostUrl(post): return "https://www.vlive.tv/globalv-web/vam-web/post/v1....
0.417271
0.117826
import json import os import time from traceback import print_exc from typing import TypedDict, cast import click from flask import Flask, redirect, url_for, session from flask.cli import with_appcontext from flask.wrappers import Response from flask_dance.contrib.google import make_google_blueprint from flask_dance.co...
server.py
import json import os import time from traceback import print_exc from typing import TypedDict, cast import click from flask import Flask, redirect, url_for, session from flask.cli import with_appcontext from flask.wrappers import Response from flask_dance.contrib.google import make_google_blueprint from flask_dance.co...
0.423577
0.054651
from abc import ABC, abstractmethod from functools import lru_cache from typing import Iterator class Team(ABC): """Abstract interface for some teams.""" pass class Teams(ABC): """Abstract interface for some teams.""" @abstractmethod def __next__(self) -> Team: pass @abstractmetho...
stats/league/teams.py
from abc import ABC, abstractmethod from functools import lru_cache from typing import Iterator class Team(ABC): """Abstract interface for some teams.""" pass class Teams(ABC): """Abstract interface for some teams.""" @abstractmethod def __next__(self) -> Team: pass @abstractmetho...
0.872863
0.128635
import serial import time import socket import struct import msvcrt ser = serial.Serial('com7', 9600, timeout = 0.5) UDP_IP = "10.6.3.1" UDP_PORT = 5005 #sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #sock.bind((UDP_IP, UDP_PORT)) #sock.listen(1) #conn, addr = sock.accept() #print "Connected by: ", addr ...
gcs_code.py
import serial import time import socket import struct import msvcrt ser = serial.Serial('com7', 9600, timeout = 0.5) UDP_IP = "10.6.3.1" UDP_PORT = 5005 #sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #sock.bind((UDP_IP, UDP_PORT)) #sock.listen(1) #conn, addr = sock.accept() #print "Connected by: ", addr ...
0.05634
0.072834
#Scraps a page from Amazon website and collects all the product related information from the website and store them in a data frame. import pandas as pd import numpy as np import re from urllib.request import urlopen from bs4 import BeautifulSoup import requests no_pages = 1 def get_data(pageNo): r = re...
PYTHON/web_scraping_Amazon.py
#Scraps a page from Amazon website and collects all the product related information from the website and store them in a data frame. import pandas as pd import numpy as np import re from urllib.request import urlopen from bs4 import BeautifulSoup import requests no_pages = 1 def get_data(pageNo): r = re...
0.1254
0.247879
import os import shutil import sys import tinify import settings SUPPORTED_FORMATS = ('jpg', 'jpeg', 'png') def create_dirs(raw_images_dir=settings.USER_INPUT_PATH, save_dir=settings.USER_OUTPUT_PATH): """Creates the necessary directories if they do not exist. Args raw_images_dir ...
image_optimizer.py
import os import shutil import sys import tinify import settings SUPPORTED_FORMATS = ('jpg', 'jpeg', 'png') def create_dirs(raw_images_dir=settings.USER_INPUT_PATH, save_dir=settings.USER_OUTPUT_PATH): """Creates the necessary directories if they do not exist. Args raw_images_dir ...
0.375936
0.177829
from libqtile.config import Group, Key from libqtile.lazy import lazy from variables.commands import Commands, mod # A list of available commands that can be bound to keys can be found # at https://docs.qtile.org/en/latest/manual/config/lazy.html # Qtile keyboard shortcuts keys = [ # Qtile Key([mod, 'control'...
qtile/modules/shortcuts.py
from libqtile.config import Group, Key from libqtile.lazy import lazy from variables.commands import Commands, mod # A list of available commands that can be bound to keys can be found # at https://docs.qtile.org/en/latest/manual/config/lazy.html # Qtile keyboard shortcuts keys = [ # Qtile Key([mod, 'control'...
0.556641
0.184694
from __future__ import unicode_literals from django.db import models, migrations import msgvis.apps.enhance.fields class Migration(migrations.Migration): dependencies = [ ('corpus', '0014_auto_20150221_0240'), ] operations = [ migrations.CreateModel( name='Dictionary', ...
msgvis/apps/enhance/migrations/0001_initial.py
from __future__ import unicode_literals from django.db import models, migrations import msgvis.apps.enhance.fields class Migration(migrations.Migration): dependencies = [ ('corpus', '0014_auto_20150221_0240'), ] operations = [ migrations.CreateModel( name='Dictionary', ...
0.638948
0.171859
import unittest import numpy as np class ExtendedTestCase(unittest.TestCase): # pylint: disable=invalid-name """ Extended ``TestCase`` class of the ``unittest`` module. """ def assertAlmostEqualArrays(self, obtained_array, expected_array): """ Assert that two NumPy arrays are elem...
mcdm/tests/helper_testing.py
import unittest import numpy as np class ExtendedTestCase(unittest.TestCase): # pylint: disable=invalid-name """ Extended ``TestCase`` class of the ``unittest`` module. """ def assertAlmostEqualArrays(self, obtained_array, expected_array): """ Assert that two NumPy arrays are elem...
0.734596
0.77223
from __future__ import ( division, absolute_import, print_function, unicode_literals, ) from builtins import * # noqa from future.builtins.disabled import * # noqa from magic_constraints.exception import MagicSyntaxError, MagicTypeError def transform_to_slots(constraints_package, *args, **kwarg...
magic_constraints/argument.py
from __future__ import ( division, absolute_import, print_function, unicode_literals, ) from builtins import * # noqa from future.builtins.disabled import * # noqa from magic_constraints.exception import MagicSyntaxError, MagicTypeError def transform_to_slots(constraints_package, *args, **kwarg...
0.624179
0.208884
from random import * # Generates exact cover instance for target length n with t subsets # Returns (s, w) where s is a t-length list of subsets and w is a l length list of witness indices of s def generate(n, l, t): assert t >= n assert 1 <= l <= n target = list(range(1,n+1)) witness = [] # Randoml...
witnessencrypt/ecigen.py
from random import * # Generates exact cover instance for target length n with t subsets # Returns (s, w) where s is a t-length list of subsets and w is a l length list of witness indices of s def generate(n, l, t): assert t >= n assert 1 <= l <= n target = list(range(1,n+1)) witness = [] # Randoml...
0.619011
0.394434
import logging import re from unittest.mock import patch import pytest from ebook_homebrew.exceptions import InvalidNumberParameterTypeError, \ TargetSrcFileNotFoundError, ChangeFileNameOSError, InvalidImageParameterTypeError from ebook_homebrew.rename import ChangeFilename _logger = logging.getLogger(name=__nam...
tests/ut/test_rename.py
import logging import re from unittest.mock import patch import pytest from ebook_homebrew.exceptions import InvalidNumberParameterTypeError, \ TargetSrcFileNotFoundError, ChangeFileNameOSError, InvalidImageParameterTypeError from ebook_homebrew.rename import ChangeFilename _logger = logging.getLogger(name=__nam...
0.510008
0.476336
import datetime import os import django.utils.timezone from django.contrib.auth.models import User from django.core.validators import RegexValidator from django.db import models from django.db.models import Q from django.urls import reverse from django.utils.translation import gettext_lazy as _ class Semester(models...
dashboard/models.py
import datetime import os import django.utils.timezone from django.contrib.auth.models import User from django.core.validators import RegexValidator from django.db import models from django.db.models import Q from django.urls import reverse from django.utils.translation import gettext_lazy as _ class Semester(models...
0.235988
0.10217
import sys sys.path.append('./py') from tests.test import * from tests.random import * from ga import GA from multivector import MultiVector ga = GA(3) assert ga.n == 3 x = 4 + 3*ga[1] + 4*ga[2] + 5*ga[1,2] y = 3 + 2*ga[1] + 3*ga[2] + 4*ga[1,2] z = 10 + 16*ga[1] + 26*ga[2] + 32*ga[1,2] assert x*y == z ga2 = GA(2...
test-ga.py
import sys sys.path.append('./py') from tests.test import * from tests.random import * from ga import GA from multivector import MultiVector ga = GA(3) assert ga.n == 3 x = 4 + 3*ga[1] + 4*ga[2] + 5*ga[1,2] y = 3 + 2*ga[1] + 3*ga[2] + 4*ga[1,2] z = 10 + 16*ga[1] + 26*ga[2] + 32*ga[1,2] assert x*y == z ga2 = GA(2...
0.177312
0.511412
import weakref class Message: def __init__(self, message_id, content, metadata): self.message_id = message_id self.content = content self.metadata = metadata class MessagingDriver: def __init__(self): self._finalizer = weakref.finalize(self, self.close_connection) def de...
melange/messaging/messaging_driver.py
import weakref class Message: def __init__(self, message_id, content, metadata): self.message_id = message_id self.content = content self.metadata = metadata class MessagingDriver: def __init__(self): self._finalizer = weakref.finalize(self, self.close_connection) def de...
0.791821
0.301285
import cv2 import albumentations as A from typing import Any from typing import Tuple from typing import Union from typing import Optional from albumentations.pytorch import ToTensorV2 from .general import ToRGB from .general import ToGray from .general import BatchWrapper from .....data import Transforms from ........
cflearn/api/cv/data/transforms/A.py
import cv2 import albumentations as A from typing import Any from typing import Tuple from typing import Union from typing import Optional from albumentations.pytorch import ToTensorV2 from .general import ToRGB from .general import ToGray from .general import BatchWrapper from .....data import Transforms from ........
0.903796
0.216053
# debug import hTools2 reload(hTools2) if hTools2.DEBUG: import hTools2.modules.fontutils reload(hTools2.modules.fontutils) # imports from vanilla import * try: from mojo.roboFont import AllFonts, CurrentFont, CurrentGlyph except: from robofab.world import AllFonts, CurrentFont, CurrentGlyph from...
Lib/hTools2/dialogs/glyph/switch_glyph.py
# debug import hTools2 reload(hTools2) if hTools2.DEBUG: import hTools2.modules.fontutils reload(hTools2.modules.fontutils) # imports from vanilla import * try: from mojo.roboFont import AllFonts, CurrentFont, CurrentGlyph except: from robofab.world import AllFonts, CurrentFont, CurrentGlyph from...
0.360602
0.078254
# Import all packages import tensorflow as tf class QmixNet(tf.keras.Model): def __init__(self, matrix_dims, name='Qmix', **kwargs): super(QmixNet, self).__init__(name=name, **kwargs) q_init = tf.zeros_initializer() self.q_1 = tf.Variable(initial_value=q_init(shape=(matrix_dims[0],), dtype='float32'),...
matrix_game/q_mix.py
# Import all packages import tensorflow as tf class QmixNet(tf.keras.Model): def __init__(self, matrix_dims, name='Qmix', **kwargs): super(QmixNet, self).__init__(name=name, **kwargs) q_init = tf.zeros_initializer() self.q_1 = tf.Variable(initial_value=q_init(shape=(matrix_dims[0],), dtype='float32'),...
0.885186
0.451387
import argparse import os import scipy.misc import numpy as np from ada_rendering import pose2image import tensorflow as tf from pdb import set_trace as st parser = argparse.ArgumentParser(description='') parser.add_argument('--dataset_name', dest='dataset_name', default='facades', help='name of the dataset') parser....
main.py
import argparse import os import scipy.misc import numpy as np from ada_rendering import pose2image import tensorflow as tf from pdb import set_trace as st parser = argparse.ArgumentParser(description='') parser.add_argument('--dataset_name', dest='dataset_name', default='facades', help='name of the dataset') parser....
0.498291
0.085327
from .common import * mod = Blueprint('submission', __name__) class SubmitForm(FlaskForm): problem_id = IntegerField('Problem ID', [InputRequired('This field is required.')]) language_id = SelectField('Language', [InputRequired('This field is required.')], coerce=int) code = TextAreaField('Compile Comman...
web/codepass_web/views/submission.py
from .common import * mod = Blueprint('submission', __name__) class SubmitForm(FlaskForm): problem_id = IntegerField('Problem ID', [InputRequired('This field is required.')]) language_id = SelectField('Language', [InputRequired('This field is required.')], coerce=int) code = TextAreaField('Compile Comman...
0.322099
0.083404
import argparse import datetime import hashlib import os import os.path as osp import uuid import torch import yaml from torch.optim.lr_scheduler import MultiStepLR from torch.utils.data import DataLoader import torchfcn from cmu_airlab.datasets.dataset_air_lab import AirLabClassSegBase from torchfcn.models.fcn_util...
train_airlab_data.py
import argparse import datetime import hashlib import os import os.path as osp import uuid import torch import yaml from torch.optim.lr_scheduler import MultiStepLR from torch.utils.data import DataLoader import torchfcn from cmu_airlab.datasets.dataset_air_lab import AirLabClassSegBase from torchfcn.models.fcn_util...
0.667906
0.225246
import os import time from mindspore.common import set_seed from src.dataset import data_to_mindrecord_byte_image from src.model_utils.config import config set_seed(1) rank = 0 device_num = 1 def generate_coco_mindrecord(): """ train_fasterrcnn_ """ # It will generate mindrecord file in config.mindrecord_...
tests/st/fl/cross_silo_faster_rcnn/generate_mindrecord.py
import os import time from mindspore.common import set_seed from src.dataset import data_to_mindrecord_byte_image from src.model_utils.config import config set_seed(1) rank = 0 device_num = 1 def generate_coco_mindrecord(): """ train_fasterrcnn_ """ # It will generate mindrecord file in config.mindrecord_...
0.181263
0.117699
import cv2 import glob import keras import numpy as np import pandas as pd from keras import backend as K from keras.layers import MaxPooling2D, Conv2D, Flatten, Dense, Input, AlphaDropout, Dropout from keras.models import Model from settings import IMAGE_SIZE df = pd.read_pickle('../data/all_obs.pkl', compression='g...
process/3_train_nn.py
import cv2 import glob import keras import numpy as np import pandas as pd from keras import backend as K from keras.layers import MaxPooling2D, Conv2D, Flatten, Dense, Input, AlphaDropout, Dropout from keras.models import Model from settings import IMAGE_SIZE df = pd.read_pickle('../data/all_obs.pkl', compression='g...
0.747524
0.443359
import json from invenio_indexer.api import RecordIndexer from invenio_pidstore.models import PersistentIdentifier from oarepo_records_draft import current_drafts from sample.config import SAMPLE_DRAFT_PID_TYPE from sample.record import SampleDraftRecord def test_search_records(app, db, client, community): ass...
tests/test_search.py
import json from invenio_indexer.api import RecordIndexer from invenio_pidstore.models import PersistentIdentifier from oarepo_records_draft import current_drafts from sample.config import SAMPLE_DRAFT_PID_TYPE from sample.record import SampleDraftRecord def test_search_records(app, db, client, community): ass...
0.389663
0.266047
import os import numpy as np import torch import shutil import torchvision.transforms as transforms from torch.autograd import Variable class AvgrageMeter(object): def __init__(self): self.reset() def reset(self): self.avg = 0 self.sum = 0 self.cnt = 0 def update(self, val, n=1): self.sum...
autoPyTorch/components/networks/image/darts/utils.py
import os import numpy as np import torch import shutil import torchvision.transforms as transforms from torch.autograd import Variable class AvgrageMeter(object): def __init__(self): self.reset() def reset(self): self.avg = 0 self.sum = 0 self.cnt = 0 def update(self, val, n=1): self.sum...
0.615319
0.421076
import argparse import math import progressbar import time import h5py import numpy as np DSET_NAME = 'dset' def _calc_batches(count, batch_size): return int(math.ceil(count / float(batch_size))) def write(filename, batched=False, batch_size=32): data_count = 10000 data_shape = (3, 256, 256) data...
main.py
import argparse import math import progressbar import time import h5py import numpy as np DSET_NAME = 'dset' def _calc_batches(count, batch_size): return int(math.ceil(count / float(batch_size))) def write(filename, batched=False, batch_size=32): data_count = 10000 data_shape = (3, 256, 256) data...
0.424651
0.225513
import json import os from pathlib import Path import numpy as np import torch from logzero import logger from showcase import constants _root_dir = os.path.expanduser('~/.config/showcase') def get_dataset_root(create_directory=True): if create_directory: try: os.makedirs(_root_dir, exist_o...
showcase/utils/subfuncs.py
import json import os from pathlib import Path import numpy as np import torch from logzero import logger from showcase import constants _root_dir = os.path.expanduser('~/.config/showcase') def get_dataset_root(create_directory=True): if create_directory: try: os.makedirs(_root_dir, exist_o...
0.29747
0.145449
from nonebot import ( CommandSession, IntentCommand, NLPSession, on_command, on_natural_language, permission ) from coolqbot import bot @on_command( 'whoami', aliases={'我是谁'}, permission=permission.GROUP, only_to_me=False ) async def whoami(session: CommandSession): msg = await session.bot.get_group_...
plugins_bak/basic.py
from nonebot import ( CommandSession, IntentCommand, NLPSession, on_command, on_natural_language, permission ) from coolqbot import bot @on_command( 'whoami', aliases={'我是谁'}, permission=permission.GROUP, only_to_me=False ) async def whoami(session: CommandSession): msg = await session.bot.get_group_...
0.246806
0.066266
from prim import Parser, syntax_tree, fmap, lift, mzero from operator import and_, or_ from state import ( isParseError, isParseSuccess, parseSuccessTree, setParseSuccessTree, mergeErrorsMany, inputConsumed ) def _sequence(*parsers): '''same as 'sequence', but less efficient (due to ...
parsefunc/combinators.py
from prim import Parser, syntax_tree, fmap, lift, mzero from operator import and_, or_ from state import ( isParseError, isParseSuccess, parseSuccessTree, setParseSuccessTree, mergeErrorsMany, inputConsumed ) def _sequence(*parsers): '''same as 'sequence', but less efficient (due to ...
0.414188
0.449332
import discord from discord.ext import commands from utils import MyContext async def can_mute(ctx: MyContext) -> bool: """Check if someone can mute""" if ctx.bot.database_online: return await ctx.bot.get_cog("Servers").staff_finder(ctx.author, "mute") else: return ctx.channel.permissions_...
fcts/checks.py
import discord from discord.ext import commands from utils import MyContext async def can_mute(ctx: MyContext) -> bool: """Check if someone can mute""" if ctx.bot.database_online: return await ctx.bot.get_cog("Servers").staff_finder(ctx.author, "mute") else: return ctx.channel.permissions_...
0.463201
0.168686
import sys import chardet import argparse from pyflowchart.flowchart import Flowchart def detect_decode(file_content: bytes) -> str: """detect_decode detect the encoding of file_content, then decode file_content on the detected encoding. If the confidence of detect result is less then 0.9, the UTF-...
pyflowchart/__main__.py
import sys import chardet import argparse from pyflowchart.flowchart import Flowchart def detect_decode(file_content: bytes) -> str: """detect_decode detect the encoding of file_content, then decode file_content on the detected encoding. If the confidence of detect result is less then 0.9, the UTF-...
0.441673
0.254787
import json from datetime import date, datetime import sqlalchemy.types as types from dbbase import DB db = DB(config=":memory:") status_codes = [ [0, "New"], [1, "Active"], [2, "Suspended"], [3, "Inactive"], ] class StatusCodes(types.TypeDecorator): """ Status codes are entered as strings ...
examples/table_documentation.py
import json from datetime import date, datetime import sqlalchemy.types as types from dbbase import DB db = DB(config=":memory:") status_codes = [ [0, "New"], [1, "Active"], [2, "Suspended"], [3, "Inactive"], ] class StatusCodes(types.TypeDecorator): """ Status codes are entered as strings ...
0.652574
0.275978
import argparse import os import pathlib import subprocess def error(msg): print(msg) exit(1) def is_windows(): if os.name == 'nt': return True else: return False def get_shader_list(project_path, asset_platform, shader_type, shader_platform, shadergen_path): """ Gets the sha...
scripts/bundler/get_shader_list.py
import argparse import os import pathlib import subprocess def error(msg): print(msg) exit(1) def is_windows(): if os.name == 'nt': return True else: return False def get_shader_list(project_path, asset_platform, shader_type, shader_platform, shadergen_path): """ Gets the sha...
0.321993
0.071429
import logging from getpass import getpass from argparse import ArgumentParser from configparser import SafeConfigParser import concurrent.futures import os import uuid import datetime import asyncio from urllib.parse import urljoin import slixmpp import pyinotify class EventHandler(pyinotify.ProcessEvent): def ...
imgnotifybot.py
import logging from getpass import getpass from argparse import ArgumentParser from configparser import SafeConfigParser import concurrent.futures import os import uuid import datetime import asyncio from urllib.parse import urljoin import slixmpp import pyinotify class EventHandler(pyinotify.ProcessEvent): def ...
0.50293
0.066327
def axisymmetric_file(geometry_type, geometry_parameters, Nrank, wavelength, index, index_m, kb=None, conducting=False, Nparam=1, use_ds=True, complex_plane=True, eps_z_re_im=0.95, Nint=200): """Create input file for axisymmetric particles Arguments: geometry_type (int) choos...
miepy/tmatrix/axisymmetric_file.py
def axisymmetric_file(geometry_type, geometry_parameters, Nrank, wavelength, index, index_m, kb=None, conducting=False, Nparam=1, use_ds=True, complex_plane=True, eps_z_re_im=0.95, Nint=200): """Create input file for axisymmetric particles Arguments: geometry_type (int) choos...
0.809351
0.596609
import argparse import datetime import json import os import pdfminer.high_level import sys import wget import sys def query_yes_no(question, default="yes"): valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "...
mkparser.py
import argparse import datetime import json import os import pdfminer.high_level import sys import wget import sys def query_yes_no(question, default="yes"): valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False} if default is None: prompt = " [y/n] " elif default == "...
0.244814
0.091423
import time import sched import threading from synapse.config import config from synapse.logger import logger @logger class SynSched(threading.Thread): def __init__(self): self.logger.debug("Initializing the scheduler...") threading.Thread.__init__(self, name="SCHEDULER") # Start the sc...
synapse/scheduler.py
import time import sched import threading from synapse.config import config from synapse.logger import logger @logger class SynSched(threading.Thread): def __init__(self): self.logger.debug("Initializing the scheduler...") threading.Thread.__init__(self, name="SCHEDULER") # Start the sc...
0.447702
0.075927
from typing import Dict, Callable, Union import random from ..calc.combat_data import AttackData from ..calc import stats def _(_: AttackData) -> None: pass def fe7_silencer(atk: AttackData) -> None: """ With a crit/2% chance to activate, deals damage equal to the opponent's remaining HP. Prevents o...
FEArena/feaapi/api/skills/before_attack.py
from typing import Dict, Callable, Union import random from ..calc.combat_data import AttackData from ..calc import stats def _(_: AttackData) -> None: pass def fe7_silencer(atk: AttackData) -> None: """ With a crit/2% chance to activate, deals damage equal to the opponent's remaining HP. Prevents o...
0.67405
0.4436
import pandas as pd import numpy as np import tensorflow as tf class SlidingWindow(tf.keras.utils.Sequence): def __init__( self, df: pd.DataFrame, window_size: int, target_features: list[str], feature_names: list[str] = None, horizon_size: int = 1, jump: in...
windpower/utils/tabularize.py
import pandas as pd import numpy as np import tensorflow as tf class SlidingWindow(tf.keras.utils.Sequence): def __init__( self, df: pd.DataFrame, window_size: int, target_features: list[str], feature_names: list[str] = None, horizon_size: int = 1, jump: in...
0.778776
0.400955
# XKCD password generator import argparse import collections import os.path import random # Parse the command line options. parser = argparse.ArgumentParser(description="XKCD password generator https://xkcd.com/936/") parser.add_argument("-d", "--dictionary", default="en", help="Dictionary to use") parser.add_argume...
network/xkcd/xkcd.py
# XKCD password generator import argparse import collections import os.path import random # Parse the command line options. parser = argparse.ArgumentParser(description="XKCD password generator https://xkcd.com/936/") parser.add_argument("-d", "--dictionary", default="en", help="Dictionary to use") parser.add_argume...
0.502686
0.064359
import numpy as np class Distance_metrics: """ Calculate distance between each corresponding points of two arrays using different distance metrics """ def Eucledian_Distance(X1,X2): """" Returns the list of eucledian distance between two corresponding points of two ...
MLlib/distance_metrics.py
import numpy as np class Distance_metrics: """ Calculate distance between each corresponding points of two arrays using different distance metrics """ def Eucledian_Distance(X1,X2): """" Returns the list of eucledian distance between two corresponding points of two ...
0.805173
0.837487
b_w = 'QPushButton{border-top-left-radius: 10px;border-top-right-radius: 10px;border-bottom-right-radius: ' \ '10px;border-bottom-left-radius: 10px;background-color: rgb(234, 234, 234);}' \ 'QPushButton:pressed {background-color: rgb(188, 188, 188);}' \ 'QPushButton {text-align: left;}' b_g = 'QPushB...
SAMG/COL.py
b_w = 'QPushButton{border-top-left-radius: 10px;border-top-right-radius: 10px;border-bottom-right-radius: ' \ '10px;border-bottom-left-radius: 10px;background-color: rgb(234, 234, 234);}' \ 'QPushButton:pressed {background-color: rgb(188, 188, 188);}' \ 'QPushButton {text-align: left;}' b_g = 'QPushB...
0.742235
0.268384
import os from PySide2 import QtWidgets, QtCore, QtGui from propsettings_qt.ui_settings_area import SettingsAreaWidget from pyrulo import class_imports class ConfigurableSelector(QtWidgets.QWidget): """ Widget para cargar clases que hereden de una clase base especificada e inicializar un combobox con inst...
pyrulo_qt/ui_configurable_selector.py
import os from PySide2 import QtWidgets, QtCore, QtGui from propsettings_qt.ui_settings_area import SettingsAreaWidget from pyrulo import class_imports class ConfigurableSelector(QtWidgets.QWidget): """ Widget para cargar clases que hereden de una clase base especificada e inicializar un combobox con inst...
0.519765
0.061087
import datetime from typing import List, Dict from lxml import etree as ET import os import numpy as np from collections import OrderedDict from miso.training.parameters import MisoParameters class ModelInfo: def __init__(self, name: str, description: str, type:...
miso/deploy/model_info.py
import datetime from typing import List, Dict from lxml import etree as ET import os import numpy as np from collections import OrderedDict from miso.training.parameters import MisoParameters class ModelInfo: def __init__(self, name: str, description: str, type:...
0.734501
0.233029
from uuid import uuid4 import pytest from common.test.acceptance.fixtures.course import CourseFixture # lint-amnesty, pylint: disable=unused-import from common.test.acceptance.fixtures.discussion import ( Comment, Response, SingleThreadViewFixture, Thread, ) from common.test.acceptance.pages.common....
Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/common/test/acceptance/tests/discussion/test_discussion.py
from uuid import uuid4 import pytest from common.test.acceptance.fixtures.course import CourseFixture # lint-amnesty, pylint: disable=unused-import from common.test.acceptance.fixtures.discussion import ( Comment, Response, SingleThreadViewFixture, Thread, ) from common.test.acceptance.pages.common....
0.345768
0.427875
import numpy as np def integerized(sequence): key_dict = sorted(set(sequence)) int_seq = [] for char in sequence: to_int = key_dict.index(char) int_seq.append(to_int) return int_seq def preprocess(sequences, ignoreLower=True): upper_seq = [] len_record = [] for ...
utils/mismatchtree.py
import numpy as np def integerized(sequence): key_dict = sorted(set(sequence)) int_seq = [] for char in sequence: to_int = key_dict.index(char) int_seq.append(to_int) return int_seq def preprocess(sequences, ignoreLower=True): upper_seq = [] len_record = [] for ...
0.432782
0.521227
import os import cv2 import torch import argparse import numpy as np from PIL import Image from torchvision import transforms from config import get_config from Learner import face_learner from data.data_pipe import get_val_pair from mtcnn_pytorch.crop_and_aligned import mctnn_crop_face def initialize_learner(conf,...
plot_qualitative_results_given_2_imgs.py
import os import cv2 import torch import argparse import numpy as np from PIL import Image from torchvision import transforms from config import get_config from Learner import face_learner from data.data_pipe import get_val_pair from mtcnn_pytorch.crop_and_aligned import mctnn_crop_face def initialize_learner(conf,...
0.661267
0.397061
import random print("This simulates f-pairs, L2-L3.") f_his = [] f = 178 perturbation_pos_f = random.sample(range(6, f), round(f * 0.05)) perturbation_pos_f = sorted(perturbation_pos_f) print(perturbation_pos_f) def calculate_strategy_f(memoryA, memoryB): t1 = [0,0,0] t2 = [0,0,0] for i in range(len(...
testpayoff.py
import random print("This simulates f-pairs, L2-L3.") f_his = [] f = 178 perturbation_pos_f = random.sample(range(6, f), round(f * 0.05)) perturbation_pos_f = sorted(perturbation_pos_f) print(perturbation_pos_f) def calculate_strategy_f(memoryA, memoryB): t1 = [0,0,0] t2 = [0,0,0] for i in range(len(...
0.173288
0.515986
from collections import defaultdict rules = defaultdict(list) rev_rules = defaultdict(list) with open('input') as f: rep_text = f.read().splitlines(keepends=False) calibration_molecule = rep_text[-1] rep_text = rep_text[:-1] for line in rep_text: if len(line.strip()) > 0: k, v = line.split(' => ') ...
2015/19/rednose_reactor.py
from collections import defaultdict rules = defaultdict(list) rev_rules = defaultdict(list) with open('input') as f: rep_text = f.read().splitlines(keepends=False) calibration_molecule = rep_text[-1] rep_text = rep_text[:-1] for line in rep_text: if len(line.strip()) > 0: k, v = line.split(' => ') ...
0.252845
0.140661
from airflow.models.baseoperator import BaseOperator from airflow.hooks.postgres_hook import PostgresHook from airflow.utils.decorators import apply_defaults from airflow.contrib.hooks.aws_hook import AwsHook class StageTablesOperator(BaseOperator): """ @description: This operator copies data f...
airflow/plugins/operators/StagTablesOperator.py
from airflow.models.baseoperator import BaseOperator from airflow.hooks.postgres_hook import PostgresHook from airflow.utils.decorators import apply_defaults from airflow.contrib.hooks.aws_hook import AwsHook class StageTablesOperator(BaseOperator): """ @description: This operator copies data f...
0.764892
0.202246
import inspect import logging import os import requests from requests import HTTPError from requests.adapters import HTTPAdapter from urllib3 import Retry DEFAULT_TIMEOUT = 60 # seconds class TimeoutHTTPAdapter(HTTPAdapter): def __init__(self, *args, **kwargs): self.timeout = DEFAULT_TIMEOUT if...
library/util.py
import inspect import logging import os import requests from requests import HTTPError from requests.adapters import HTTPAdapter from urllib3 import Retry DEFAULT_TIMEOUT = 60 # seconds class TimeoutHTTPAdapter(HTTPAdapter): def __init__(self, *args, **kwargs): self.timeout = DEFAULT_TIMEOUT if...
0.403449
0.050941
import numpy as np BATCHSIZE = 1000 class Evaluator(object): def __init__(self, metric, nbest=None, filtered=False, whole_graph=None): assert metric in ['mrr', 'hits', 'all'], 'Invalid metric: {}'.format(metric) if metric == 'hits': assert nbest, 'Please indicate n-best in using hits...
src/processors/evaluator.py
import numpy as np BATCHSIZE = 1000 class Evaluator(object): def __init__(self, metric, nbest=None, filtered=False, whole_graph=None): assert metric in ['mrr', 'hits', 'all'], 'Invalid metric: {}'.format(metric) if metric == 'hits': assert nbest, 'Please indicate n-best in using hits...
0.479991
0.52476
import logging from ignition.service.framework import ServiceRegistration from ignition.boot.config import BootProperties from ignition.boot.configurators.utils import validate_no_service_with_capability_exists from ignition.service.messaging import MessagingProperties, InboxCapability, DeliveryCapability, PostalCapabi...
ignition/boot/configurators/messaging.py
import logging from ignition.service.framework import ServiceRegistration from ignition.boot.config import BootProperties from ignition.boot.configurators.utils import validate_no_service_with_capability_exists from ignition.service.messaging import MessagingProperties, InboxCapability, DeliveryCapability, PostalCapabi...
0.428473
0.051415
from morepath.request import Response from onegov.core.security import Public from onegov.election_day import _ from onegov.election_day import ElectionDayApp from onegov.election_day.collections import EmailSubscriberCollection from onegov.election_day.collections import SmsSubscriberCollection from onegov.election_da...
src/onegov/election_day/views/subscription.py
from morepath.request import Response from onegov.core.security import Public from onegov.election_day import _ from onegov.election_day import ElectionDayApp from onegov.election_day.collections import EmailSubscriberCollection from onegov.election_day.collections import SmsSubscriberCollection from onegov.election_da...
0.656328
0.111
import PyIgnition, pygame, sys, math, random pygame.font.init() screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("PyIgnition 'Controlled Eruption' demo") clock = pygame.time.Clock() curframe = 0 started = False # 'Press space to start' text starttextfont = pygame.font.Font("cour...
display_dominik/Controlled Eruption.py
import PyIgnition, pygame, sys, math, random pygame.font.init() screen = pygame.display.set_mode((800, 600)) pygame.display.set_caption("PyIgnition 'Controlled Eruption' demo") clock = pygame.time.Clock() curframe = 0 started = False # 'Press space to start' text starttextfont = pygame.font.Font("cour...
0.178669
0.208612
import random from environment.selfplay import SelfPlay from environment.mazebase_wrapper import MazebaseWrapper from environment.observation import ObservationTuple, Observation from utils.constant import * from copy import deepcopy import numpy as np class SelfPlayTarget(SelfPlay): """ Wrapper class over se...
SelfPlay/environment/selfplay_target.py
import random from environment.selfplay import SelfPlay from environment.mazebase_wrapper import MazebaseWrapper from environment.observation import ObservationTuple, Observation from utils.constant import * from copy import deepcopy import numpy as np class SelfPlayTarget(SelfPlay): """ Wrapper class over se...
0.567937
0.186428
import botCore import parserCore from aiogram import utils from modules import adblocker, database, rating async def send_post(message): if adblocker.post_contains_ad(message): for user in database.User.select() \ .where(database.User.observing_channels.contains(str(message.se...
modules/messages.py
import botCore import parserCore from aiogram import utils from modules import adblocker, database, rating async def send_post(message): if adblocker.post_contains_ad(message): for user in database.User.select() \ .where(database.User.observing_channels.contains(str(message.se...
0.115224
0.038683
from module import * from models import * from flask import request, session class Viper(object): def __init__(self, vphone="", vname="", vrank="0", vid=""): self.phone = vphone self.name = vname self.rank = vrank self.vid = vid def addVip(self): if self.name == "" or ...
classes/vip.py
from module import * from models import * from flask import request, session class Viper(object): def __init__(self, vphone="", vname="", vrank="0", vid=""): self.phone = vphone self.name = vname self.rank = vrank self.vid = vid def addVip(self): if self.name == "" or ...
0.355887
0.091788
def binary_search_base(nums: list, target: int) -> int: """ Time complexi O(logn) The basic binary search nums is a sorted list if multi targets in nums, return one target index else return -1 """ if not nums: return -1 left, right = 0, len(nums) - 1 while left < right: ...
search and sort/binary_search.py
def binary_search_base(nums: list, target: int) -> int: """ Time complexi O(logn) The basic binary search nums is a sorted list if multi targets in nums, return one target index else return -1 """ if not nums: return -1 left, right = 0, len(nums) - 1 while left < right: ...
0.703448
0.722796
import os import random from string import ascii_uppercase, digits from Bio import Seq, SeqUtils, SeqIO, SeqRecord from Bio.Alphabet import IUPAC from Bio.Blast import NCBIWWW, NCBIXML from matplotlib import pylab __author__ = '<NAME>' __license__ = "MIT" __version__ = "1.0" __status__ = "Production" class Sequence...
Sequence.py
import os import random from string import ascii_uppercase, digits from Bio import Seq, SeqUtils, SeqIO, SeqRecord from Bio.Alphabet import IUPAC from Bio.Blast import NCBIWWW, NCBIXML from matplotlib import pylab __author__ = '<NAME>' __license__ = "MIT" __version__ = "1.0" __status__ = "Production" class Sequence...
0.585931
0.25247
import kivy from kivy.app import App from kivy.config import Config kivy.require("1.10.0") Config.read("mitc.ini") from kivy.core.window import Window from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.stacklayout import StackLayout INPUT_REFERENCE = 0 class Input(TextInput): ...
src/MitC.py
import kivy from kivy.app import App from kivy.config import Config kivy.require("1.10.0") Config.read("mitc.ini") from kivy.core.window import Window from kivy.uix.textinput import TextInput from kivy.uix.button import Button from kivy.uix.stacklayout import StackLayout INPUT_REFERENCE = 0 class Input(TextInput): ...
0.411347
0.1692
import numpy as np import torch import torch.nn as nn from gnn_cnn_model.modules import * class MultiHeadAttention(nn.Module): def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1): super(MultiHeadAttention, self).__init__() self.n_head = n_head self.d_k = d_k self.d_v = d_v ...
gnn_cnn_model/sublayers.py
import numpy as np import torch import torch.nn as nn from gnn_cnn_model.modules import * class MultiHeadAttention(nn.Module): def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1): super(MultiHeadAttention, self).__init__() self.n_head = n_head self.d_k = d_k self.d_v = d_v ...
0.941196
0.328375
import struct import re import zipfile import os import logging from io import BytesIO from collections import OrderedDict from urllib.parse import urlparse import requests from ckan.lib import uploader, formatters log = logging.getLogger(__name__) ALLOWED_FMTS = ('zip', 'application/zip', 'application/x-zip-compre...
ckanext/zippreview/utils.py
import struct import re import zipfile import os import logging from io import BytesIO from collections import OrderedDict from urllib.parse import urlparse import requests from ckan.lib import uploader, formatters log = logging.getLogger(__name__) ALLOWED_FMTS = ('zip', 'application/zip', 'application/x-zip-compre...
0.302082
0.101947
"""---------------- Importing libraries ---------------- """ # System tools import sys import os sys.path.append(os.path.join("..")) # Import pandas for working with dataframes import pandas as pd # Neural networks with numpy import numpy as np from utils.neuralnetwork import NeuralNetwork # Machine learning tools...
src/Neural_Network.py
"""---------------- Importing libraries ---------------- """ # System tools import sys import os sys.path.append(os.path.join("..")) # Import pandas for working with dataframes import pandas as pd # Neural networks with numpy import numpy as np from utils.neuralnetwork import NeuralNetwork # Machine learning tools...
0.508544
0.637285
import secrets import time import asyncio from typing import ( Any, cast, Dict, List, ) from eth_utils import encode_hex from hp2p.constants import PEER_STAKE_GONE_STALE_TIME_PERIOD from hvm.exceptions import ( CanonicalHeadNotFound, ) from hp2p.exceptions import HandshakeFailure from hp2p.p2p_...
helios/protocol/hls/peer.py
import secrets import time import asyncio from typing import ( Any, cast, Dict, List, ) from eth_utils import encode_hex from hp2p.constants import PEER_STAKE_GONE_STALE_TIME_PERIOD from hvm.exceptions import ( CanonicalHeadNotFound, ) from hp2p.exceptions import HandshakeFailure from hp2p.p2p_...
0.603348
0.136983
import py from rpython.flowspace.argument import (ArgumentsForTranslation, rawshape, Signature) class TestSignature(object): def test_helpers(self): sig = Signature(["a", "b", "c"], None, None) assert sig.num_argnames() == 3 assert not sig.has_vararg() assert not sig.has_kwarg(...
rpython/flowspace/test/test_argument.py
import py from rpython.flowspace.argument import (ArgumentsForTranslation, rawshape, Signature) class TestSignature(object): def test_helpers(self): sig = Signature(["a", "b", "c"], None, None) assert sig.num_argnames() == 3 assert not sig.has_vararg() assert not sig.has_kwarg(...
0.5083
0.522202
import datetime import nose.tools from nose.tools import with_setup from billy.models import db def setup_func(): assert db.name.endswith('_test') db.metadata.drop() db.bills.drop() db.votes.drop() db.legislators.drop() db.document_ids.drop() db.vote_ids.drop() db.committees.drop() ...
billy/tests/models/legislator_test_context_role.py
import datetime import nose.tools from nose.tools import with_setup from billy.models import db def setup_func(): assert db.name.endswith('_test') db.metadata.drop() db.bills.drop() db.votes.drop() db.legislators.drop() db.document_ids.drop() db.vote_ids.drop() db.committees.drop() ...
0.46563
0.260125
from setuptools import setup import os import seam_erasure here = os.path.abspath(os.path.dirname(__file__)) # Get the long description from the README file with open(os.path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() long_description = long_description.replace( "static/img/...
setup.py
from setuptools import setup import os import seam_erasure here = os.path.abspath(os.path.dirname(__file__)) # Get the long description from the README file with open(os.path.join(here, 'README.md'), encoding='utf-8') as f: long_description = f.read() long_description = long_description.replace( "static/img/...
0.444806
0.200127
import sys import os import argparse import src.common as commonutils """ PyDashing CLI Parser. --------------------- """ class PyDashingCli(object): """ PyDashing CLI Parser. """ def __init__(self): """ Initialize PyDashing CLI. """ # Check for atleast one argument ...
testdash/src/pydashing_cli.py
import sys import os import argparse import src.common as commonutils """ PyDashing CLI Parser. --------------------- """ class PyDashingCli(object): """ PyDashing CLI Parser. """ def __init__(self): """ Initialize PyDashing CLI. """ # Check for atleast one argument ...
0.376509
0.197561
"Entities relating to the datamap." from enum import Enum, auto from pathlib import Path # pylint: disable=R0903,R0913; from typing import IO, Dict, Optional, Union from engine.exceptions import DatamapNotCSVException class DatamapLineValueType(Enum): """A representation of a data type for us in validating data...
engine/domain/datamap.py
"Entities relating to the datamap." from enum import Enum, auto from pathlib import Path # pylint: disable=R0903,R0913; from typing import IO, Dict, Optional, Union from engine.exceptions import DatamapNotCSVException class DatamapLineValueType(Enum): """A representation of a data type for us in validating data...
0.89706
0.508117
from collections import OrderedDict import numpy as np from astropy.modeling import models from astropy.modeling.core import Model from astropy.utils.misc import isiterable from asdf.tags.core.ndarray import NDArrayType from asdf_astropy.converters.transform.core import TransformConverterBase __all__ = ['LabelMappe...
gwcs/converters/selector.py
from collections import OrderedDict import numpy as np from astropy.modeling import models from astropy.modeling.core import Model from astropy.utils.misc import isiterable from asdf.tags.core.ndarray import NDArrayType from asdf_astropy.converters.transform.core import TransformConverterBase __all__ = ['LabelMappe...
0.699357
0.437643
import cv2 as cv import mediapipe as mp import time mpDraw = mp.solutions.drawing_utils mpFaceDetection = mp.solutions.face_detection faceDetection = mpFaceDetection.FaceDetection(0.30) pTime = 0 cap = cv.VideoCapture('Videos/mkbhd.mp4') def Rescale(frame, scale=0.50): # FOR PICTURES,VIDEO,LIVE JUST T0 MAKE IT F...
videofacedetect.py
import cv2 as cv import mediapipe as mp import time mpDraw = mp.solutions.drawing_utils mpFaceDetection = mp.solutions.face_detection faceDetection = mpFaceDetection.FaceDetection(0.30) pTime = 0 cap = cv.VideoCapture('Videos/mkbhd.mp4') def Rescale(frame, scale=0.50): # FOR PICTURES,VIDEO,LIVE JUST T0 MAKE IT F...
0.404978
0.322846
from django.core.management.base import BaseCommand from cantusdata.models.folio import Folio from cantusdata.models.manuscript import Manuscript from django.core.management import call_command from optparse import make_option import csv class Command(BaseCommand): """ Import a folio mapping (CSV file) Sa...
public/cantusdata/management/commands/import_folio_mapping.py
from django.core.management.base import BaseCommand from cantusdata.models.folio import Folio from cantusdata.models.manuscript import Manuscript from django.core.management import call_command from optparse import make_option import csv class Command(BaseCommand): """ Import a folio mapping (CSV file) Sa...
0.402744
0.184143
adjList=[ [26, 1], [28, 0], [29, 3], [43, 2], [31, 5], [69, 6, 4], [70, 5], [97, 8], [45, 9, 7], [46, 8], [58, 11], [36, 10], [37, 13], [39, 14, 12], [61, 15, 13], [41, 14], [71], [47, 18], [48, 17], [20], [50, 21, 19], [20], [...
graph_datasets/mazes/pmaze9.py
adjList=[ [26, 1], [28, 0], [29, 3], [43, 2], [31, 5], [69, 6, 4], [70, 5], [97, 8], [45, 9, 7], [46, 8], [58, 11], [36, 10], [37, 13], [39, 14, 12], [61, 15, 13], [41, 14], [71], [47, 18], [48, 17], [20], [50, 21, 19], [20], [...
0.202404
0.651819
from collections import namedtuple from random import choice from string import ascii_letters import pytest from azure_databricks_api.exceptions import ResourceAlreadyExists, IoError, ResourceDoesNotExist, InvalidParameterValue from tests.utils import create_client client = create_client() DBFS_TEMP_DIR = '/tmp' SM...
tests/test_dbfs.py
from collections import namedtuple from random import choice from string import ascii_letters import pytest from azure_databricks_api.exceptions import ResourceAlreadyExists, IoError, ResourceDoesNotExist, InvalidParameterValue from tests.utils import create_client client = create_client() DBFS_TEMP_DIR = '/tmp' SM...
0.391871
0.21794
from unittest import TestCase import numpy as np import dnn_misc import numpy.testing as test class TestRelu(TestCase): def test_forward(self): # check_relu.forward np.random.seed(123) # example data X = np.random.normal(0, 1, (5, 3)) check_relu = dnn_misc.relu() ha...
test_relu.py
from unittest import TestCase import numpy as np import dnn_misc import numpy.testing as test class TestRelu(TestCase): def test_forward(self): # check_relu.forward np.random.seed(123) # example data X = np.random.normal(0, 1, (5, 3)) check_relu = dnn_misc.relu() ha...
0.345105
0.553143