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
__author__ = "<NAME>, <NAME>" __version__ = '$Id$' from pybrain.tools.example_tools import ExTools from pybrain.structure.modules.tanhlayer import TanhLayer from pybrain.tools.shortcuts import buildNetwork from pybrain.rl.environments.shipsteer import ShipSteeringEnvironment from pybrain.rl.environments.shipsteer imp...
examples/rl/environments/shipsteer/shipbench_pgpe.py
__author__ = "<NAME>, <NAME>" __version__ = '$Id$' from pybrain.tools.example_tools import ExTools from pybrain.structure.modules.tanhlayer import TanhLayer from pybrain.tools.shortcuts import buildNetwork from pybrain.rl.environments.shipsteer import ShipSteeringEnvironment from pybrain.rl.environments.shipsteer imp...
0.430267
0.167866
__all__ = [ 'RM_Peripheral_FEFILT1' ] from . static import Base_RM_Peripheral from . FEFILT1_register import * class RM_Peripheral_FEFILT1(Base_RM_Peripheral): def __init__(self, rmio, label): self.__dict__['zz_frozen'] = False super(RM_Peripheral_FEFILT1, self).__init__(rmio, label, ...
platform/radio/efr32_multiphy_configurator/host_py_rm_studio_internal/full/efr32xg25/revA0/FEFILT1.py
__all__ = [ 'RM_Peripheral_FEFILT1' ] from . static import Base_RM_Peripheral from . FEFILT1_register import * class RM_Peripheral_FEFILT1(Base_RM_Peripheral): def __init__(self, rmio, label): self.__dict__['zz_frozen'] = False super(RM_Peripheral_FEFILT1, self).__init__(rmio, label, ...
0.382372
0.078078
import pybullet as p import os import math class Car: def __init__(self, client): self.client = client f_name = os.path.join(os.path.dirname(__file__), 'simplecar.urdf') self.car = p.loadURDF(fileName=f_name, basePosition=[0, 0, 0.1], ...
rl_tracking/resources/car.py
import pybullet as p import os import math class Car: def __init__(self, client): self.client = client f_name = os.path.join(os.path.dirname(__file__), 'simplecar.urdf') self.car = p.loadURDF(fileName=f_name, basePosition=[0, 0, 0.1], ...
0.691289
0.242531
from functools import partial import math from typing import Optional, List import torch import torch.nn as nn from openfold.model.primitives import Linear, LayerNorm, Attention from openfold.model.dropout import ( DropoutRowwise, DropoutColumnwise, ) from openfold.model.pair_transition import PairTransition ...
openfold/model/template.py
from functools import partial import math from typing import Optional, List import torch import torch.nn as nn from openfold.model.primitives import Linear, LayerNorm, Attention from openfold.model.dropout import ( DropoutRowwise, DropoutColumnwise, ) from openfold.model.pair_transition import PairTransition ...
0.916764
0.341061
from requests import request BASE = "http://localhost:5001/" # Inserting Mango print('Inserting Mango') response = request(method='PUT', url=BASE + "api/fruitpal?commodity=mango&country=MX&fixed_overhead=32&variable_overhead=1.24") print(response.status_code, response.json()) response = request(method='PUT', url=BAS...
fruitpal/insert_data.py
from requests import request BASE = "http://localhost:5001/" # Inserting Mango print('Inserting Mango') response = request(method='PUT', url=BASE + "api/fruitpal?commodity=mango&country=MX&fixed_overhead=32&variable_overhead=1.24") print(response.status_code, response.json()) response = request(method='PUT', url=BAS...
0.2522
0.0666
import logging import io import base64 import requests import voluptuous as vol from homeassistant.components.notify import ( ATTR_TITLE, ATTR_TITLE_DEFAULT, ATTR_DATA, BaseNotificationService, PLATFORM_SCHEMA) from homeassistant.const import CONF_TIMEOUT import homeassistant.helpers.config_validation as cv ...
homeassistant/components/notify/nfandroidtv.py
import logging import io import base64 import requests import voluptuous as vol from homeassistant.components.notify import ( ATTR_TITLE, ATTR_TITLE_DEFAULT, ATTR_DATA, BaseNotificationService, PLATFORM_SCHEMA) from homeassistant.const import CONF_TIMEOUT import homeassistant.helpers.config_validation as cv ...
0.469034
0.128881
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._enums import * __all__ = [ 'ObservabilityConfigurationTag', 'ObservabilityConfigurationTraceConfiguration', 'ServiceAuthentication...
sdk/python/pulumi_aws_native/apprunner/outputs.py
import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from . import outputs from ._enums import * __all__ = [ 'ObservabilityConfigurationTag', 'ObservabilityConfigurationTraceConfiguration', 'ServiceAuthentication...
0.872239
0.064713
import requests, json, threading, logging logger = logging.getLogger(__name__) class Video: def __init__(self, track, videoJSON): if not videoJSON['id']['kind'] == 'youtube#video': raise Exception('JSON was not a Youtube Video') self.id = videoJSON['id']['videoId'] self.channelT...
spotitube/youtube.py
import requests, json, threading, logging logger = logging.getLogger(__name__) class Video: def __init__(self, track, videoJSON): if not videoJSON['id']['kind'] == 'youtube#video': raise Exception('JSON was not a Youtube Video') self.id = videoJSON['id']['videoId'] self.channelT...
0.453746
0.060308
from __future__ import absolute_import # Copyright (c) 2010-2016 openpyxl from .drawing import Drawing def bounding_box(bw, bh, w, h): """ Returns a tuple (new_width, new_height) which has the property that it fits within box_width and box_height and has (close to) the same aspect ratio as the origin...
lib/openpyxl/drawing/image.py
from __future__ import absolute_import # Copyright (c) 2010-2016 openpyxl from .drawing import Drawing def bounding_box(bw, bh, w, h): """ Returns a tuple (new_width, new_height) which has the property that it fits within box_width and box_height and has (close to) the same aspect ratio as the origin...
0.77373
0.185062
from datetime import date, datetime from os.path import abspath, dirname, join from pathlib import Path from typing import IO, TYPE_CHECKING, Any, BinaryIO, Dict, Iterable, List, Optional, Tuple, Union # iNaturalist URLs API_V0_BASE_URL = 'https://www.inaturalist.org' API_V1_BASE_URL = 'https://api.inaturalist.org/v1'...
pyinaturalist/constants.py
from datetime import date, datetime from os.path import abspath, dirname, join from pathlib import Path from typing import IO, TYPE_CHECKING, Any, BinaryIO, Dict, Iterable, List, Optional, Tuple, Union # iNaturalist URLs API_V0_BASE_URL = 'https://www.inaturalist.org' API_V1_BASE_URL = 'https://api.inaturalist.org/v1'...
0.562417
0.183942
import pytest from urlextract.urlextract_core import URLExtractError @pytest.mark.parametrize("limit", (2, None)) @pytest.mark.parametrize( "text, expected", [ ("Let's have URL http://janlipovsky.cz", ["http://janlipovsky.cz"]), ( "http://aa.com/b.html https://aa.com/bb.html", ...
tests/unit/test_limit.py
import pytest from urlextract.urlextract_core import URLExtractError @pytest.mark.parametrize("limit", (2, None)) @pytest.mark.parametrize( "text, expected", [ ("Let's have URL http://janlipovsky.cz", ["http://janlipovsky.cz"]), ( "http://aa.com/b.html https://aa.com/bb.html", ...
0.579638
0.5144
import unittest import blackjack class TestCard(unittest.TestCase): def setUp(self): self.cards = [] for i in range(52): self.cards.append(blackjack.Card(i)) def test_get_value(self): for index, card in enumerate(self.cards): card_num = index % 13 v...
tests/test_blackjack.py
import unittest import blackjack class TestCard(unittest.TestCase): def setUp(self): self.cards = [] for i in range(52): self.cards.append(blackjack.Card(i)) def test_get_value(self): for index, card in enumerate(self.cards): card_num = index % 13 v...
0.526099
0.501099
import time import clipboard import random as rd from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_...
data-translation/crawler.py
import time import clipboard import random as rd from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_...
0.314366
0.077692
from __future__ import absolute_import import datetime import functools import king_phisher.geoip as geoip import king_phisher.ipaddress as ipaddress import geoip2.errors import graphene.relay import graphene.types.utils import graphql.language.ast import graphql_relay.connection.arrayconnection __all__ = ('Connec...
king_phisher/server/graphql/types/misc.py
from __future__ import absolute_import import datetime import functools import king_phisher.geoip as geoip import king_phisher.ipaddress as ipaddress import geoip2.errors import graphene.relay import graphene.types.utils import graphql.language.ast import graphql_relay.connection.arrayconnection __all__ = ('Connec...
0.580114
0.101947
from typing import List, Iterable, Tuple import csv import os from fileutil import OMITTED_ADDITION, get_filename_addition, DELETED_ADDITION from outputresult import OutputResult def records_to_csv(output_path: str, rows: Iterable[List[str]]): """Writes rows to a csv file at the specified path. Args: ...
release_scripts/localization_scripts/csvutil.py
from typing import List, Iterable, Tuple import csv import os from fileutil import OMITTED_ADDITION, get_filename_addition, DELETED_ADDITION from outputresult import OutputResult def records_to_csv(output_path: str, rows: Iterable[List[str]]): """Writes rows to a csv file at the specified path. Args: ...
0.786377
0.310917
import FWCore.ParameterSet.Config as cms process = cms.Process("OWNPARTICLES") process.load("FWCore.MessageService.MessageLogger_cfi") process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) ) process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring('file:/user/geisler/RelVal...
CommonTools/RecoUtils/test/pf_pu_assomap_cfg.py
import FWCore.ParameterSet.Config as cms process = cms.Process("OWNPARTICLES") process.load("FWCore.MessageService.MessageLogger_cfi") process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) ) process.source = cms.Source("PoolSource", fileNames = cms.untracked.vstring('file:/user/geisler/RelVal...
0.3295
0.085556
# This is a parent class for handling serial devices. # It implements some common functions related to serial communication # such as open and close port, read and write, etc. # Serial parameters can include: # Baudrate, # No. of data bit, start bit, and stop bit # Parity: even, odd, none import serial import sys i...
SerialDevice.py
# This is a parent class for handling serial devices. # It implements some common functions related to serial communication # such as open and close port, read and write, etc. # Serial parameters can include: # Baudrate, # No. of data bit, start bit, and stop bit # Parity: even, odd, none import serial import sys i...
0.568056
0.30399
import numpy as np import skfuzzy as fuzz import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from skfuzzy import control as ctrl import scipy.io # Set for reproducibility np.random.seed(seed=123) loc_risk = ctrl.Antecedent(np.arange(0, 11, 1), 'loc_risk') maintenance = ...
data_gen.py
import numpy as np import skfuzzy as fuzz import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from skfuzzy import control as ctrl import scipy.io # Set for reproducibility np.random.seed(seed=123) loc_risk = ctrl.Antecedent(np.arange(0, 11, 1), 'loc_risk') maintenance = ...
0.425844
0.436862
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import time from ansible import constants as C from ansible.plugins.action import ActionBase from ansible.utils.vars import combine_vars class ActionModule(ActionBase): def _get_module_args(self, fact_module, tas...
virt/ansible-latest/lib/python2.7/site-packages/ansible/plugins/action/gather_facts.py
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import time from ansible import constants as C from ansible.plugins.action import ActionBase from ansible.utils.vars import combine_vars class ActionModule(ActionBase): def _get_module_args(self, fact_module, tas...
0.475849
0.091992
import os import sys from collections import OrderedDict from matplotlib import pyplot as plt from PIL import Image import numpy as np class History(): def __init__(self): self.epoch_log = [] self.batch_log = {} def update_epoch_log(self, log): if type(log) not in [OrderedDict]: ...
torchfit/utils.py
import os import sys from collections import OrderedDict from matplotlib import pyplot as plt from PIL import Image import numpy as np class History(): def __init__(self): self.epoch_log = [] self.batch_log = {} def update_epoch_log(self, log): if type(log) not in [OrderedDict]: ...
0.333937
0.189746
#Copyright 2013 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive license for use of this work by or on behalf of the U.S. Government. Export of this program may require a license from the United States Government. import pymongo import gridfs import pickle import Queue impor...
processing/updateTopicmodel.py
#Copyright 2013 Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive license for use of this work by or on behalf of the U.S. Government. Export of this program may require a license from the United States Government. import pymongo import gridfs import pickle import Queue impor...
0.352871
0.213172
import numpy as np def layer_final_forcings(OutputObj,input_forcings,ConfigOptions,MpiConfig): """ Function to perform basic layering of input forcings as they are processed. The logic works as following: 1.) As the parent calling program loops through the forcings for each layer for this times...
core/layeringMod.py
import numpy as np def layer_final_forcings(OutputObj,input_forcings,ConfigOptions,MpiConfig): """ Function to perform basic layering of input forcings as they are processed. The logic works as following: 1.) As the parent calling program loops through the forcings for each layer for this times...
0.623377
0.442877
import re import json import socket import os.path import logging from threading import Thread from logging.handlers import TimedRotatingFileHandler logging.basicConfig( level=logging.DEBUG, format="[%(levelname)s] [%(asctime)s] >> \n%(message)s", datefmt="%Y-%m-%d %H:%M:%S" ) class Bot: def __init__(...
bot/core.py
import re import json import socket import os.path import logging from threading import Thread from logging.handlers import TimedRotatingFileHandler logging.basicConfig( level=logging.DEBUG, format="[%(levelname)s] [%(asctime)s] >> \n%(message)s", datefmt="%Y-%m-%d %H:%M:%S" ) class Bot: def __init__(...
0.261897
0.0771
from collections import OrderedDict from django.db.models import F from mep.books.models import CreatorType, Work from mep.common.management.export import BaseExport from mep.common.utils import absolutize_url class Command(BaseExport): '''Export book data.''' help = __doc__ model = Work # get a c...
mep/books/management/commands/export_books.py
from collections import OrderedDict from django.db.models import F from mep.books.models import CreatorType, Work from mep.common.management.export import BaseExport from mep.common.utils import absolutize_url class Command(BaseExport): '''Export book data.''' help = __doc__ model = Work # get a c...
0.564699
0.248318
from collections import defaultdict from bs4 import BeautifulSoup from nltk import word_tokenize import nltk from stopwords import * import os import time import sys nltk.download('punkt') OFF_SET_NEIGHBOUR = 20 def remove_non_text_elements(soup): for script in soup(["script", "style", "link", "iframe", "noscri...
implementation-indexing/run-basic-search.py
from collections import defaultdict from bs4 import BeautifulSoup from nltk import word_tokenize import nltk from stopwords import * import os import time import sys nltk.download('punkt') OFF_SET_NEIGHBOUR = 20 def remove_non_text_elements(soup): for script in soup(["script", "style", "link", "iframe", "noscri...
0.242116
0.123471
__author__ = "<NAME>" __contact__ = "University of Freiburg, IMTEK, <NAME>" __credits__ = "<NAME>" __version__ = "1.0.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>, <EMAIL>" # Import dependencies from tkinter import * from tkinter.ttk import * from FreiStat.Data_storage.constants import * import FreiStat as FS im...
Python/FreiStat_GUI/PopUp_Window/__init__.py
__author__ = "<NAME>" __contact__ = "University of Freiburg, IMTEK, <NAME>" __credits__ = "<NAME>" __version__ = "1.0.0" __maintainer__ = "<NAME>" __email__ = "<EMAIL>, <EMAIL>" # Import dependencies from tkinter import * from tkinter.ttk import * from FreiStat.Data_storage.constants import * import FreiStat as FS im...
0.501465
0.068257
from pandac.PandaModules import * from direct.interval.IntervalGlobal import * from direct.particles import ParticleEffect from direct.particles import Particles from EffectController import EffectController from PooledEffect import PooledEffect from otp.otpbase import OTPRender from pirates.audio import SoundGlobals f...
pirates/effects/MonkeyPanic.py
from pandac.PandaModules import * from direct.interval.IntervalGlobal import * from direct.particles import ParticleEffect from direct.particles import Particles from EffectController import EffectController from PooledEffect import PooledEffect from otp.otpbase import OTPRender from pirates.audio import SoundGlobals f...
0.649245
0.15034
from logging import getLogger from datetime import datetime from traceback import format_exc from collections import OrderedDict from codecs import open as open_with_encoding from inflection import titleize from .utils import get_file, count_lines log = getLogger(__name__) REGISTRY_URL = 'https://www.tse.go.cr/zi...
lib/tse2sql/readers.py
from logging import getLogger from datetime import datetime from traceback import format_exc from collections import OrderedDict from codecs import open as open_with_encoding from inflection import titleize from .utils import get_file, count_lines log = getLogger(__name__) REGISTRY_URL = 'https://www.tse.go.cr/zi...
0.608478
0.296893
import numpy as np import xarray as xr def generate_mcmc_like_dataset(seed=None): """Generate a Dataset with multiple variables, some with dimensions from mcmc sampling. Parameters ---------- seed : int or sequence of int, optional The random seed used to initialize :func:`numpy.random.defaul...
src/xarray_einstats/tutorial.py
import numpy as np import xarray as xr def generate_mcmc_like_dataset(seed=None): """Generate a Dataset with multiple variables, some with dimensions from mcmc sampling. Parameters ---------- seed : int or sequence of int, optional The random seed used to initialize :func:`numpy.random.defaul...
0.918162
0.669252
import sys from math import floor from os import environ, getcwd from os.path import dirname, realpath, join, exists from flask import Flask, render_template, request, redirect, session from datetime import datetime, timezone, timedelta sys.path.insert(0, realpath(join(getcwd(), dirname(__file__)))) import google_au...
sms2web/__init__.py
import sys from math import floor from os import environ, getcwd from os.path import dirname, realpath, join, exists from flask import Flask, render_template, request, redirect, session from datetime import datetime, timezone, timedelta sys.path.insert(0, realpath(join(getcwd(), dirname(__file__)))) import google_au...
0.35031
0.057493
from __future__ import absolute_import, division, print_function from operator import itemgetter from cctbx.sgtbx.direct_space_asu import cut_plane from cctbx.array_family import flex from scitbx import matrix import scitbx.math from boost_adaptbx.boost import rational from six.moves import range from six.moves import ...
cctbx/sgtbx/direct_space_asu/facet_analysis.py
from __future__ import absolute_import, division, print_function from operator import itemgetter from cctbx.sgtbx.direct_space_asu import cut_plane from cctbx.array_family import flex from scitbx import matrix import scitbx.math from boost_adaptbx.boost import rational from six.moves import range from six.moves import ...
0.402862
0.32861
import json from aioquant import const from aioquant.utils import logger class Orderbook: """Orderbook object. Args: platform: Exchange platform name, e.g. `binance` / `bitmex`. symbol: Trade pair name, e.g. `ETH/BTC`. asks: Asks list, e.g. `[[price, quantity], [...], ...]` b...
aioquant/market.py
import json from aioquant import const from aioquant.utils import logger class Orderbook: """Orderbook object. Args: platform: Exchange platform name, e.g. `binance` / `bitmex`. symbol: Trade pair name, e.g. `ETH/BTC`. asks: Asks list, e.g. `[[price, quantity], [...], ...]` b...
0.90196
0.389982
from typing import Dict,Sequence,List from dmt.entity import Entity from dmt.blueprint import Blueprint from .blueprints.dofcontrolconfiguration import DOFControlConfigurationBlueprint from typing import Dict from sima.sima.moao import MOAO from sima.sima.scriptablevalue import ScriptableValue from sima.simo.controldof...
src/sima/simo/dofcontrolconfiguration.py
from typing import Dict,Sequence,List from dmt.entity import Entity from dmt.blueprint import Blueprint from .blueprints.dofcontrolconfiguration import DOFControlConfigurationBlueprint from typing import Dict from sima.sima.moao import MOAO from sima.sima.scriptablevalue import ScriptableValue from sima.simo.controldof...
0.882466
0.539711
import numpy as np class Color: """ Lists of known colors. """ colors = { 'red': (1., 0., 0.), 'green': (0., 1., 0.), 'blue': (0., 0., 1.), 'white': (1., 1., 1.), 'black': (0., 0., 0.), 'darkblue': '#00008b', } def __init__(self, name): ...
src/pyensae/graphhelper/_colormap.py
import numpy as np class Color: """ Lists of known colors. """ colors = { 'red': (1., 0., 0.), 'green': (0., 1., 0.), 'blue': (0., 0., 1.), 'white': (1., 1., 1.), 'black': (0., 0., 0.), 'darkblue': '#00008b', } def __init__(self, name): ...
0.882326
0.439747
import pytest import mindspore.dataset as ds from mindspore import log as logger from util import config_get_set_num_parallel_workers, config_get_set_seed DATA_DIR = '../data/dataset/testCoNLL2000Dataset' def test_conll2000_dataset_one_file(): """ Feature: CoNLL2000ChunkingDataset. Description: test par...
tests/ut/python/dataset/test_datasets_conll2000.py
import pytest import mindspore.dataset as ds from mindspore import log as logger from util import config_get_set_num_parallel_workers, config_get_set_seed DATA_DIR = '../data/dataset/testCoNLL2000Dataset' def test_conll2000_dataset_one_file(): """ Feature: CoNLL2000ChunkingDataset. Description: test par...
0.377311
0.504883
import os import re import subprocess from contextlib import contextmanager from os.path import expandvars from pathlib import Path from typing import Optional, Union import cpuinfo import psutil from codecarbon.external.logger import logger def is_jetson(): return os.path.isdir('/sys/bus/i2c/drivers/ina3221x/0...
codecarbon/core/util.py
import os import re import subprocess from contextlib import contextmanager from os.path import expandvars from pathlib import Path from typing import Optional, Union import cpuinfo import psutil from codecarbon.external.logger import logger def is_jetson(): return os.path.isdir('/sys/bus/i2c/drivers/ina3221x/0...
0.708213
0.212661
import json import os import cv2 import numpy as np from pynif3d import logger from pynif3d.common.verification import ( check_in_options, check_lengths_match, check_path_exists, check_pos_int, ) from pynif3d.datasets.base_dataset import BaseDataset from pynif3d.log.log_funcs import func_logger clas...
pynif3d/datasets/blender.py
import json import os import cv2 import numpy as np from pynif3d import logger from pynif3d.common.verification import ( check_in_options, check_lengths_match, check_path_exists, check_pos_int, ) from pynif3d.datasets.base_dataset import BaseDataset from pynif3d.log.log_funcs import func_logger clas...
0.692746
0.452173
## First, some preliminaries that will be needed. import hashlib def sha512(s): return hashlib.sha512(s).digest() # Base field Z_p p = 2 ** 255 - 19 def modp_inv(x): return pow(x, p - 2, p) # Curve constant d = -121665 * modp_inv(121666) % p # Group order q = 2 ** 252 + 27742317777372353535851937790...
hydrand/ed25519_ref/__init__.py
## First, some preliminaries that will be needed. import hashlib def sha512(s): return hashlib.sha512(s).digest() # Base field Z_p p = 2 ** 255 - 19 def modp_inv(x): return pow(x, p - 2, p) # Curve constant d = -121665 * modp_inv(121666) % p # Group order q = 2 ** 252 + 27742317777372353535851937790...
0.719778
0.51946
import pytest import tempfile from contextlib import suppress from requests.exceptions import HTTPError import numpy as np import pandas as pd from astropy import units as u from astropy.coordinates import SkyCoord from huntsman.drp import refcat as rc @pytest.fixture(scope="function") def ra_list(): return [30...
src/huntsman/drp/tests/test_refcat.py
import pytest import tempfile from contextlib import suppress from requests.exceptions import HTTPError import numpy as np import pandas as pd from astropy import units as u from astropy.coordinates import SkyCoord from huntsman.drp import refcat as rc @pytest.fixture(scope="function") def ra_list(): return [30...
0.624294
0.403449
# pylint: disable=unused-argument import logging import unittest from devil import devil_env from devil.android import cpu_temperature from devil.android import device_utils from devil.utils import mock_calls from devil.android.sdk import adb_wrapper with devil_env.SysPath(devil_env.PYMOCK_PATH): import mock # py...
devil/devil/android/cpu_temperature_test.py
# pylint: disable=unused-argument import logging import unittest from devil import devil_env from devil.android import cpu_temperature from devil.android import device_utils from devil.utils import mock_calls from devil.android.sdk import adb_wrapper with devil_env.SysPath(devil_env.PYMOCK_PATH): import mock # py...
0.613584
0.216985
from telethon import events from telethon.errors.rpcerrorlist import YouBlockedUserError from telethon.tl.functions.account import UpdateNotifySettingsRequest from darkbot import bot, CmdHelp from darkbot.utils import admin_cmd, edit_or_reply as eor, sudo_cmd @darkbot.on(admin_cmd(pattern="history ?(.*)")) @darkbot.on...
userbot/plugins/history.py
from telethon import events from telethon.errors.rpcerrorlist import YouBlockedUserError from telethon.tl.functions.account import UpdateNotifySettingsRequest from darkbot import bot, CmdHelp from darkbot.utils import admin_cmd, edit_or_reply as eor, sudo_cmd @darkbot.on(admin_cmd(pattern="history ?(.*)")) @darkbot.on...
0.233969
0.094971
import math from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from urllib.parse import unquote app = FastAPI() origins = [ "http://localhost:3000", "localhost:3000", "http://192.168.100.14:3000", "https://calculator-react-ui.herokuapp.com" ] app.add_middleware( CORS...
app/api.py
import math from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from urllib.parse import unquote app = FastAPI() origins = [ "http://localhost:3000", "localhost:3000", "http://192.168.100.14:3000", "https://calculator-react-ui.herokuapp.com" ] app.add_middleware( CORS...
0.630571
0.32744
import pandas as pd from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score from sklearn.metrics import roc_auc_score import joblib as job from matplotlib import pyplot as plt from sklearn.metrics import confusi...
src/models/helpers.py
import pandas as pd from sklearn.metrics import accuracy_score from sklearn.metrics import precision_score from sklearn.metrics import recall_score from sklearn.metrics import f1_score from sklearn.metrics import roc_auc_score import joblib as job from matplotlib import pyplot as plt from sklearn.metrics import confusi...
0.631481
0.423816
import numpy as np import pandas as pd import scipy.stats as stats import h5py as h5 from tensorsignatures.config import * from tensorsignatures.util import * import subprocess import os class TensorSignatureData(object): r"""Makes sample data for TensorSignatures Args: seed (:obj:`int`): Seed for s...
tensorsignatures/data.py
import numpy as np import pandas as pd import scipy.stats as stats import h5py as h5 from tensorsignatures.config import * from tensorsignatures.util import * import subprocess import os class TensorSignatureData(object): r"""Makes sample data for TensorSignatures Args: seed (:obj:`int`): Seed for s...
0.847621
0.44089
from typing import Any, Dict from dataclasses import dataclass from flask import request import marshmallow as ma from ....util.import_helpers import get_all_classes_of_module from ...base_models import BaseApiObject, MaBaseSchema, ApiResponseSchema, ApiObjectSchema __all__ = [] class SchemaField(ma.fields.Fiel...
muse_for_anything/api/v1_api/models/schema.py
from typing import Any, Dict from dataclasses import dataclass from flask import request import marshmallow as ma from ....util.import_helpers import get_all_classes_of_module from ...base_models import BaseApiObject, MaBaseSchema, ApiResponseSchema, ApiObjectSchema __all__ = [] class SchemaField(ma.fields.Fiel...
0.778607
0.242412
__author__ = "<NAME>" __email__ = "<EMAIL>" import time class Driver(object): """Agilent N6705B Power Supply - Driver specific Class.""" def __init__(self, inst, cfg=None): """Initialize the specific driver.""" self.i = inst if not cfg: self.i.set_error("Configuration File for this instrument ...
instruments/AgilentN6705B.py
__author__ = "<NAME>" __email__ = "<EMAIL>" import time class Driver(object): """Agilent N6705B Power Supply - Driver specific Class.""" def __init__(self, inst, cfg=None): """Initialize the specific driver.""" self.i = inst if not cfg: self.i.set_error("Configuration File for this instrument ...
0.721645
0.161816
import haiku as hk import jax import jax.numpy as jnp import numpy as np from functools import partial import optax from jax.experimental.maps import mesh from jax.experimental import PartitionSpec from jax.experimental.pjit import pjit from clip_model import TextCLIP import clip_jax def cfg_encode_text(config, tok...
clip_trainer.py
import haiku as hk import jax import jax.numpy as jnp import numpy as np from functools import partial import optax from jax.experimental.maps import mesh from jax.experimental import PartitionSpec from jax.experimental.pjit import pjit from clip_model import TextCLIP import clip_jax def cfg_encode_text(config, tok...
0.828315
0.29476
import urllib, re import json import api class Module(api.Module): '''A module for preforming web lookups of various facts. Responds to "what is" questings best''' urls = { 'ddg': 'https://duckduckgo.com/?q=%s&o=json&d=1', 'fb': 'https://api.freebase.com/api/experimental/topic/standard?id=...
modules/ddgbot.py
import urllib, re import json import api class Module(api.Module): '''A module for preforming web lookups of various facts. Responds to "what is" questings best''' urls = { 'ddg': 'https://duckduckgo.com/?q=%s&o=json&d=1', 'fb': 'https://api.freebase.com/api/experimental/topic/standard?id=...
0.211254
0.132515
import re # noqa: F401 import sys # noqa: F401 from multiprocessing.pool import ApplyResult import typing from fds.sdk.ProcuretoPaySCIM.api_client import ApiClient, Endpoint as _Endpoint from fds.sdk.ProcuretoPaySCIM.model_utils import ( # noqa: F401 check_allowed_values, check_validations, date, da...
code/python/ProcuretoPaySCIM/v1/fds/sdk/ProcuretoPaySCIM/api/groups_api.py
import re # noqa: F401 import sys # noqa: F401 from multiprocessing.pool import ApplyResult import typing from fds.sdk.ProcuretoPaySCIM.api_client import ApiClient, Endpoint as _Endpoint from fds.sdk.ProcuretoPaySCIM.model_utils import ( # noqa: F401 check_allowed_values, check_validations, date, da...
0.303009
0.093471
from __future__ import print_function from .utils import * from .types import * import msgpackrpc import threading import warnings warnings.simplefilter("ignore", DeprecationWarning) class VehicleClient: mutex = threading.Lock() def __init__(self, ip="", port=41451, timeout_value=3600): if ip == ...
dronesim/client.py
from __future__ import print_function from .utils import * from .types import * import msgpackrpc import threading import warnings warnings.simplefilter("ignore", DeprecationWarning) class VehicleClient: mutex = threading.Lock() def __init__(self, ip="", port=41451, timeout_value=3600): if ip == ...
0.588653
0.053206
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( ...
src/imageboard/migrations/0001_initial.py
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( ...
0.542863
0.194119
import datetime import numpy as np import pandas as pd class ModelObject(object): """Generic class for holding forecasting models. Models should all have methods: .fit(df, future_regressor = []) (taking a DataFrame with DatetimeIndex and n columns of n timeseries) .predict(forecast_length = i...
autots/models/base.py
import datetime import numpy as np import pandas as pd class ModelObject(object): """Generic class for holding forecasting models. Models should all have methods: .fit(df, future_regressor = []) (taking a DataFrame with DatetimeIndex and n columns of n timeseries) .predict(forecast_length = i...
0.894624
0.404978
import sys, getopt import io import datetime import requests import json apikey = 'local-e5ee347a4ba5' fromSite = 'revima' toSite = 'insight' tag = 'REP202' toLayoutId=557327 def getEvent(e): urlGetEvent = 'https://'+fromSite+'.flightwatching.com/fleet/apiv3/events/'+str(e['id']) print(urlGetEvent) params...
python/copyRevima2InsightApuCosts.py
import sys, getopt import io import datetime import requests import json apikey = 'local-e5ee347a4ba5' fromSite = 'revima' toSite = 'insight' tag = 'REP202' toLayoutId=557327 def getEvent(e): urlGetEvent = 'https://'+fromSite+'.flightwatching.com/fleet/apiv3/events/'+str(e['id']) print(urlGetEvent) params...
0.081406
0.111483
import json from geslo import sifriraj_geslo PARAM_FMT = ":{}" class Ekol: ''' Razred, ki predstavlja tabelo v bazi. Polja razreda: - ime: ime tabele - podatki: ime datoteke s podatki ali None ''' ime = None podatki = None def __init__(self, conn): ...
baza.py
import json from geslo import sifriraj_geslo PARAM_FMT = ":{}" class Ekol: ''' Razred, ki predstavlja tabelo v bazi. Polja razreda: - ime: ime tabele - podatki: ime datoteke s podatki ali None ''' ime = None podatki = None def __init__(self, conn): ...
0.146942
0.213951
from _skelet_functions import * def worst_case_strategy(guesses, answer, possibilities=None): if len(guesses) < 1: remaining_answers = create_list_of_combinations(COMBINATIONS, 4) guess = remaining_answers[7] feedback = feedback_calculate(answer, guess) else: remaining_answer...
_worst_case_strategy.py
from _skelet_functions import * def worst_case_strategy(guesses, answer, possibilities=None): if len(guesses) < 1: remaining_answers = create_list_of_combinations(COMBINATIONS, 4) guess = remaining_answers[7] feedback = feedback_calculate(answer, guess) else: remaining_answer...
0.441432
0.517144
from .printing import PybnfError from subprocess import run, TimeoutExpired, Popen, PIPE, STDOUT, CalledProcessError, DEVNULL import logging import re import time import numpy as np from multiprocessing import cpu_count logger = logging.getLogger(__name__) def get_scheduler(config): """ :param config: PyB...
pybnf/cluster.py
from .printing import PybnfError from subprocess import run, TimeoutExpired, Popen, PIPE, STDOUT, CalledProcessError, DEVNULL import logging import re import time import numpy as np from multiprocessing import cpu_count logger = logging.getLogger(__name__) def get_scheduler(config): """ :param config: PyB...
0.494629
0.099383
import os import shutil from dataclasses import dataclass import logging import numpy as np import tables from phd.satellite.satellite_pb2 import MeanRun from phd.utils.run_tools import InputData from tables import open_file, Filters, File logger = logging.getLogger(__name__) class MeanTable: def __init__(self, ...
python/phd/satellite/mean_table.py
import os import shutil from dataclasses import dataclass import logging import numpy as np import tables from phd.satellite.satellite_pb2 import MeanRun from phd.utils.run_tools import InputData from tables import open_file, Filters, File logger = logging.getLogger(__name__) class MeanTable: def __init__(self, ...
0.546012
0.283769
from redis_support_py3.graph_query_support_py3 import Query_Support from redis_support_py3.construct_data_handlers_py3 import Generate_Handlers import datetime import msgpack class Construct_RPC_Library(object): def __init__( self, qs, site_data ): self.site_data = site_data ...
flask_web/sqlite_library/sqlite_server_lib_py3.py
from redis_support_py3.graph_query_support_py3 import Query_Support from redis_support_py3.construct_data_handlers_py3 import Generate_Handlers import datetime import msgpack class Construct_RPC_Library(object): def __init__( self, qs, site_data ): self.site_data = site_data ...
0.141667
0.086555
from argparse import ArgumentParser import glob import os from .config import ConfigReader, ReadingError from .dispatcher import Dispatcher, DispatchError from .logging import Level from .logging import Logger from .util import module def add_options(parser): """ Adds all options to the specified parser. :par...
dotwerke/cli.py
from argparse import ArgumentParser import glob import os from .config import ConfigReader, ReadingError from .dispatcher import Dispatcher, DispatchError from .logging import Level from .logging import Logger from .util import module def add_options(parser): """ Adds all options to the specified parser. :par...
0.53048
0.068164
from __future__ import absolute_import, division, print_function, unicode_literals from django.conf import settings from django.core.exceptions import ImproperlyConfigured from pkg_resources import DistributionNotFound, get_distribution from haystack import signals from haystack.constants import DEFAULT_ALIA...
oscar/lib/python2.7/site-packages/haystack/__init__.py
from __future__ import absolute_import, division, print_function, unicode_literals from django.conf import settings from django.core.exceptions import ImproperlyConfigured from pkg_resources import DistributionNotFound, get_distribution from haystack import signals from haystack.constants import DEFAULT_ALIA...
0.475362
0.051344
import numpy as np import pandas as pd from six import string_types class DummyCurve(object): def __init__(self, datas): """ Parse a curvedata format :param datas: list of dicts """ if isinstance(datas, (list, tuple)): pass for data in datas: ...
mesures/parsers/dummy_data.py
import numpy as np import pandas as pd from six import string_types class DummyCurve(object): def __init__(self, datas): """ Parse a curvedata format :param datas: list of dicts """ if isinstance(datas, (list, tuple)): pass for data in datas: ...
0.272508
0.411702
import urllib, requests class AniSearch(object): ## REQUIRED : urllib , requests def __init__(self, path): self.pic_path = path self.b64img = None self.season = None; self.anime = None def image_b64(self): with open(self.pic_path, 'rb') as img_file: encode_str = img_file.read() self.b6...
Image2Anime.py
import urllib, requests class AniSearch(object): ## REQUIRED : urllib , requests def __init__(self, path): self.pic_path = path self.b64img = None self.season = None; self.anime = None def image_b64(self): with open(self.pic_path, 'rb') as img_file: encode_str = img_file.read() self.b6...
0.179315
0.078997
from django.contrib.auth import get_user_model from django.contrib.auth.password_validation import validate_password from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers, exceptions from .models.user_model import Account from .models.models import Country from .password_confi...
mysite/account/serializers.py
from django.contrib.auth import get_user_model from django.contrib.auth.password_validation import validate_password from django.utils.translation import ugettext_lazy as _ from rest_framework import serializers, exceptions from .models.user_model import Account from .models.models import Country from .password_confi...
0.38885
0.134378
import csv from decimal import * import math from math import * import sys import numpy from numpy import * from argparse import ArgumentParser def main(): # Ground Truth and Measurement Path parser = ArgumentParser() parser.add_argument("-g", "--ground-truth", nargs='+', help="the ground truth csv file y...
evaluate.py
import csv from decimal import * import math from math import * import sys import numpy from numpy import * from argparse import ArgumentParser def main(): # Ground Truth and Measurement Path parser = ArgumentParser() parser.add_argument("-g", "--ground-truth", nargs='+', help="the ground truth csv file y...
0.295027
0.309402
import pyglet from pybox.graphics import window class GameWindow(window.Window): def __init__(self, registry, *args, **kwargs): super().__init__(*args, **kwargs) self._registry = registry self._keys = pyglet.window.key.KeyStateHandler() self.push_handlers(self._keys) # V...
app/window.py
import pyglet from pybox.graphics import window class GameWindow(window.Window): def __init__(self, registry, *args, **kwargs): super().__init__(*args, **kwargs) self._registry = registry self._keys = pyglet.window.key.KeyStateHandler() self.push_handlers(self._keys) # V...
0.541894
0.199327
base_folder = '%DVT_ROOT%/' caffevis_deploy_prototxt = base_folder + './models/bvlc-googlenet/bvlc-googlenet-deploy.prototxt' caffevis_network_weights = base_folder + './models/bvlc-googlenet/bvlc_googlenet.caffemodel' caffevis_data_mean = (104, 117, 123) # input images static_files_dir = base_folder + './input_...
model_settings/settings_bvlc_googlenet.py
base_folder = '%DVT_ROOT%/' caffevis_deploy_prototxt = base_folder + './models/bvlc-googlenet/bvlc-googlenet-deploy.prototxt' caffevis_network_weights = base_folder + './models/bvlc-googlenet/bvlc_googlenet.caffemodel' caffevis_data_mean = (104, 117, 123) # input images static_files_dir = base_folder + './input_...
0.391522
0.052207
import uuid import json import logging import falcon import falcon.request import drydock_provisioner.error as errors class BaseResource(object): def __init__(self): self.logger = logging.getLogger('drydock') def on_options(self, req, resp): self_attrs = dir(self) methods = ['GET', ...
drydock_provisioner/control/base.py
import uuid import json import logging import falcon import falcon.request import drydock_provisioner.error as errors class BaseResource(object): def __init__(self): self.logger = logging.getLogger('drydock') def on_options(self, req, resp): self_attrs = dir(self) methods = ['GET', ...
0.373762
0.060668
import numpy as np from lenstronomy.ImSim.MultiBand.single_band_multi_model import SingleBandMultiModel from lenstronomy.ImSim.MultiBand.multi_linear import MultiLinear from lenstronomy.ImSim.MultiBand.joint_linear import JointLinear class ImageLikelihood(object): """ manages imaging data likelihoods """ ...
lenstronomy/Sampling/Likelihoods/image_likelihood.py
import numpy as np from lenstronomy.ImSim.MultiBand.single_band_multi_model import SingleBandMultiModel from lenstronomy.ImSim.MultiBand.multi_linear import MultiLinear from lenstronomy.ImSim.MultiBand.joint_linear import JointLinear class ImageLikelihood(object): """ manages imaging data likelihoods """ ...
0.877122
0.549882
from .mpi_p2p_mp.base_framework.algorithm_api import FedML_Base_distributed from .mpi_p2p_mp.decentralized_framework.algorithm_api import ( FedML_Decentralized_Demo_distributed, ) from .mpi_p2p_mp.fedavg.FedAvgAPI import FedML_FedAvg_distributed from .mpi_p2p_mp.fedavg_robust.FedAvgRobustAPI import FedML_FedAvgRobu...
python/fedml/simulation/simulator.py
from .mpi_p2p_mp.base_framework.algorithm_api import FedML_Base_distributed from .mpi_p2p_mp.decentralized_framework.algorithm_api import ( FedML_Decentralized_Demo_distributed, ) from .mpi_p2p_mp.fedavg.FedAvgAPI import FedML_FedAvg_distributed from .mpi_p2p_mp.fedavg_robust.FedAvgRobustAPI import FedML_FedAvgRobu...
0.486332
0.090937
import abc import asyncio import subprocess from time import sleep from . import logger from .constants import VOLUME_FADE_SECONDS try: import alsaaudio # pylint: disable=import-error except: pass def cap(volume, _min=1, _max=100): return min(max(volume, _min), _max) class VolumeControl(abc.ABC): ...
spfy/volume.py
import abc import asyncio import subprocess from time import sleep from . import logger from .constants import VOLUME_FADE_SECONDS try: import alsaaudio # pylint: disable=import-error except: pass def cap(volume, _min=1, _max=100): return min(max(volume, _min), _max) class VolumeControl(abc.ABC): ...
0.53607
0.144964
import os import sys # add project dir to path BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) from absl import flags from absl import app import numpy as np from pprint import pprint from meta_learn.util import get_logger from experiments.util import * from experiment...
experiments/meta_overfitting_v2/neural_processes_overfitting_base.py
import os import sys # add project dir to path BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) from absl import flags from absl import app import numpy as np from pprint import pprint from meta_learn.util import get_logger from experiments.util import * from experiment...
0.448909
0.238406
from airflow.operators.dummy_operator import DummyOperator from airflow.operators.python_operator import BranchPythonOperator from airflow.utils.trigger_rule import TriggerRule from liminal.runners.airflow.model import task from liminal.runners.airflow.operators.cloudformation import CloudFormationDeleteStackOperator,...
liminal/runners/airflow/tasks/delete_cloudformation_stack.py
from airflow.operators.dummy_operator import DummyOperator from airflow.operators.python_operator import BranchPythonOperator from airflow.utils.trigger_rule import TriggerRule from liminal.runners.airflow.model import task from liminal.runners.airflow.operators.cloudformation import CloudFormationDeleteStackOperator,...
0.675658
0.239972
# Como comer um gigante.... é com um pedaço de cada vez. # Na hora de fazer este exercicio, atentar para # Com o arquivo de cadastro.txt onde possui os seguintes dados: codigo cliente, nome, idade, sexo, e-mail e telefone # 1 - Crie um metodo que gere e retorne uma lista com bibliotecas com os dados dos clientes # 2...
Aula_19/exercicio3.py
# Como comer um gigante.... é com um pedaço de cada vez. # Na hora de fazer este exercicio, atentar para # Com o arquivo de cadastro.txt onde possui os seguintes dados: codigo cliente, nome, idade, sexo, e-mail e telefone # 1 - Crie um metodo que gere e retorne uma lista com bibliotecas com os dados dos clientes # 2...
0.214116
0.471284
import logging from datetime import timedelta # Django Imports from django.core.exceptions import ValidationError from django.test import TestCase from django.utils import timezone # Ghostwriter Libraries from ghostwriter.api.models import APIKey from ghostwriter.factories import UserFactory logging.disable(logging....
ghostwriter/api/tests/test_models.py
import logging from datetime import timedelta # Django Imports from django.core.exceptions import ValidationError from django.test import TestCase from django.utils import timezone # Ghostwriter Libraries from ghostwriter.api.models import APIKey from ghostwriter.factories import UserFactory logging.disable(logging....
0.704058
0.185892
import os import mock from oslotest import base as test_base from ironic_python_agent import errors from ironic_python_agent import numa_inspector as numa_insp from ironic_python_agent import utils class TestCollectNumaTopologyInfo(test_base.BaseTestCase): def setUp(self): super(TestCollectNumaTopology...
ironic_python_agent/tests/unit/test_numa_inspector.py
import os import mock from oslotest import base as test_base from ironic_python_agent import errors from ironic_python_agent import numa_inspector as numa_insp from ironic_python_agent import utils class TestCollectNumaTopologyInfo(test_base.BaseTestCase): def setUp(self): super(TestCollectNumaTopology...
0.400515
0.282005
import M2Crypto import base64 import urllib from flask import current_app import hashlib import urllib2 from sharper.flaskapp.template import decimal_pretty from bg_biz.service.config_service import ConfigService from bg_biz.pay.sign.rsa import RSASigner import json from sharper.util import encrypt_util from bg_biz.or...
bg_biz/pay/hiwifipay.py
import M2Crypto import base64 import urllib from flask import current_app import hashlib import urllib2 from sharper.flaskapp.template import decimal_pretty from bg_biz.service.config_service import ConfigService from bg_biz.pay.sign.rsa import RSASigner import json from sharper.util import encrypt_util from bg_biz.or...
0.196248
0.078395
from abc import ABCMeta, abstractmethod from pyalgs.algorithms.graphs.topological_sort import DepthFirstOrder from pyalgs.data_structures.graphs.graph import EdgeWeightedGraph, Digraph, DirectedEdgeWeightedGraph class ConnectedComponents(object): marked = None _id = None _count = 0 def __init__(self...
pyalgs/algorithms/graphs/connectivity.py
from abc import ABCMeta, abstractmethod from pyalgs.algorithms.graphs.topological_sort import DepthFirstOrder from pyalgs.data_structures.graphs.graph import EdgeWeightedGraph, Digraph, DirectedEdgeWeightedGraph class ConnectedComponents(object): marked = None _id = None _count = 0 def __init__(self...
0.835584
0.284126
import re import sys import os import math import numpy as np import pandas as pd from .fluxmap import fluxMap # For binning the proton list x/y values def readCarlo(fname, bin_um = 320): """ Read in and histogram a Carlo's blob.out proton radiography file. Looks for a file in the same directory which specifie...
pradreader/rdcarlo.py
import re import sys import os import math import numpy as np import pandas as pd from .fluxmap import fluxMap # For binning the proton list x/y values def readCarlo(fname, bin_um = 320): """ Read in and histogram a Carlo's blob.out proton radiography file. Looks for a file in the same directory which specifie...
0.531696
0.547706
import numpy as np from scipy.stats import norm, truncnorm class TransitionKernel(): ''' A transition kernel on a random variable (or a set of RVs) stores the current value of the RV, propose() will propose a new RV by setting the value attribute, and return forward and backward transition log probability. reve...
7dof_arm_reaching/kernel.py
import numpy as np from scipy.stats import norm, truncnorm class TransitionKernel(): ''' A transition kernel on a random variable (or a set of RVs) stores the current value of the RV, propose() will propose a new RV by setting the value attribute, and return forward and backward transition log probability. reve...
0.832747
0.667717
import time from copy import deepcopy import torch import torch.optim as optim from Utils.evaluation import evaluation, LOO_print_result, print_final_result from Utils.loss import relaxed_ranking_loss from Utils.data_utils import T_annealing def LOO_IR_RRD_run(opt, model, gpu, optimizer, train_loader, te...
models/Knowledge-Distillation/DE-RRD/run.py
import time from copy import deepcopy import torch import torch.optim as optim from Utils.evaluation import evaluation, LOO_print_result, print_final_result from Utils.loss import relaxed_ranking_loss from Utils.data_utils import T_annealing def LOO_IR_RRD_run(opt, model, gpu, optimizer, train_loader, te...
0.465873
0.228156
import requests import base64 import re #_url = 'https://qaq.link/' #_proxies = {} #_headers = {} #_auth = ('<PASSWORD>', '<PASSWORD>') _url = 'http://wwww.xxxxxx.com' _proxies = {'http': 'http://127.0.0.1:2081/', 'https': 'http://127.0.0.1:2081/'} # 改代理 _headers = {'Cookie': 'PHPSESSID=fbg7079bj6...
thinkphp5.0.1-automatic-getshell-master/tp_exp.py
import requests import base64 import re #_url = 'https://qaq.link/' #_proxies = {} #_headers = {} #_auth = ('<PASSWORD>', '<PASSWORD>') _url = 'http://wwww.xxxxxx.com' _proxies = {'http': 'http://127.0.0.1:2081/', 'https': 'http://127.0.0.1:2081/'} # 改代理 _headers = {'Cookie': 'PHPSESSID=fbg7079bj6...
0.085819
0.071624
import collections import os.path import sys def find_ancestor_with(relpath, start_path=None): """Returns the lowest ancestor of this file that contains |relpath|.""" cur_dir_path = start_path or os.path.abspath(os.path.dirname(__file__)) while True: if os.path.exists(os.path.join(cur_dir_path, relpath)): ...
mojo/devtools/common/devtoolslib/paths.py
import collections import os.path import sys def find_ancestor_with(relpath, start_path=None): """Returns the lowest ancestor of this file that contains |relpath|.""" cur_dir_path = start_path or os.path.abspath(os.path.dirname(__file__)) while True: if os.path.exists(os.path.join(cur_dir_path, relpath)): ...
0.524882
0.139807
import onnx from onnx import helper from onnx import AttributeProto, TensorProto, GraphProto, OperatorSetIdProto from onnx import numpy_helper import numpy as np vocab_size=256 #30258 X = helper.make_tensor_value_info('input', TensorProto.FLOAT, ["batch", "seqlen", 128]) unsqueezed_masked_lm_positions = helper.make_t...
onnxruntime/test/testdata/transform/computation_reduction/e2e.py
import onnx from onnx import helper from onnx import AttributeProto, TensorProto, GraphProto, OperatorSetIdProto from onnx import numpy_helper import numpy as np vocab_size=256 #30258 X = helper.make_tensor_value_info('input', TensorProto.FLOAT, ["batch", "seqlen", 128]) unsqueezed_masked_lm_positions = helper.make_t...
0.466603
0.528959
import os import sys import pandas as pd # Gathers results of all simulations of a single simulation batch # (10 replicates for each of n coverage level) # and places into a single summary file DIRECTORY = sys.argv[1] PREFIX = sys.argv[2] WDIR = "/lustre/scratch/npaulat/ESAT" COVERAGE = DIRECTORY.split("_")[1] WDI...
simulations/merge_ESAT_flag_stats.py
import os import sys import pandas as pd # Gathers results of all simulations of a single simulation batch # (10 replicates for each of n coverage level) # and places into a single summary file DIRECTORY = sys.argv[1] PREFIX = sys.argv[2] WDIR = "/lustre/scratch/npaulat/ESAT" COVERAGE = DIRECTORY.split("_")[1] WDI...
0.106342
0.205775
import collections """Functions for infection rates""" import tensorflow as tf import tensorflow_probability as tfp from tensorflow_probability.python.internal import dtype_util import numpy as np from covid.rdata import load_mobility_matrix, load_population, load_age_mixing from covid.pydata import load_commute_volum...
covid/model_nonflat.py
import collections """Functions for infection rates""" import tensorflow as tf import tensorflow_probability as tfp from tensorflow_probability.python.internal import dtype_util import numpy as np from covid.rdata import load_mobility_matrix, load_population, load_age_mixing from covid.pydata import load_commute_volum...
0.784195
0.565659
import json from django.core import mail from .. import test from ...acl.test import patch_user_acl from ...users.test import create_test_user from ..models import Thread, ThreadParticipant from ..test import other_user_cant_use_private_threads from .test_privatethreads import PrivateThreadsTestCase class PrivateTh...
misago/misago/threads/tests/test_privatethread_patch_api.py
import json from django.core import mail from .. import test from ...acl.test import patch_user_acl from ...users.test import create_test_user from ..models import Thread, ThreadParticipant from ..test import other_user_cant_use_private_threads from .test_privatethreads import PrivateThreadsTestCase class PrivateTh...
0.447943
0.200793
import argparse from github_archive import GithubArchive from github_archive.constants import DEFAULT_LOCATION, DEFAULT_NUM_THREADS, DEFAULT_TIMEOUT class GithubArchiveCli: def __init__(self): parser = argparse.ArgumentParser( description=( 'A powerful tool to concurrently clo...
github_archive/cli.py
import argparse from github_archive import GithubArchive from github_archive.constants import DEFAULT_LOCATION, DEFAULT_NUM_THREADS, DEFAULT_TIMEOUT class GithubArchiveCli: def __init__(self): parser = argparse.ArgumentParser( description=( 'A powerful tool to concurrently clo...
0.28577
0.090937
import logging import pulpcore.client.pulp_rpm from pulpcore.client.pulp_rpm.rest import ApiException from pulp_operations.api_client_conf import rpm_configuration from pulp_operations.task import wait_for_task_complete #module logger - child of parent logger 'pulp_operations' mlogger = logging.getLogger('pulp_operat...
pulp_operations/content.py
import logging import pulpcore.client.pulp_rpm from pulpcore.client.pulp_rpm.rest import ApiException from pulp_operations.api_client_conf import rpm_configuration from pulp_operations.task import wait_for_task_complete #module logger - child of parent logger 'pulp_operations' mlogger = logging.getLogger('pulp_operat...
0.651355
0.086709
import numpy as np import torch as torch from torch.utils.data import Dataset from nuscenes.nuscenes import NuScenes from nuscenes.utils.geometry_utils import transform_matrix from nuscenes.utils.data_classes import PointCloud, LidarPointCloud from pyquaternion import Quaternion import os.path as osp from functools imp...
nuscenes_dataset.py
import numpy as np import torch as torch from torch.utils.data import Dataset from nuscenes.nuscenes import NuScenes from nuscenes.utils.geometry_utils import transform_matrix from nuscenes.utils.data_classes import PointCloud, LidarPointCloud from pyquaternion import Quaternion import os.path as osp from functools imp...
0.79546
0.449997
# parseratproxy function def parseratproxy(time, os, etree, filetoread, db, dbconnection, projectname, projectid, separator): import string ratproxymessages = "xml" + separator + "ratproxymessages.xml" if os.path.isfile(ratproxymessages): pass else: print "The following file does not exist:", ratproxymes...
src/lib/parsers/parseratproxy.py
# parseratproxy function def parseratproxy(time, os, etree, filetoread, db, dbconnection, projectname, projectid, separator): import string ratproxymessages = "xml" + separator + "ratproxymessages.xml" if os.path.isfile(ratproxymessages): pass else: print "The following file does not exist:", ratproxymes...
0.107145
0.090374
import xml.etree.ElementTree as ET import numpy as np def get_bb_of_gt_from_pascal_xml_annotation(xml_name, voc_path): string = voc_path + '/Annotations/' + xml_name + '.xml' tree = ET.parse(string) root = tree.getroot() names = [] x_min = [] x_max = [] y_min = [] y_max = [] for ch...
scripts/parse_xml_annotations.py
import xml.etree.ElementTree as ET import numpy as np def get_bb_of_gt_from_pascal_xml_annotation(xml_name, voc_path): string = voc_path + '/Annotations/' + xml_name + '.xml' tree = ET.parse(string) root = tree.getroot() names = [] x_min = [] x_max = [] y_min = [] y_max = [] for ch...
0.225246
0.323674
import os from ACSLogging import LOGGER_FWK from acs.Core.PathManager import Folders import acs.UtilitiesFWK.Utilities as Util class CampaignReportTree(object): """ CampaignReportTree class gives the access to folder created in _Reports for the current campaign """ def __init__(self, campaign_name=...
acs/acs/Core/Report/CampaignReportTree.py
import os from ACSLogging import LOGGER_FWK from acs.Core.PathManager import Folders import acs.UtilitiesFWK.Utilities as Util class CampaignReportTree(object): """ CampaignReportTree class gives the access to folder created in _Reports for the current campaign """ def __init__(self, campaign_name=...
0.651909
0.080069
import numpy as np from numpy.random import rand import copy import itertools class Kohonen(object): def __init__(self, gridWidth, epochs, alphaStart=0.5, alphaEnd=0.001): self.gridWidth = gridWidth self.epochs = epochs self.alphaStart = alphaStart self.alphaEnd = alphaEnd ...
kohonen.py
import numpy as np from numpy.random import rand import copy import itertools class Kohonen(object): def __init__(self, gridWidth, epochs, alphaStart=0.5, alphaEnd=0.001): self.gridWidth = gridWidth self.epochs = epochs self.alphaStart = alphaStart self.alphaEnd = alphaEnd ...
0.751192
0.51379
import itertools from collections import Counter # 计算皇家同花顺需要的牌 def find_royal_flush_cards(visible_cards: list): existing_cards = [] possible_cards = [] # 至少要先能凑成同花 possible_suit = is_flush_possible(visible_cards) if possible_suit != '': for card in visible_cards: if card[0] == ...
MatchFinder.py
import itertools from collections import Counter # 计算皇家同花顺需要的牌 def find_royal_flush_cards(visible_cards: list): existing_cards = [] possible_cards = [] # 至少要先能凑成同花 possible_suit = is_flush_possible(visible_cards) if possible_suit != '': for card in visible_cards: if card[0] == ...
0.164651
0.232093
from collections import namedtuple import datetime import pymssql from tqdm import tqdm import pandas as pd class DBConnector(object): def __init__(self, db_name, db_settings={}): self.db_settings = db_settings self.db_settings['database'] = db_name self.db_conn = None ...
utilities/database/db_connector.py
from collections import namedtuple import datetime import pymssql from tqdm import tqdm import pandas as pd class DBConnector(object): def __init__(self, db_name, db_settings={}): self.db_settings = db_settings self.db_settings['database'] = db_name self.db_conn = None ...
0.420719
0.110136
import numpy as np import pandas as pd import cmasher as cmr import plotly.express as px import plotly.graph_objects as go from scipy.interpolate import RegularGridInterpolator from scipy.interpolate import CubicSpline from gofish import imagecube from matplotlib import cm from matplotlib.colors import ListedColormap,...
trivia.py
import numpy as np import pandas as pd import cmasher as cmr import plotly.express as px import plotly.graph_objects as go from scipy.interpolate import RegularGridInterpolator from scipy.interpolate import CubicSpline from gofish import imagecube from matplotlib import cm from matplotlib.colors import ListedColormap,...
0.800224
0.480296
import inspect import textwrap from pyiron.base.job.generic import GenericJob """ The GenericMaster is the template class for all meta jobs """ __author__ = "<NAME>" __copyright__ = ( "Copyright 2020, Max-Planck-Institut für Eisenforschung GmbH - " "Computational Materials Design (CM) Department" ) __version...
pyiron/base/master/generic.py
import inspect import textwrap from pyiron.base.job.generic import GenericJob """ The GenericMaster is the template class for all meta jobs """ __author__ = "<NAME>" __copyright__ = ( "Copyright 2020, Max-Planck-Institut für Eisenforschung GmbH - " "Computational Materials Design (CM) Department" ) __version...
0.814975
0.2522
import os from cliar import set_arg_map, set_metavars, set_help, ignore from pathlib import Path import webbrowser from foliant.cli import make from foliant.cli.base import BaseCli from foliant.config import Parser from foliant.utils import spinner from pydrive.auth import GoogleAuth from pydrive.drive import Google...
foliant/cli/gupload.py
import os from cliar import set_arg_map, set_metavars, set_help, ignore from pathlib import Path import webbrowser from foliant.cli import make from foliant.cli.base import BaseCli from foliant.config import Parser from foliant.utils import spinner from pydrive.auth import GoogleAuth from pydrive.drive import Google...
0.247169
0.054049
from subprocess import Popen, PIPE import re # Inspired by http://alloutput.com/amateur-radio/aprs-notes/ class DWParser: ''' Manage collecting and parsing audio signals with Direwolf ''' def __init__(self): ''' Constructor Defaults to Direwolf settings for Enhanced Plus mode and 2x sampling, ...
Database/DWParser.py
from subprocess import Popen, PIPE import re # Inspired by http://alloutput.com/amateur-radio/aprs-notes/ class DWParser: ''' Manage collecting and parsing audio signals with Direwolf ''' def __init__(self): ''' Constructor Defaults to Direwolf settings for Enhanced Plus mode and 2x sampling, ...
0.249264
0.18924
import json import datetime import numpy as np from nupic.frameworks.opf.model_factory import ModelFactory from nupic.frameworks.opf.common_models.cluster_params import getScalarMetricWithTimeOfDayAnomalyParams class stream_anomaly_detect(): """ stream data anomaly detect for one field. """ def __i...
hit-gd-anomaly-detection/src/main/python/HTM/AnomalyDetection/algorithm/streamAnomalyDetect.py
import json import datetime import numpy as np from nupic.frameworks.opf.model_factory import ModelFactory from nupic.frameworks.opf.common_models.cluster_params import getScalarMetricWithTimeOfDayAnomalyParams class stream_anomaly_detect(): """ stream data anomaly detect for one field. """ def __i...
0.737914
0.375621