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
import os import sys cwd = os.getcwd() sys.path.append(cwd) from time import sleep import pybullet as p import numpy as np def setUpWorld(initialSimSteps=100): """ Reset the simulation to the beginning and reload all models. Parameters ---------- initialSimSteps : int Returns ------- ...
simulator/pybullet/baxter_main.py
import os import sys cwd = os.getcwd() sys.path.append(cwd) from time import sleep import pybullet as p import numpy as np def setUpWorld(initialSimSteps=100): """ Reset the simulation to the beginning and reload all models. Parameters ---------- initialSimSteps : int Returns ------- ...
0.53607
0.3628
from __future__ import unicode_literals import itertools from datetime import tzinfo, timedelta class UTC(tzinfo): """Why is this not in the standard library? """ ZERO = timedelta(0) def utcoffset(self, dt): return self.ZERO def tzname(self, dt): return "UTC" def dst(self,...
python/0.4/teleport/util.py
from __future__ import unicode_literals import itertools from datetime import tzinfo, timedelta class UTC(tzinfo): """Why is this not in the standard library? """ ZERO = timedelta(0) def utcoffset(self, dt): return self.ZERO def tzname(self, dt): return "UTC" def dst(self,...
0.676513
0.140749
import argparse import asyncio import os import re import aiohttp from utils import print_warn, print_green, fetch, batch parser = argparse.ArgumentParser( description='Download files from an exposed git repository in git-repo-url' ) parser.add_argument('repo-url', type=str, help='url of the exposed .git folde...
main.py
import argparse import asyncio import os import re import aiohttp from utils import print_warn, print_green, fetch, batch parser = argparse.ArgumentParser( description='Download files from an exposed git repository in git-repo-url' ) parser.add_argument('repo-url', type=str, help='url of the exposed .git folde...
0.40439
0.078254
import glob, os, sys import pandas as pd import numpy as np import warnings import pymannkendall as pmk import matplotlib.pyplot as plt sys.path.insert(0,r'E:\github\seasonality_risk\Functions') from Functions_HCMC import collect_rainfall, calc_avg_max_min_rainfall, keep_full_years, thiessen_rain, select_epoch_pairs ...
Pre-process/rainfall_test_trend_MM.py
import glob, os, sys import pandas as pd import numpy as np import warnings import pymannkendall as pmk import matplotlib.pyplot as plt sys.path.insert(0,r'E:\github\seasonality_risk\Functions') from Functions_HCMC import collect_rainfall, calc_avg_max_min_rainfall, keep_full_years, thiessen_rain, select_epoch_pairs ...
0.132571
0.468
from collections import OrderedDict as Od from typing import Callable, Dict, FrozenSet, NamedTuple, Tuple, Union import functools import unittest.mock as mock import pytest from pyunits.compound_units.compound_unit import CompoundUnit from pyunits.compound_units.compound_unit_type import CompoundUnitType from pyunits...
pyunits/compound_units/tests/test_unit_analysis.py
from collections import OrderedDict as Od from typing import Callable, Dict, FrozenSet, NamedTuple, Tuple, Union import functools import unittest.mock as mock import pytest from pyunits.compound_units.compound_unit import CompoundUnit from pyunits.compound_units.compound_unit_type import CompoundUnitType from pyunits...
0.93954
0.725782
import numba import numpy as np def is_unitary(u, digits): """Return True if u^dagger u is equal to the unit matrix with the given tolerance.""" unitary = np.eye(u.shape[0], dtype=np.complex128) # The rounding is required in edge cases? product = np.round(np.conj(u.T) @ u, digits - 1) return np...
floq/linalg.py
import numba import numpy as np def is_unitary(u, digits): """Return True if u^dagger u is equal to the unit matrix with the given tolerance.""" unitary = np.eye(u.shape[0], dtype=np.complex128) # The rounding is required in edge cases? product = np.round(np.conj(u.T) @ u, digits - 1) return np...
0.816809
0.79538
def getTags(v2, db): from notion.client import NotionClient try: client = NotionClient(token_v2=v2) print("Connected") except: print("Error v2") try: cv = client.get_collection_view(db) print("Connected") except: print("Error db") try: ...
app/src/main/python/Notion.py
def getTags(v2, db): from notion.client import NotionClient try: client = NotionClient(token_v2=v2) print("Connected") except: print("Error v2") try: cv = client.get_collection_view(db) print("Connected") except: print("Error db") try: ...
0.245447
0.144209
""" Higher-level storage operations, particulary for keys. """ import os import stat import random import traceback from Crypto.PublicKey import RSA as CryptoKey import syndicate.util.config as conf log = conf.log # ------------------- def read_file( file_path ): """ Read data from file_path Return no...
python/syndicate/util/storage.py
""" Higher-level storage operations, particulary for keys. """ import os import stat import random import traceback from Crypto.PublicKey import RSA as CryptoKey import syndicate.util.config as conf log = conf.log # ------------------- def read_file( file_path ): """ Read data from file_path Return no...
0.444324
0.142649
from __future__ import absolute_import, division, print_function from six.moves import range import math """radius is taken to be d_star, or 1/resolution limit in units of distance""" def sphere_volume(radius): return (4./3.)*math.pi*math.pow(radius,3) def vol_of_Ewald_sphere_solid_of_revolution(wavelength): """...
spotfinder/math_support/sphere_formulae.py
from __future__ import absolute_import, division, print_function from six.moves import range import math """radius is taken to be d_star, or 1/resolution limit in units of distance""" def sphere_volume(radius): return (4./3.)*math.pi*math.pow(radius,3) def vol_of_Ewald_sphere_solid_of_revolution(wavelength): """...
0.709623
0.63542
from collections import namedtuple import numpy as np from supervisely_lib.annotation.label import Label, PixelwiseScoresLabel from supervisely_lib.geometry.bitmap import Bitmap from supervisely_lib.geometry.rectangle import Rectangle from supervisely_lib.geometry.multichannel_bitmap import MultichannelBitmap from s...
superviselySDK/supervisely_lib/nn/raw_to_labels.py
from collections import namedtuple import numpy as np from supervisely_lib.annotation.label import Label, PixelwiseScoresLabel from supervisely_lib.geometry.bitmap import Bitmap from supervisely_lib.geometry.rectangle import Rectangle from supervisely_lib.geometry.multichannel_bitmap import MultichannelBitmap from s...
0.965956
0.665794
import torch from utils.validation import evaluate from tqdm.autonotebook import tqdm import os import numpy as np import torch.nn as nn import torch.nn.functional as F def train_model( model, dataset, optimizer, num_epochs, batch_size, loss_fkt=torch.nn.CrossEntropyLoss(), val_dataset=Non...
utils/training.py
import torch from utils.validation import evaluate from tqdm.autonotebook import tqdm import os import numpy as np import torch.nn as nn import torch.nn.functional as F def train_model( model, dataset, optimizer, num_epochs, batch_size, loss_fkt=torch.nn.CrossEntropyLoss(), val_dataset=Non...
0.872822
0.376566
import logging import uuid from datetime import timedelta from django.db import IntegrityError, models from django.utils import dateformat, timezone from django.utils.encoding import smart_text from .. import settings as djstripe_settings from ..fields import JSONField, StripeDateTimeField, StripeIdField from ..manag...
djstripe/models/base.py
import logging import uuid from datetime import timedelta from django.db import IntegrityError, models from django.utils import dateformat, timezone from django.utils.encoding import smart_text from .. import settings as djstripe_settings from ..fields import JSONField, StripeDateTimeField, StripeIdField from ..manag...
0.669096
0.088112
from . import register from .smbus2.smbus2 import SMBus, i2c_msg from random import randint import time import logging # rest time in second betweet each read/write transaction REST_INTERVAL = 0.3 # maximum block size for each read transaction BLOCK_SIZE = 20 # PN532 is the NFC tag reader module class PN532(object...
tag_reader/api.py
from . import register from .smbus2.smbus2 import SMBus, i2c_msg from random import randint import time import logging # rest time in second betweet each read/write transaction REST_INTERVAL = 0.3 # maximum block size for each read transaction BLOCK_SIZE = 20 # PN532 is the NFC tag reader module class PN532(object...
0.279533
0.222362
import logging import networkx as nx from primrose.configuration.util import OperationType, ConfigurationError import matplotlib.pyplot as plt from networkx.algorithms.shortest_paths.generic import has_path from primrose.node_factory import NodeFactory from primrose.base.conditional_path_node import AbstractConditional...
primrose/configuration/configuration_dag.py
import logging import networkx as nx from primrose.configuration.util import OperationType, ConfigurationError import matplotlib.pyplot as plt from networkx.algorithms.shortest_paths.generic import has_path from primrose.node_factory import NodeFactory from primrose.base.conditional_path_node import AbstractConditional...
0.838051
0.54692
import json from http.client import HTTPException from urllib.request import Request, urlopen from dotenv import dotenv_values, load_dotenv from fastapi import FastAPI, Header from fastapi.middleware.cors import CORSMiddleware from jose import jwt from starlette.responses import JSONResponse, Response from model.user...
controller/private_api.py
import json from http.client import HTTPException from urllib.request import Request, urlopen from dotenv import dotenv_values, load_dotenv from fastapi import FastAPI, Header from fastapi.middleware.cors import CORSMiddleware from jose import jwt from starlette.responses import JSONResponse, Response from model.user...
0.387227
0.060252
import torch import torch.nn as nn from copy import deepcopy class GeneratorFemnist(nn.Module): ''' The generator for Femnist dataset ''' def __init__(self, noise_dim=100): super(GeneratorFemnist, self).__init__() module_list = [] module_list.append( nn.Linear(in_f...
federatedscope/attack/models/gan_based_model.py
import torch import torch.nn as nn from copy import deepcopy class GeneratorFemnist(nn.Module): ''' The generator for Femnist dataset ''' def __init__(self, noise_dim=100): super(GeneratorFemnist, self).__init__() module_list = [] module_list.append( nn.Linear(in_f...
0.830353
0.341212
def find_top_confirmed(n = 15): import pandas as pd corona_df=pd.read_csv("dataset2.csv") by_country = corona_df.groupby('Country_Region').sum()[['Confirmed', 'Deaths', 'Recovered', 'Active']] cdf = by_country.nlargest(n, 'Confirmed')[['Confirmed']] return cdf cdf=find_top_confirmed() pairs=[...
app.py
def find_top_confirmed(n = 15): import pandas as pd corona_df=pd.read_csv("dataset2.csv") by_country = corona_df.groupby('Country_Region').sum()[['Confirmed', 'Deaths', 'Recovered', 'Active']] cdf = by_country.nlargest(n, 'Confirmed')[['Confirmed']] return cdf cdf=find_top_confirmed() pairs=[...
0.276593
0.147187
import ipaddress import re from .feature import Feature from .vrf import VRF from .cisco_secret import CiscoSecret from .nxcli import * import nxos_utils class OSPFSession(Feature): ''' Use this class to configure the OSPF feature. ''' def __init__(self, Instance=None, vrf='default'): self._...
Python nxapi scripts/cisco/ospf.py
import ipaddress import re from .feature import Feature from .vrf import VRF from .cisco_secret import CiscoSecret from .nxcli import * import nxos_utils class OSPFSession(Feature): ''' Use this class to configure the OSPF feature. ''' def __init__(self, Instance=None, vrf='default'): self._...
0.582016
0.151122
from pdip.data import RepositoryProvider from pdip.dependency.container import DependencyContainer from pdip.logging.loggers.database import SqlLogger from pdip.data import Seed from pdi.domain.connection import ConnectionType, ConnectorType class ConnectionSeed(Seed): def seed(self): try: re...
src/api/pdi/domain/connection/ConnectionSeed.py
from pdip.data import RepositoryProvider from pdip.dependency.container import DependencyContainer from pdip.logging.loggers.database import SqlLogger from pdip.data import Seed from pdi.domain.connection import ConnectionType, ConnectorType class ConnectionSeed(Seed): def seed(self): try: re...
0.296349
0.149656
import os import sys import shutil import pysam import breakmer.utils as utils __author__ = "<NAME>" __copyright__ = "Copyright 2015, <NAME>" __email__ = "<EMAIL>" __license__ = "MIT" class ParamManager(object): """ParamManager class stores all the input specifications provided to the program to run. These inc...
breakmer/params.py
import os import sys import shutil import pysam import breakmer.utils as utils __author__ = "<NAME>" __copyright__ = "Copyright 2015, <NAME>" __email__ = "<EMAIL>" __license__ = "MIT" class ParamManager(object): """ParamManager class stores all the input specifications provided to the program to run. These inc...
0.586523
0.197522
import numpy as np # file template # each row is "rel_id rel_type word1 word2" # rel_type is 0 if not any subword information and any integer > 0 identifies the particular type of morphological relation # filters out any words that aren't in the model vocabulary def clean_dset(inpath, outpath, model): filein = op...
evaluation/analogy_dataset.py
import numpy as np # file template # each row is "rel_id rel_type word1 word2" # rel_type is 0 if not any subword information and any integer > 0 identifies the particular type of morphological relation # filters out any words that aren't in the model vocabulary def clean_dset(inpath, outpath, model): filein = op...
0.125172
0.218096
def build_trinuc_lookup(): ''' Builds a trinuc-to-index and index-to-trinuc dictionaries for decoding indicators values and trinucleotide strings. :return: trinuc: index, index: trinuc ''' values = [] index = 0 for c in "ACGT": for d in "ACGT": for ref in "CT": ...
glider/utils/trinucs.py
def build_trinuc_lookup(): ''' Builds a trinuc-to-index and index-to-trinuc dictionaries for decoding indicators values and trinucleotide strings. :return: trinuc: index, index: trinuc ''' values = [] index = 0 for c in "ACGT": for d in "ACGT": for ref in "CT": ...
0.625438
0.668907
max_predicate = lambda a, b: a[1] <= b[1] class Heap: def __init__(self): self.heap = [] def heap_swap(self, a, b): t = self.heap[a] self.heap[a] = self.heap[b] self.heap[b] = t def _heapify(self, heap_size, x, predicate): left = 2 * (x + 1) - 1 right = ...
pymsvlm/msAlign/Heap.py
max_predicate = lambda a, b: a[1] <= b[1] class Heap: def __init__(self): self.heap = [] def heap_swap(self, a, b): t = self.heap[a] self.heap[a] = self.heap[b] self.heap[b] = t def _heapify(self, heap_size, x, predicate): left = 2 * (x + 1) - 1 right = ...
0.673729
0.460107
import logging import os import shutil import pytest import semver from click.testing import CliRunner from git import Git from create_python_project import RepositoryManager, ProjectManager DIR_NAME = os.path.dirname(__file__) @pytest.fixture(scope='function') def config_path(): yield os.path.join(DIR_NAME, '...
tests/conftest.py
import logging import os import shutil import pytest import semver from click.testing import CliRunner from git import Git from create_python_project import RepositoryManager, ProjectManager DIR_NAME = os.path.dirname(__file__) @pytest.fixture(scope='function') def config_path(): yield os.path.join(DIR_NAME, '...
0.445047
0.15588
from contextlib import contextmanager import logging import os import time from tempfile import NamedTemporaryFile from alembic import command from alembic.config import Config from sqlalchemy import and_, create_engine, event, or_ from sqlalchemy.orm.session import sessionmaker from sqlalchemy.exc import Operationa...
buildgrid/server/persistence/sql/impl.py
from contextlib import contextmanager import logging import os import time from tempfile import NamedTemporaryFile from alembic import command from alembic.config import Config from sqlalchemy import and_, create_engine, event, or_ from sqlalchemy.orm.session import sessionmaker from sqlalchemy.exc import Operationa...
0.623262
0.087369
import time from rpi_ws281x import Adafruit_NeoPixel, Color class LedStrip(): def __init__( self, ledCount = 110, # Number of LED pixels. ledPin = 18, # GPIO pin connected to the pixels (18 uses PWM, 10 uses SPI /dev/spidev0.0). ledFreqHz = 800000, # LED signal frequency ...
ledstrip.py
import time from rpi_ws281x import Adafruit_NeoPixel, Color class LedStrip(): def __init__( self, ledCount = 110, # Number of LED pixels. ledPin = 18, # GPIO pin connected to the pixels (18 uses PWM, 10 uses SPI /dev/spidev0.0). ledFreqHz = 800000, # LED signal frequency ...
0.68679
0.23895
import argparse import json import sys import time import signal import logging import logging.config import traceback from typing import List, Tuple from pathlib import Path from pysimpledlna.ui.playlist import PlayListEditor import os from pysimpledlna import SimpleDLNAServer, Device from pysimpledlna.ac import Ac...
pysimpledlna/cli.py
import argparse import json import sys import time import signal import logging import logging.config import traceback from typing import List, Tuple from pathlib import Path from pysimpledlna.ui.playlist import PlayListEditor import os from pysimpledlna import SimpleDLNAServer, Device from pysimpledlna.ac import Ac...
0.201813
0.046378
from __future__ import unicode_literals from datetime import datetime, timedelta from django.contrib.auth.models import User from django.db import models from django.db.models import Q from django.utils.translation import ugettext_lazy as _ import operator class UserProfile(models.Model): user = models.OneToOneF...
base/models.py
from __future__ import unicode_literals from datetime import datetime, timedelta from django.contrib.auth.models import User from django.db import models from django.db.models import Q from django.utils.translation import ugettext_lazy as _ import operator class UserProfile(models.Model): user = models.OneToOneF...
0.575707
0.089813
import typing from dataclasses import dataclass from typing import Generic, TypeVar, Union import numpy as np T = TypeVar("T", int, float) @dataclass class Point2DBaseGeometry(Generic[T]): """Represents a 2D Point. Args: x: :attr:`~.Point2D.x` y: :attr:`~.Point2D.y` class_id: :attr:...
paralleldomain/model/geometry/point_2d.py
import typing from dataclasses import dataclass from typing import Generic, TypeVar, Union import numpy as np T = TypeVar("T", int, float) @dataclass class Point2DBaseGeometry(Generic[T]): """Represents a 2D Point. Args: x: :attr:`~.Point2D.x` y: :attr:`~.Point2D.y` class_id: :attr:...
0.932684
0.577495
level_dict["hidden"] = { "scheme": "metal_scheme", "size": (9,9,9), "intro": "hidden", "help": ( "$scale(1.5)mission:\nactivate the exit!\n\n" + \ ...
py/levels/hidden.py
level_dict["hidden"] = { "scheme": "metal_scheme", "size": (9,9,9), "intro": "hidden", "help": ( "$scale(1.5)mission:\nactivate the exit!\n\n" + \ ...
0.333503
0.245718
import datetime from django.conf import settings from django.contrib import auth from django.core.exceptions import ImproperlyConfigured from django.shortcuts import get_object_or_404 from django.utils.module_loading import import_string from .models import IdP IDP_SESSION_KEY = "_idpid" NAMEID_SESSION_KEY = "_namei...
pucadmin/sp/utils.py
import datetime from django.conf import settings from django.contrib import auth from django.core.exceptions import ImproperlyConfigured from django.shortcuts import get_object_or_404 from django.utils.module_loading import import_string from .models import IdP IDP_SESSION_KEY = "_idpid" NAMEID_SESSION_KEY = "_namei...
0.314471
0.05549
# ----------------------------------------- Higher-level Chain functions ----------------------------------------------- def makeChain(functionDictList, preiterable=None, inMethod=None, in_kwargs=None, writeInfoExists=False, recordMethod=None, record_kwargs=None, writeInfo_recordkw=None, extractMethod=...
msbrainpy/chain.py
# ----------------------------------------- Higher-level Chain functions ----------------------------------------------- def makeChain(functionDictList, preiterable=None, inMethod=None, in_kwargs=None, writeInfoExists=False, recordMethod=None, record_kwargs=None, writeInfo_recordkw=None, extractMethod=...
0.697403
0.663969
import os import sys import tempfile try: import pydot except ImportError: # Workaround for an obscure test case: on some TeamCity build hosts, we run # self-tests from a Mercurial checkout rather than from a pip install. In that # scenario, pip can't have fulfilled our pydot2 requirement, so import py...
autobuild/autobuild_tool_graph.py
import os import sys import tempfile try: import pydot except ImportError: # Workaround for an obscure test case: on some TeamCity build hosts, we run # self-tests from a Mercurial checkout rather than from a pip install. In that # scenario, pip can't have fulfilled our pydot2 requirement, so import py...
0.310694
0.159774
import json, sys from collections import defaultdict def aggregate(pdf_filepath, report, aggregated_report_filepath): agg_report = { "failures": defaultdict(list), "errors": defaultdict(list), } try: with open(aggregated_report_filepath) as agg_file: prev_agg_report = j...
SMSProject/venv/Lib/site-packages/scripts/checker_commons.py
import json, sys from collections import defaultdict def aggregate(pdf_filepath, report, aggregated_report_filepath): agg_report = { "failures": defaultdict(list), "errors": defaultdict(list), } try: with open(aggregated_report_filepath) as agg_file: prev_agg_report = j...
0.095181
0.112942
from .host_performance_metric_group import HostPerformanceMetricGroup from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class HostTopProcesses(HostPerformanceMetricGroup): ...
src/oci/opsi/models/host_top_processes.py
from .host_performance_metric_group import HostPerformanceMetricGroup from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401 from oci.decorators import init_model_state_from_kwargs @init_model_state_from_kwargs class HostTopProcesses(HostPerformanceMetricGroup): ...
0.841858
0.252531
import cantera as ct import csv import numpy as np import sys from PyQt4 import QtGui, QtCore # define gui app and widget app = QtGui.QApplication(sys.argv) # Widget class with changed icon class NSortableTableWidgetItem(QtGui.QTableWidgetItem): # Implement less than (<) for numeric table widget items....
equilibrium_simple_gas.py
import cantera as ct import csv import numpy as np import sys from PyQt4 import QtGui, QtCore # define gui app and widget app = QtGui.QApplication(sys.argv) # Widget class with changed icon class NSortableTableWidgetItem(QtGui.QTableWidgetItem): # Implement less than (<) for numeric table widget items....
0.302494
0.086478
import argparse import platform import os DATASET_DIR = "./datasets" TARGETS = [ ("apple", "get_apple.py"), ("bee_waggle_6", "get_bee_waggle_6.py"), ("bitcoin", "get_bitcoin.py"), ("iceland_tourism", "get_iceland_tourism.py"), ("measles", "get_measles.py"), ("occupancy", "get_occupancy.py"), ...
build_tcpd.py
import argparse import platform import os DATASET_DIR = "./datasets" TARGETS = [ ("apple", "get_apple.py"), ("bee_waggle_6", "get_bee_waggle_6.py"), ("bitcoin", "get_bitcoin.py"), ("iceland_tourism", "get_iceland_tourism.py"), ("measles", "get_measles.py"), ("occupancy", "get_occupancy.py"), ...
0.430147
0.208179
import os from dataclasses import dataclass from typing import ( List, Optional ) from aws_cdk.core import ( Construct, Stack, StackProps ) from aws_cdk.aws_ec2 import ( BastionHostLinux, IMachineImage, IVpc, Port, SubnetSelection ) from aws_cdk.aws_s3_assets import ( Asset )...
examples/deadline/All-In-AWS-Infrastructure-Basic/python/package/lib/compute_tier.py
import os from dataclasses import dataclass from typing import ( List, Optional ) from aws_cdk.core import ( Construct, Stack, StackProps ) from aws_cdk.aws_ec2 import ( BastionHostLinux, IMachineImage, IVpc, Port, SubnetSelection ) from aws_cdk.aws_s3_assets import ( Asset )...
0.705886
0.130867
__author__ = 'rochelle' #!/usr/bin/env python import csv import arcpy import logging logger = logging.getLogger('LoadSurveyData') logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) arcpy.env.workspace = r"Database Connections\vampire_vampire_gdb_localhost.sde" de...
python/household_survey/LoadSurveyData.py
__author__ = 'rochelle' #!/usr/bin/env python import csv import arcpy import logging logger = logging.getLogger('LoadSurveyData') logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG) arcpy.env.workspace = r"Database Connections\vampire_vampire_gdb_localhost.sde" de...
0.214774
0.101367
import os import re import tkinter as tk import tkinter.simpledialog from tkinter import PhotoImage from tkinter import filedialog from tkinter import messagebox from PIL import ImageGrab import MoonlightMiner from CustomWidgets import CustomButton, RecentButton, CustomLabel, CustomFrame class PDFReader(t...
Moonlight PDF Reader/application.pyw
import os import re import tkinter as tk import tkinter.simpledialog from tkinter import PhotoImage from tkinter import filedialog from tkinter import messagebox from PIL import ImageGrab import MoonlightMiner from CustomWidgets import CustomButton, RecentButton, CustomLabel, CustomFrame class PDFReader(t...
0.273866
0.062732
#Importing libraries from bokeh.plotting import figure from bokeh.io import output_file, show from bokeh.sampledata.iris import flowers from bokeh.models import Range1d, PanTool, ResetTool, HoverTool, WheelZoomTool from screeninfo import get_monitors #Define the output file path output_file("iris.html") #...
S3-Plotting Flower Species.py
#Importing libraries from bokeh.plotting import figure from bokeh.io import output_file, show from bokeh.sampledata.iris import flowers from bokeh.models import Range1d, PanTool, ResetTool, HoverTool, WheelZoomTool from screeninfo import get_monitors #Define the output file path output_file("iris.html") #...
0.411466
0.266322
from datetime import datetime import requests from PyQt5 import QtWidgets, QtCore import clientui import user_and_passui import errorui URL = 'http://127.0.0.1:5000/' VERSION = "1.0.0" THEMES = ["color: rgb(255, 255, 255); background-color: rgba(0, 255, 254, 0);", "background-color: qlineargradient(spread:p...
messenger.py
from datetime import datetime import requests from PyQt5 import QtWidgets, QtCore import clientui import user_and_passui import errorui URL = 'http://127.0.0.1:5000/' VERSION = "1.0.0" THEMES = ["color: rgb(255, 255, 255); background-color: rgba(0, 255, 254, 0);", "background-color: qlineargradient(spread:p...
0.317003
0.091951
import urllib.request, json from .models import Articles from .models import Sources Articles = Articles Sources = Sources #Getting Api key API_KEY = None source_url = None source_articles_url = None #Getting base url def configure_request(app): global api_key, source_articles_url, source_url api_key = app.confi...
app/requests.py
import urllib.request, json from .models import Articles from .models import Sources Articles = Articles Sources = Sources #Getting Api key API_KEY = None source_url = None source_articles_url = None #Getting base url def configure_request(app): global api_key, source_articles_url, source_url api_key = app.confi...
0.314051
0.046055
import json import logging as log import redis import crawl_monitor.settings as settings NUM_SPLIT = 'num_split' SOURCE_SET = 'inbound_sources' def parse_message(message): try: decoded = json.loads(str(message.value(), 'utf-8')) decoded['source'] = decoded['source'].lower() except (json.JSOND...
crawl_monitor/source_splitter.py
import json import logging as log import redis import crawl_monitor.settings as settings NUM_SPLIT = 'num_split' SOURCE_SET = 'inbound_sources' def parse_message(message): try: decoded = json.loads(str(message.value(), 'utf-8')) decoded['source'] = decoded['source'].lower() except (json.JSOND...
0.489748
0.13925
data = ( 'ha', # 0x00 'hu', # 0x01 'hi', # 0x02 'haa', # 0x03 'hee', # 0x04 'he', # 0x05 'ho', # 0x06 None, # 0x07 'la', # 0x08 'lu', # 0x09 'li', # 0x0a 'laa', # 0x0b 'lee', # 0x0c 'le', # 0x0d 'lo', # 0x0e 'lwa', # 0x0f 'hha', # 0x10 'hhu', # 0x11 'hhi', # 0x12...
Lib/site-packages/unidecode/x012.py
data = ( 'ha', # 0x00 'hu', # 0x01 'hi', # 0x02 'haa', # 0x03 'hee', # 0x04 'he', # 0x05 'ho', # 0x06 None, # 0x07 'la', # 0x08 'lu', # 0x09 'li', # 0x0a 'laa', # 0x0b 'lee', # 0x0c 'le', # 0x0d 'lo', # 0x0e 'lwa', # 0x0f 'hha', # 0x10 'hhu', # 0x11 'hhi', # 0x12...
0.049051
0.185338
from django.conf.urls import url, re_path from django.contrib import admin from django.urls import include from rest_framework.urlpatterns import format_suffix_patterns from rest_framework.schemas import get_schema_view from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, \ verify_jwt_token f...
moviebase/moviebase/urls.py
from django.conf.urls import url, re_path from django.contrib import admin from django.urls import include from rest_framework.urlpatterns import format_suffix_patterns from rest_framework.schemas import get_schema_view from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token, \ verify_jwt_token f...
0.361616
0.098339
import os import sys import jinja2 import json PROJECT_PATH = os.path.dirname(os.path.realpath(__file__)) # load jinja templates template_path = os.path.join(PROJECT_PATH, 'templates') template_loader = jinja2.FileSystemLoader(searchpath=template_path) template_env = jinja2.Environment(loader=template_loader, keep_t...
publish_img.py
import os import sys import jinja2 import json PROJECT_PATH = os.path.dirname(os.path.realpath(__file__)) # load jinja templates template_path = os.path.join(PROJECT_PATH, 'templates') template_loader = jinja2.FileSystemLoader(searchpath=template_path) template_env = jinja2.Environment(loader=template_loader, keep_t...
0.407923
0.17441
import prody as pr import numpy as np from prody.utilities.catchall import getCoords from scipy.spatial.transform import Rotation from sklearn.neighbors import NearestNeighbors import os from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem.rdmolfiles import MolToPDBFile from ..basic import prody_ext ...
metalprot/combs/position_ligand.py
import prody as pr import numpy as np from prody.utilities.catchall import getCoords from scipy.spatial.transform import Rotation from sklearn.neighbors import NearestNeighbors import os from rdkit import Chem from rdkit.Chem import AllChem from rdkit.Chem.rdmolfiles import MolToPDBFile from ..basic import prody_ext ...
0.492432
0.377627
import json import logging from django.test.client import Client from networkapi.test.test_case import NetworkApiTestCase log = logging.getLogger(__name__) class EquipmentPostSuccessTestCase(NetworkApiTestCase): fixtures = [ 'networkapi/system/fixtures/initial_variables.json', 'networkapi/usua...
networkapi/api_equipment/v4/tests/sanity/test_equipment_post.py
import json import logging from django.test.client import Client from networkapi.test.test_case import NetworkApiTestCase log = logging.getLogger(__name__) class EquipmentPostSuccessTestCase(NetworkApiTestCase): fixtures = [ 'networkapi/system/fixtures/initial_variables.json', 'networkapi/usua...
0.417746
0.068475
from decimal import Decimal from django.db import models from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import slugify from django.conf import settings from oscar.apps.shipping.methods import ShippingMethod class AbstractOrderAndItemLevelChargeMethod(models.Model, Shippi...
oscar/apps/shipping/abstract_models.py
from decimal import Decimal from django.db import models from django.utils.translation import ugettext_lazy as _ from django.template.defaultfilters import slugify from django.conf import settings from oscar.apps.shipping.methods import ShippingMethod class AbstractOrderAndItemLevelChargeMethod(models.Model, Shippi...
0.658637
0.142649
from celery import shared_task, chain from django.db import IntegrityError from django.utils.dateparse import parse_datetime from django.utils.timezone import now from eveuniverse.core.esitools import is_esi_online from eveuniverse.tasks import update_unresolved_eve_entities from allianceauth.services.hooks import g...
killtracker/tasks.py
from celery import shared_task, chain from django.db import IntegrityError from django.utils.dateparse import parse_datetime from django.utils.timezone import now from eveuniverse.core.esitools import is_esi_online from eveuniverse.tasks import update_unresolved_eve_entities from allianceauth.services.hooks import g...
0.392453
0.070688
from datetime import datetime from unittest import TestCase from PyProjManCore.task import Task from PyProjManCore.time_element import TimeElement class TestTaskParameters(TestCase): """Test Fields of Task Object""" def test_id(self): """Check if Task ID has UUID Version 4""" t = Task() ...
UnitTesting/test_task.py
from datetime import datetime from unittest import TestCase from PyProjManCore.task import Task from PyProjManCore.time_element import TimeElement class TestTaskParameters(TestCase): """Test Fields of Task Object""" def test_id(self): """Check if Task ID has UUID Version 4""" t = Task() ...
0.735642
0.592254
import json from glob import glob import numpy as np from sklearn.metrics import f1_score, average_precision_score from sklearn.model_selection import train_test_split from models import rnn_classifier, transformer_classifier from prepare_data import get_id_from_path, labels_to_vector, random_crop from tqdm import tq...
code/evaluate.py
import json from glob import glob import numpy as np from sklearn.metrics import f1_score, average_precision_score from sklearn.model_selection import train_test_split from models import rnn_classifier, transformer_classifier from prepare_data import get_id_from_path, labels_to_vector, random_crop from tqdm import tq...
0.605799
0.290603
import re import statsmodels.api as sm import numpy as np import matplotlib import matplotlib.pyplot as plt import math def parse_times_file(filename): f = open(filename, "r") lines = f.readlines() f.close() # Get the filename of the manifest these results are for p = re.compile(".*(/.*\.json).*"...
benchmark/performance_visualization.py
import re import statsmodels.api as sm import numpy as np import matplotlib import matplotlib.pyplot as plt import math def parse_times_file(filename): f = open(filename, "r") lines = f.readlines() f.close() # Get the filename of the manifest these results are for p = re.compile(".*(/.*\.json).*"...
0.347426
0.423696
WEBSOCKET_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" class AcceptedFriendRequestEvent: def __init__(self, chat_uuid, acceptor_uuid, acceptor_email, acceptor_username): self._type = "accepted_friend_request" self._chat_uuid = chat_uuid self._acceptor_uuid = acceptor_uuid self._accep...
realtime/events.py
WEBSOCKET_DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ" class AcceptedFriendRequestEvent: def __init__(self, chat_uuid, acceptor_uuid, acceptor_email, acceptor_username): self._type = "accepted_friend_request" self._chat_uuid = chat_uuid self._acceptor_uuid = acceptor_uuid self._accep...
0.732305
0.093678
import random import pandas as pd import os from pydub import AudioSegment import argparse def parse_arguments(): parser = argparse.ArgumentParser(description='') parser.add_argument("-i", "--input_dir", required=True, help="Input directory") parser.add_argument("-p",...
training/audio_preprocessing.py
import random import pandas as pd import os from pydub import AudioSegment import argparse def parse_arguments(): parser = argparse.ArgumentParser(description='') parser.add_argument("-i", "--input_dir", required=True, help="Input directory") parser.add_argument("-p",...
0.278355
0.095349
import sys if __name__ == '__main__': sys.path.append('../../bookend') class SJobject: def __init__(self, line, linetype=None): """Parses a line of SJ.out.tab or SJ.bed to an SJ object. O-indexed open coordinates.""" fields = line.rstrip().split('\t') if linetype is None: ...
bookend/core/sj_merge.py
import sys if __name__ == '__main__': sys.path.append('../../bookend') class SJobject: def __init__(self, line, linetype=None): """Parses a line of SJ.out.tab or SJ.bed to an SJ object. O-indexed open coordinates.""" fields = line.rstrip().split('\t') if linetype is None: ...
0.483892
0.210502
import logging import tkinter as tk import cv2 from cv2 import * from gui.operations.operation_template import OperationTemplate from gui.tabpicture import TabPicture class OperationAdaptiveThreshold(OperationTemplate): adaptiveMethodOptions = {'Gaussion': cv2.ADAPTIVE_THRESH_GAUSSIAN_C, ...
gui/operations/OperationsLinear/adap_prog.py
import logging import tkinter as tk import cv2 from cv2 import * from gui.operations.operation_template import OperationTemplate from gui.tabpicture import TabPicture class OperationAdaptiveThreshold(OperationTemplate): adaptiveMethodOptions = {'Gaussion': cv2.ADAPTIVE_THRESH_GAUSSIAN_C, ...
0.295636
0.115088
from base import * from lm import * from . import * from .trf import DefaultOps from trf.nce import noise class Config(trf.Config): def __init__(self, data): super().__init__(data) del self.__dict__['pi_0'] average_len = np.sum(np.arange(self.max_len+1) * self.pi_true) ...
hrf/trf_g.py
from base import * from lm import * from . import * from .trf import DefaultOps from trf.nce import noise class Config(trf.Config): def __init__(self, data): super().__init__(data) del self.__dict__['pi_0'] average_len = np.sum(np.arange(self.max_len+1) * self.pi_true) ...
0.399812
0.10904
import numpy as np import matplotlib.pyplot as plt from scipy import stats from scipy.optimize import curve_fit import astropy.table as t from astropy import units as u, constants as c from importer import * import manga_tools as m import smsd from radial import radial_gp def make_manga_dms_comparison(res, pca_sys...
dms_compare.py
import numpy as np import matplotlib.pyplot as plt from scipy import stats from scipy.optimize import curve_fit import astropy.table as t from astropy import units as u, constants as c from importer import * import manga_tools as m import smsd from radial import radial_gp def make_manga_dms_comparison(res, pca_sys...
0.642096
0.477311
PID_INDEX = 2 TITLE_INDEX = 4 import subprocess import sys import time def get_windows(): """Return the output of `wmctrl -l -p` as list of lines. This is basicaly the list of windows currently opened. See man wmctrl for more info. """ pr = subprocess.run(["wmctrl","-l","-p"], text=True, stdout=s...
launch_on_workspace/launcher.py
PID_INDEX = 2 TITLE_INDEX = 4 import subprocess import sys import time def get_windows(): """Return the output of `wmctrl -l -p` as list of lines. This is basicaly the list of windows currently opened. See man wmctrl for more info. """ pr = subprocess.run(["wmctrl","-l","-p"], text=True, stdout=s...
0.624637
0.464902
from datetime import * from mongoengine import * import operator from flask_jwt import jwt_required, current_identity from flask_restful import reqparse, Resource from static import app_constant, status from models.comment import BaseComment from models.base_event import BaseEvent from models.action import BaseAction ...
services/event_service/comment_services.py
from datetime import * from mongoengine import * import operator from flask_jwt import jwt_required, current_identity from flask_restful import reqparse, Resource from static import app_constant, status from models.comment import BaseComment from models.base_event import BaseEvent from models.action import BaseAction ...
0.387574
0.078254
from DAN_Task import DANetClassifier, DANetRegressor import argparse import os import torch.distributed import torch.backends.cudnn from sklearn.metrics import accuracy_score, mean_squared_error from data.dataset import get_data from lib.utils import normalize_reg_label from qhoptim.pyt import QHAdam from config.defaul...
main.py
from DAN_Task import DANetClassifier, DANetRegressor import argparse import os import torch.distributed import torch.backends.cudnn from sklearn.metrics import accuracy_score, mean_squared_error from data.dataset import get_data from lib.utils import normalize_reg_label from qhoptim.pyt import QHAdam from config.defaul...
0.635109
0.105533
import time import requests as requests from configparser import ConfigParser class Ticker: def __init__(self): config = ConfigParser() config.read_file(open('config.ini')) self.url = config['ticker']['url'] self.key = config['ticker']['responce_key'].split(',\n') def get_ti...
bitfinex/api/data.py
import time import requests as requests from configparser import ConfigParser class Ticker: def __init__(self): config = ConfigParser() config.read_file(open('config.ini')) self.url = config['ticker']['url'] self.key = config['ticker']['responce_key'].split(',\n') def get_ti...
0.21626
0.092647
import pprint import re # noqa: F401 import six from OsduClient.configuration import Configuration class FileToManyRelationship(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict):...
src/sdk/python/OsduClient/models/file_to_many_relationship.py
import pprint import re # noqa: F401 import six from OsduClient.configuration import Configuration class FileToManyRelationship(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict):...
0.744842
0.244577
import numpy as np import scipy import warnings import utils from . import model def compute_crlb(x_aoa, xs, cov): """ Computes the CRLB on position accuracy for source at location xs and sensors at locations in x_aoa (Ndim x N). C is an NxN matrix of TOA covariances at each of the N sensors. P...
triang/perf.py
import numpy as np import scipy import warnings import utils from . import model def compute_crlb(x_aoa, xs, cov): """ Computes the CRLB on position accuracy for source at location xs and sensors at locations in x_aoa (Ndim x N). C is an NxN matrix of TOA covariances at each of the N sensors. P...
0.794265
0.794604
from bsvlib.curve import multiply, curve, Point, get_y, negative, add def test(): x = 0xe46dcd7991e5a4bd642739249b0158312e1aee56a60fd1bf622172ffe65bd789 y = 0x97693d32c540ac253de7a3dc73f7e4ba7b38d2dc1ecc8e07920b496fb107d6b2 p = Point(x, y) k = 0xf97c89aaacf0cd2e47ddbacc97dae1f88bec49106ac37716c451dcdd...
tests/test_curve.py
from bsvlib.curve import multiply, curve, Point, get_y, negative, add def test(): x = 0xe46dcd7991e5a4bd642739249b0158312e1aee56a60fd1bf622172ffe65bd789 y = 0x97693d32c540ac253de7a3dc73f7e4ba7b38d2dc1ecc8e07920b496fb107d6b2 p = Point(x, y) k = 0xf97c89aaacf0cd2e47ddbacc97dae1f88bec49106ac37716c451dcdd...
0.750095
0.339485
from pprint import pformat from six import iteritems import re class CouponDefinition(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, created=None, changed_by=None, updated=None, id=None, crm_id=None, org...
billforward/models/coupon_definition.py
from pprint import pformat from six import iteritems import re class CouponDefinition(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, created=None, changed_by=None, updated=None, id=None, crm_id=None, org...
0.730482
0.099426
import sys def read_matriz_file(): file = open('input/matriz_exercicio_caderno.txt','r') dimensao = int(file.readline().replace('\n', '')) matriz = [] rows = file.read().splitlines() for line in rows: matriz.append(list(map(float,line.split(' ')))) return dimensao, matriz def read_veto...
EliminacaoDeGauss.py
import sys def read_matriz_file(): file = open('input/matriz_exercicio_caderno.txt','r') dimensao = int(file.readline().replace('\n', '')) matriz = [] rows = file.read().splitlines() for line in rows: matriz.append(list(map(float,line.split(' ')))) return dimensao, matriz def read_veto...
0.049268
0.523664
# Imports here... import numpy def compress(a, n): new_array = [] length = len(a) pool_size = length // n + (length % n != 0) for i in range(0, length, pool_size): new_array.append(numpy.mean(a[i: i + n])) return new_array # Classes here... class NeuralNetwork: def __init__(self, i...
neural_network.py
# Imports here... import numpy def compress(a, n): new_array = [] length = len(a) pool_size = length // n + (length % n != 0) for i in range(0, length, pool_size): new_array.append(numpy.mean(a[i: i + n])) return new_array # Classes here... class NeuralNetwork: def __init__(self, i...
0.744099
0.597667
import ctypes from itertools import product import numpy as np import sdl2 class Display: """Manager class to handle graphical output. Args: display_scale: Sets the scale factor of the graphics window. Attributes: pixel_buffer: Array of bools storing the current state of the pixel gr...
pychip8/display.py
import ctypes from itertools import product import numpy as np import sdl2 class Display: """Manager class to handle graphical output. Args: display_scale: Sets the scale factor of the graphics window. Attributes: pixel_buffer: Array of bools storing the current state of the pixel gr...
0.720172
0.1602
import flask import six from oslo_config import cfg from oslo_log import log from oslo_utils import uuidutils from werkzeug import exceptions as werkzeug_exceptions from hostha import context from hostha.i18n import _LE from hostha.api import v1 as api_v1 from hostha.common.utils import api as api_utils CONF = cfg.C...
hostha/api/app.py
import flask import six from oslo_config import cfg from oslo_log import log from oslo_utils import uuidutils from werkzeug import exceptions as werkzeug_exceptions from hostha import context from hostha.i18n import _LE from hostha.api import v1 as api_v1 from hostha.common.utils import api as api_utils CONF = cfg.C...
0.427994
0.065009
import random, os, sys, time, numpy from shapely import * from shapely.geometry import Point filename = 'radius_search.png' numberOfPoints = 1000 gridWidth = 10000 gridHeight = 10000 shapePoints = [] circleRadius = random.randint(500, 1500) circleX = random.randint(0, gridWidth) circleY = random.randint(0, gridHeight...
shapelyAreaSearch.py
import random, os, sys, time, numpy from shapely import * from shapely.geometry import Point filename = 'radius_search.png' numberOfPoints = 1000 gridWidth = 10000 gridHeight = 10000 shapePoints = [] circleRadius = random.randint(500, 1500) circleX = random.randint(0, gridWidth) circleY = random.randint(0, gridHeight...
0.279632
0.308555
import os import argparse import numpy as np import pyrender import open3d as o3d class OnscreenRenderer(object): def __init__(self): pass def __call__(self, scene): pyrender.Viewer(scene, use_raymond_lighting=True) def setup_scene_and_renderer(mode): """ This function returns a tuple ...
visual_data_pyrender.py
import os import argparse import numpy as np import pyrender import open3d as o3d class OnscreenRenderer(object): def __init__(self): pass def __call__(self, scene): pyrender.Viewer(scene, use_raymond_lighting=True) def setup_scene_and_renderer(mode): """ This function returns a tuple ...
0.539226
0.343342
import sys import codecs import setuptools from version import __version__ as version install_requires = [ 'beautifulsoup4', 'decorator', 'kitchen', 'requests >=2.4.0', # https://github.com/tildeclub/ttrv/issues/325 'six', ] tests_require = [ 'coveralls', 'pytest>=3.1.0', # Pinned for ...
setup.py
import sys import codecs import setuptools from version import __version__ as version install_requires = [ 'beautifulsoup4', 'decorator', 'kitchen', 'requests >=2.4.0', # https://github.com/tildeclub/ttrv/issues/325 'six', ] tests_require = [ 'coveralls', 'pytest>=3.1.0', # Pinned for ...
0.3027
0.202286
import mock import unittest from nambaone.bot import Bot from unittest.mock import patch, MagicMock from nambaone.exceptions import ClientException, FileDownloadException, FileUploadException class TestBot(unittest.TestCase): test_token = '<PASSWORD>' def setUp(self): self.bot = Bot(self.t...
tests/test_bot.py
import mock import unittest from nambaone.bot import Bot from unittest.mock import patch, MagicMock from nambaone.exceptions import ClientException, FileDownloadException, FileUploadException class TestBot(unittest.TestCase): test_token = '<PASSWORD>' def setUp(self): self.bot = Bot(self.t...
0.579638
0.265499
# Standard imports from enum import Enum, auto from typing import Union # Third party imports import numpy # Relative imports from ..utils.arrays import unique from ..utils.constants import DTYPE_BOOL, DTYPE_FLOAT, DTYPE_INT, DTYPE_UINT8, DTYPE_STR, TYPE_ARRAY class DataType(Enum): """ Enum of different kinds ...
bananas/dataset/datatype.py
# Standard imports from enum import Enum, auto from typing import Union # Third party imports import numpy # Relative imports from ..utils.arrays import unique from ..utils.constants import DTYPE_BOOL, DTYPE_FLOAT, DTYPE_INT, DTYPE_UINT8, DTYPE_STR, TYPE_ARRAY class DataType(Enum): """ Enum of different kinds ...
0.870968
0.712995
import os import sys import argparse import shutil #Globals g_includedFiles = [] class COLORS: DEFAULT = '\033[0m' HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' ERROR = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def printColor(text, color=COLORS.DEFAULT, resetColo...
verilog/runQflow.py
import os import sys import argparse import shutil #Globals g_includedFiles = [] class COLORS: DEFAULT = '\033[0m' HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' ERROR = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' def printColor(text, color=COLORS.DEFAULT, resetColo...
0.1661
0.08163
import jwt import re from flask import request, url_for, current_app, abort from flask_sqlalchemy import DefaultMeta, BaseQuery from functools import wraps from sqlalchemy.orm.attributes import InstrumentedAttribute from sqlalchemy.sql.expression import BinaryExpression from typing import Tuple from werkzeug.exceptions...
book_library_app/utils.py
import jwt import re from flask import request, url_for, current_app, abort from flask_sqlalchemy import DefaultMeta, BaseQuery from functools import wraps from sqlalchemy.orm.attributes import InstrumentedAttribute from sqlalchemy.sql.expression import BinaryExpression from typing import Tuple from werkzeug.exceptions...
0.646795
0.089296
from geometry_msgs.msg import WrenchStamped from baxter_core_msgs.msg import EndpointState import msg_filters import msg_filters_with_scaling import msg_filters_with_scaling_and_clip from rostopics_to_timeseries import RosTopicFilteringScheme from smach_based_introspection_framework.msg import tactile_static import ta...
src/smach_based_introspection_framework/offline_part/anomaly_classification_feature_selection/filtering_schemes.py
from geometry_msgs.msg import WrenchStamped from baxter_core_msgs.msg import EndpointState import msg_filters import msg_filters_with_scaling import msg_filters_with_scaling_and_clip from rostopics_to_timeseries import RosTopicFilteringScheme from smach_based_introspection_framework.msg import tactile_static import ta...
0.402627
0.135947
from telegram.ext import BaseFilter from work_materials.globals import dispatcher class FilterShadowLetter(BaseFilter): def filter(self, message): return message.text.find("/shadow_letter_") == 0 filter_shadow_letter= FilterShadowLetter() class FilterAwaitingShadowLetter(BaseFilter): def filter(self...
work_materials/filters/shadow_letter_filters.py
from telegram.ext import BaseFilter from work_materials.globals import dispatcher class FilterShadowLetter(BaseFilter): def filter(self, message): return message.text.find("/shadow_letter_") == 0 filter_shadow_letter= FilterShadowLetter() class FilterAwaitingShadowLetter(BaseFilter): def filter(self...
0.435061
0.094552
import os import sys root_path = "/".join(os.path.realpath(__file__).split("/")[:-2]) if root_path not in sys.path: sys.path.insert(0, root_path) import torch import time from bin.eval_model import eval_checkpoint def train(model, optimizer, train_dataloader, dev_dataloader, test_dataloader, config, ...
bin/train_model.py
import os import sys root_path = "/".join(os.path.realpath(__file__).split("/")[:-2]) if root_path not in sys.path: sys.path.insert(0, root_path) import torch import time from bin.eval_model import eval_checkpoint def train(model, optimizer, train_dataloader, dev_dataloader, test_dataloader, config, ...
0.427516
0.193033
import pytest import ipywidgets from hypothesis import strategies as st from hypothesis import given, settings from superintendent import controls from superintendent.controls import togglebuttongroup from superintendent.controls import hintedmultiselect DUMMY_KEYUP_DICT_ENTER = { "altKey": False, "ctrlKey...
tests/controls/test_multiclasssubmitter.py
import pytest import ipywidgets from hypothesis import strategies as st from hypothesis import given, settings from superintendent import controls from superintendent.controls import togglebuttongroup from superintendent.controls import hintedmultiselect DUMMY_KEYUP_DICT_ENTER = { "altKey": False, "ctrlKey...
0.563858
0.372534
from django.db import IntegrityError from celery.execute import send_task from .apitask import APITask from thing.models.apikey import APIKey from thing.models.character import Character from thing.models.mailmessage import MailMessage class MailMessages(APITask): name = 'thing.mail_messages' def run(sel...
thing/tasks/mailmessages.py
from django.db import IntegrityError from celery.execute import send_task from .apitask import APITask from thing.models.apikey import APIKey from thing.models.character import Character from thing.models.mailmessage import MailMessage class MailMessages(APITask): name = 'thing.mail_messages' def run(sel...
0.35768
0.089853
apiAttachAvailable = u'API jest dost\u0119pne' apiAttachNotAvailable = u'Niedost\u0119pny' apiAttachPendingAuthorization = u'Autoryzacja w toku' apiAttachRefused = u'Odmowa' apiAttachSuccess = u'Sukces' apiAttachUnknown = u'Nieznany' budDeletedFriend = u'Usuni\u0119ty z listy znajomych' budFriend = u'Znajomy' budNeverB...
Skype4Py/lang/pl.py
apiAttachAvailable = u'API jest dost\u0119pne' apiAttachNotAvailable = u'Niedost\u0119pny' apiAttachPendingAuthorization = u'Autoryzacja w toku' apiAttachRefused = u'Odmowa' apiAttachSuccess = u'Sukces' apiAttachUnknown = u'Nieznany' budDeletedFriend = u'Usuni\u0119ty z listy znajomych' budFriend = u'Znajomy' budNeverB...
0.134463
0.0524
import sys def formatFloat(flt): # Remove any trailing 0's. If that leaves just a period, remove it too. We # can't strip both at once otherwise '0.000' becomes '' and we want '0' return str(flt).rstrip('0').rstrip('.') class Node(object): def __init__(self): self._id = 0 self._idSet = False self._name = "...
python/ns/bridge/data/Brain.py
import sys def formatFloat(flt): # Remove any trailing 0's. If that leaves just a period, remove it too. We # can't strip both at once otherwise '0.000' becomes '' and we want '0' return str(flt).rstrip('0').rstrip('.') class Node(object): def __init__(self): self._id = 0 self._idSet = False self._name = "...
0.176459
0.156814
import asyncio import configparser import logging.handlers import os import re import sys from datetime import datetime, timedelta import telethon.events from telethon.tl.functions.channels import EditBannedRequest, GetParticipantRequest, LeaveChannelRequest from telethon.tl.functions.users import GetFullUserRequest ...
main.py
import asyncio import configparser import logging.handlers import os import re import sys from datetime import datetime, timedelta import telethon.events from telethon.tl.functions.channels import EditBannedRequest, GetParticipantRequest, LeaveChannelRequest from telethon.tl.functions.users import GetFullUserRequest ...
0.233794
0.045331
import psycopg2 from datetime import datetime import psycopg2 from funcionario import * class Departamento: def __init__(self,nome): self._nome = nome self._vinculo = [] def _get_nome(self): return self._nome def _get_vinculo(self): return self._vinculo ...
login/departamento.py
import psycopg2 from datetime import datetime import psycopg2 from funcionario import * class Departamento: def __init__(self,nome): self._nome = nome self._vinculo = [] def _get_nome(self): return self._nome def _get_vinculo(self): return self._vinculo ...
0.124905
0.091707
from .bodydeclaration import BodyDeclaration from ..type.classorinterfacetype import ClassOrInterfaceType from ..typeparameter import TypeParameter from . import _import class ConstructorDeclaration(BodyDeclaration): def __init__(self, kwargs={}): super(ConstructorDeclaration, self).__init__(kwargs) ...
jskparser/ast/body/constructordeclaration.py
from .bodydeclaration import BodyDeclaration from ..type.classorinterfacetype import ClassOrInterfaceType from ..typeparameter import TypeParameter from . import _import class ConstructorDeclaration(BodyDeclaration): def __init__(self, kwargs={}): super(ConstructorDeclaration, self).__init__(kwargs) ...
0.561455
0.215124
from random import Random from multiprocessing import cpu_count from inspyred import ec from optimModels.optimization import evaluators, generators, replacers, variators, observers from optimModels.utils.constantes import optimType class EAConfigurations: """ Basic configurations to Evolutionary Algorithm. ...
src/optimModels/optimization/evolutionary_computation.py
from random import Random from multiprocessing import cpu_count from inspyred import ec from optimModels.optimization import evaluators, generators, replacers, variators, observers from optimModels.utils.constantes import optimType class EAConfigurations: """ Basic configurations to Evolutionary Algorithm. ...
0.726134
0.285883
import numpy as np from batchgenerators.transforms import Compose, MirrorTransform from batchgenerators.transforms.crop_and_pad_transforms import CenterCropTransform, RandomCropTransform from batchgenerators.transforms.spatial_transforms import ResizeTransform, SpatialTransform from batchgenerators.transforms.utility_t...
datasets/two_dim/data_augmentation.py
import numpy as np from batchgenerators.transforms import Compose, MirrorTransform from batchgenerators.transforms.crop_and_pad_transforms import CenterCropTransform, RandomCropTransform from batchgenerators.transforms.spatial_transforms import ResizeTransform, SpatialTransform from batchgenerators.transforms.utility_t...
0.726426
0.682481
import collections import datetime import traceback from django.conf import settings from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from django.db.models import Q from django.utils import timezone from clubs.models import Club, ClubApplication, Membership, send_mail_h...
backend/clubs/management/commands/daily_notifications.py
import collections import datetime import traceback from django.conf import settings from django.contrib.auth.models import Group from django.core.management.base import BaseCommand from django.db.models import Q from django.utils import timezone from clubs.models import Club, ClubApplication, Membership, send_mail_h...
0.35488
0.099426
from __future__ import absolute_import, print_function, division import numpy as np class database(object): def __init__(self, params): self.size = params['db_size'] self.img_scale = params['img_scale'] self.states = np.zeros([self.size, 84, 84], dtype='uint8') # image dimensions ...
fathom/deepq/database.py
from __future__ import absolute_import, print_function, division import numpy as np class database(object): def __init__(self, params): self.size = params['db_size'] self.img_scale = params['img_scale'] self.states = np.zeros([self.size, 84, 84], dtype='uint8') # image dimensions ...
0.598312
0.179746
import numpy as np def Bresenham_line(ends): w, h = np.diff(ends, axis=0)[0] pt1, __ = ends x, y = pt1 longest = np.absolute(w) shortest = np.absolute(h) if w != 0: dx = int(np.absolute(w)/w) if h != 0: dy = int(np.absolute(h)/h) if not (longest > shortest...
LineDraw.py
import numpy as np def Bresenham_line(ends): w, h = np.diff(ends, axis=0)[0] pt1, __ = ends x, y = pt1 longest = np.absolute(w) shortest = np.absolute(h) if w != 0: dx = int(np.absolute(w)/w) if h != 0: dy = int(np.absolute(h)/h) if not (longest > shortest...
0.36659
0.490419
import time from typing import Generator import docker import pytest from tempo import Model, Pipeline from tempo.seldon import SeldonDockerRuntime from tempo.serve.loader import save from tempo.serve.metadata import RuntimeOptions @pytest.fixture def runtime() -> SeldonDockerRuntime: return SeldonDockerRuntime...
tests/seldon/docker/conftest.py
import time from typing import Generator import docker import pytest from tempo import Model, Pipeline from tempo.seldon import SeldonDockerRuntime from tempo.serve.loader import save from tempo.serve.metadata import RuntimeOptions @pytest.fixture def runtime() -> SeldonDockerRuntime: return SeldonDockerRuntime...
0.390127
0.317175
import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from torch.utils.data import Dataset from torch.utils.data import random_split from torchvision.utils import save_image import torchvision.transforms as transforms import os import io import numpy as np from zipp imp...
train_anime.py
import torch import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader from torch.utils.data import Dataset from torch.utils.data import random_split from torchvision.utils import save_image import torchvision.transforms as transforms import os import io import numpy as np from zipp imp...
0.89244
0.431464
from abc import ABC, abstractmethod from typing import Union, Tuple import datetime as dt class LocalDate(int, ABC): """ Represents a date within the calendar, with no reference to a particular time zone or time of day, and provides conversion to and from: * Integer year, month, and day of month ...
py/datacentric/date_time/local_date.py
from abc import ABC, abstractmethod from typing import Union, Tuple import datetime as dt class LocalDate(int, ABC): """ Represents a date within the calendar, with no reference to a particular time zone or time of day, and provides conversion to and from: * Integer year, month, and day of month ...
0.945292
0.692382
import typing import itertools import numpy as np from loguru import logger from skimage.measure import regionprops import SimpleITK as sitk def center_crop_object_mask(mask: np.ndarray, cshape: typing.Union[tuple, int], ) -> typing.List[tuple]: """ Creates indices to crop patche...
nndet/io/patching.py
import typing import itertools import numpy as np from loguru import logger from skimage.measure import regionprops import SimpleITK as sitk def center_crop_object_mask(mask: np.ndarray, cshape: typing.Union[tuple, int], ) -> typing.List[tuple]: """ Creates indices to crop patche...
0.856407
0.633013
import io import datetime from typing import TYPE_CHECKING, Optional, Union, Type, List, Dict, Awaitable from .base.http import HTTPRequestBase, EmptyObject from .model import Channel, Message, MessageReference, AllowedMentions, Snowflake, Embed, Attachment, Overwrite, \ Emoji, User, Interaction, InteractionRespons...
dico/api.py
import io import datetime from typing import TYPE_CHECKING, Optional, Union, Type, List, Dict, Awaitable from .base.http import HTTPRequestBase, EmptyObject from .model import Channel, Message, MessageReference, AllowedMentions, Snowflake, Embed, Attachment, Overwrite, \ Emoji, User, Interaction, InteractionRespons...
0.843992
0.154663
from argparse import ArgumentParser import hashlib import json import os import shutil def hash(data): m = hashlib.sha256() m.update(bytes(data, 'utf-8')) return m.hexdigest() if __name__ == '__main__': parser = ArgumentParser(description='Build image manifest') parser.add_argument('layers', na...
oci/build-image-manifest.py
from argparse import ArgumentParser import hashlib import json import os import shutil def hash(data): m = hashlib.sha256() m.update(bytes(data, 'utf-8')) return m.hexdigest() if __name__ == '__main__': parser = ArgumentParser(description='Build image manifest') parser.add_argument('layers', na...
0.567817
0.121113