code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
from indra.util import _require_python3 import os import sys from random import shuffle from indra.sources import biopax import indra.tools.assemble_corpus as ac from indra.assemblers import CxAssembler from indra.literature.pubmed_client import get_ids_for_gene base_network = 'PAR1-mediated thrombin signaling events...
models/gpcr/assemble_model.py
from indra.util import _require_python3 import os import sys from random import shuffle from indra.sources import biopax import indra.tools.assemble_corpus as ac from indra.assemblers import CxAssembler from indra.literature.pubmed_client import get_ids_for_gene base_network = 'PAR1-mediated thrombin signaling events...
0.244183
0.102529
import os import subprocess import threading import time import datetime # Import the GPIO library so python can work with the GPIO pins import RPi.GPIO as GPIO # Debug flags DEBUG_FAN = False # Debug print def debug(flag, str): if flag: print(str) # These values need to be provided in the container ...
fanctrl.py
import os import subprocess import threading import time import datetime # Import the GPIO library so python can work with the GPIO pins import RPi.GPIO as GPIO # Debug flags DEBUG_FAN = False # Debug print def debug(flag, str): if flag: print(str) # These values need to be provided in the container ...
0.205695
0.078254
from cwbot.modules.BaseDungeonModule import BaseDungeonModule from cwbot.common.exceptions import FatalError from cwbot.util.textProcessing import intOrFloatToString from cwbot.common.kmailContainer import Kmail from collections import defaultdict import re import random import copy def _nameKey(x): re...
cwbot/modules/oldcw/DreadPointsModule.py
from cwbot.modules.BaseDungeonModule import BaseDungeonModule from cwbot.common.exceptions import FatalError from cwbot.util.textProcessing import intOrFloatToString from cwbot.common.kmailContainer import Kmail from collections import defaultdict import re import random import copy def _nameKey(x): re...
0.463444
0.089694
"""API for the senlin service.""" from django.views import generic from openstack_dashboard.api.rest import urls from openstack_dashboard.api.rest import utils as rest_utils from senlin_dashboard.api import senlin from senlin_dashboard.api import utils as api_utils from senlin_dashboard.cluster.nodes import forms as ...
senlin_dashboard/api/rest/senlin.py
"""API for the senlin service.""" from django.views import generic from openstack_dashboard.api.rest import urls from openstack_dashboard.api.rest import utils as rest_utils from senlin_dashboard.api import senlin from senlin_dashboard.api import utils as api_utils from senlin_dashboard.cluster.nodes import forms as ...
0.779532
0.143908
import unittest from sumatra.core import _Registry as Registry class TestRegistry(unittest.TestCase): def setUp(self): self.registry = Registry.__new__(Registry) # hack to create new instance for each test self.registry.__init__() class ComponentBaseType(object): required_attribut...
test/unittests/test_core.py
import unittest from sumatra.core import _Registry as Registry class TestRegistry(unittest.TestCase): def setUp(self): self.registry = Registry.__new__(Registry) # hack to create new instance for each test self.registry.__init__() class ComponentBaseType(object): required_attribut...
0.659515
0.356979
import re import time def readTrainTxt(filename): f = open(filename, "r+") positive = [] negative = [] for line in f.readlines(): lineContent = line.split("\t") if(len(lineContent) != 2): continue if lineContent[0] == "1": positive.append(lineContent[1]....
PRNN/Assignment/Assignment1/textClassification.py
import re import time def readTrainTxt(filename): f = open(filename, "r+") positive = [] negative = [] for line in f.readlines(): lineContent = line.split("\t") if(len(lineContent) != 2): continue if lineContent[0] == "1": positive.append(lineContent[1]....
0.374676
0.245221
import os import json import boto3 import sys import datetime import hashlib import secrets import time table_name = os.environ['DDB_TABLE'] ddb_client = boto3.client('dynamodb') ses_client = boto3.client('ses') sns_client = boto3.client('sns') sender = os.environ['SENDER'] unsubscribe_url = os.environ['UNSUBSCRIBE_U...
functions/create_user.py
import os import json import boto3 import sys import datetime import hashlib import secrets import time table_name = os.environ['DDB_TABLE'] ddb_client = boto3.client('dynamodb') ses_client = boto3.client('ses') sns_client = boto3.client('sns') sender = os.environ['SENDER'] unsubscribe_url = os.environ['UNSUBSCRIBE_U...
0.153137
0.070816
import Doberman import datetime from socket import getfqdn import time import requests __all__ = 'Database'.split() dtnow = Doberman.utils.dtnow class Database(object): """ Class to handle interfacing with the Doberman database """ def __init__(self, mongo_client, experiment_name=None): sel...
Doberman/Database.py
import Doberman import datetime from socket import getfqdn import time import requests __all__ = 'Database'.split() dtnow = Doberman.utils.dtnow class Database(object): """ Class to handle interfacing with the Doberman database """ def __init__(self, mongo_client, experiment_name=None): sel...
0.63477
0.163679
import socket import struct from unittest import mock from oslo_config import cfg from oslo_config import fixture as oslo_fixture from octavia.cmd import health_checker from octavia.tests.common import utils as test_utils from octavia.tests.unit import base CONF = cfg.CONF class TestHealthCheckerCMD(base.TestCase)...
octavia/tests/unit/cmd/test_health_checker.py
import socket import struct from unittest import mock from oslo_config import cfg from oslo_config import fixture as oslo_fixture from octavia.cmd import health_checker from octavia.tests.common import utils as test_utils from octavia.tests.unit import base CONF = cfg.CONF class TestHealthCheckerCMD(base.TestCase)...
0.539711
0.31563
import logging import os import subprocess import uuid import time import docker import pytest from sklearn import svm, datasets from bentoml.deployment.utils import ensure_docker_available_or_raise from bentoml.configuration import PREV_PYPI_RELEASE_VERSION from bentoml.utils.tempdir import TempDirectory from e2e_te...
e2e_tests/conftest.py
import logging import os import subprocess import uuid import time import docker import pytest from sklearn import svm, datasets from bentoml.deployment.utils import ensure_docker_available_or_raise from bentoml.configuration import PREV_PYPI_RELEASE_VERSION from bentoml.utils.tempdir import TempDirectory from e2e_te...
0.356111
0.182335
from __future__ import absolute_import from threading import Thread from typing import List import numpy as np from .control import ControlThread, Controls from .image import ImageThread from .location import LocationThread class DroneServerThread(Thread): """Custom thread class containing everything needed for...
communication/src/drone/__init__.py
from __future__ import absolute_import from threading import Thread from typing import List import numpy as np from .control import ControlThread, Controls from .image import ImageThread from .location import LocationThread class DroneServerThread(Thread): """Custom thread class containing everything needed for...
0.863679
0.249185
import nipype.pipeline.engine as pe from spynoza.io.bids import collect_data from IPython import embed from spynoza.io.bids import BIDSGrabber from nipype.interfaces import mipav from nipype.interfaces import fsl from nipype.interfaces import io as nio from nipype.interfaces import utility as niu from spynoza.utils imp...
src/scripts/mipav_hybrid.py
import nipype.pipeline.engine as pe from spynoza.io.bids import collect_data from IPython import embed from spynoza.io.bids import BIDSGrabber from nipype.interfaces import mipav from nipype.interfaces import fsl from nipype.interfaces import io as nio from nipype.interfaces import utility as niu from spynoza.utils imp...
0.295027
0.186373
from typing import Any, Dict, List, Optional from functools import lru_cache import datetime import json import re from jinja2 import Environment, FileSystemLoader import praw import requests from bot import * import daily_markov NWS_FORECAST_URL = 'https://api.weather.gov/gridpoints/SEW/123,68/forecast' class Em...
daily_post.py
from typing import Any, Dict, List, Optional from functools import lru_cache import datetime import json import re from jinja2 import Environment, FileSystemLoader import praw import requests from bot import * import daily_markov NWS_FORECAST_URL = 'https://api.weather.gov/gridpoints/SEW/123,68/forecast' class Em...
0.628179
0.200989
import tea ''' Want to see if Wrestling is correlated with greater athlete Weight than Swimming, and if Female athletes have a lower Weight than Male athletes. ''' data_path = "./athlete_events_cleaned_weight.csv" variables = [ { 'name': 'ID', 'data type': 'ratio' }, { 'name': '...
examples/Olympics/olympics_tea.py
import tea ''' Want to see if Wrestling is correlated with greater athlete Weight than Swimming, and if Female athletes have a lower Weight than Male athletes. ''' data_path = "./athlete_events_cleaned_weight.csv" variables = [ { 'name': 'ID', 'data type': 'ratio' }, { 'name': '...
0.390243
0.400339
import random from typing import List import pytest from entities import Window, Option, Session, GeneratedWindow, Request from exceptions import InvalidSelectedOptionError from lottus import LottusContext, SessionProvider, GeneratedWindowProvider, Lottus from processors import default_processor def create_lottus_a...
test_lottus.py
import random from typing import List import pytest from entities import Window, Option, Session, GeneratedWindow, Request from exceptions import InvalidSelectedOptionError from lottus import LottusContext, SessionProvider, GeneratedWindowProvider, Lottus from processors import default_processor def create_lottus_a...
0.727395
0.18374
from unittest import mock from fastapi import FastAPI from fastapi.testclient import TestClient from authx.routers import get_auth_router from tests.utils import ( ACCESS_COOKIE_NAME, REFRESH_COOKIE_NAME, MockAuthBackend, mock_get_authenticated_user, private_key, public_key, ) app = FastAPI()...
tests/routers/test_routers_auth.py
from unittest import mock from fastapi import FastAPI from fastapi.testclient import TestClient from authx.routers import get_auth_router from tests.utils import ( ACCESS_COOKIE_NAME, REFRESH_COOKIE_NAME, MockAuthBackend, mock_get_authenticated_user, private_key, public_key, ) app = FastAPI()...
0.44553
0.236235
from flask import Flask, request, jsonify from datetime import datetime from pymodm import connect, MongoModel, fields import PIL connect("mongodb+srv://brad_howard:<EMAIL>" "/final_database?retryWrites=true&w=majority") app = Flask(__name__) class Patient(MongoModel): mr_number = fields.IntegerField(...
project_server.py
from flask import Flask, request, jsonify from datetime import datetime from pymodm import connect, MongoModel, fields import PIL connect("mongodb+srv://brad_howard:<EMAIL>" "/final_database?retryWrites=true&w=majority") app = Flask(__name__) class Patient(MongoModel): mr_number = fields.IntegerField(...
0.744099
0.344857
from flask import Flask, abort, make_response, render_template, url_for from io import BytesIO import openslide from openslide import ImageSlide, open_slide from openslide.deepzoom import DeepZoomGenerator from optparse import OptionParser import re from unicodedata import normalize DEEPZOOM_SLIDE = None DEEPZOOM_FOR...
python_scribbles/slideServer.py
from flask import Flask, abort, make_response, render_template, url_for from io import BytesIO import openslide from openslide import ImageSlide, open_slide from openslide.deepzoom import DeepZoomGenerator from optparse import OptionParser import re from unicodedata import normalize DEEPZOOM_SLIDE = None DEEPZOOM_FOR...
0.500488
0.08772
from jaxline import base_config from ml_collections import config_dict def get_config(debug: bool = False) -> config_dict.ConfigDict: """Get Jaxline experiment config.""" config = base_config.get_base_config() config.random_seed = 42 # E.g. '/data/pretrained_models/k0_seed100' (and set k_fold_split_id=0, belo...
ogb_lsc/mag/config.py
from jaxline import base_config from ml_collections import config_dict def get_config(debug: bool = False) -> config_dict.ConfigDict: """Get Jaxline experiment config.""" config = base_config.get_base_config() config.random_seed = 42 # E.g. '/data/pretrained_models/k0_seed100' (and set k_fold_split_id=0, belo...
0.59843
0.080683
import pytest from grizzly_extras.arguments import split_value, get_unsupported_arguments, parse_arguments, unquote @pytest.mark.parametrize('separator', ['|', ', ']) def test_split_value(separator: str) -> None: assert split_value(f'hello world {separator} foo bar', separator) == ('hello world', 'foo bar',) ...
tests/test_grizzly_extras/test_arguments.py
import pytest from grizzly_extras.arguments import split_value, get_unsupported_arguments, parse_arguments, unquote @pytest.mark.parametrize('separator', ['|', ', ']) def test_split_value(separator: str) -> None: assert split_value(f'hello world {separator} foo bar', separator) == ('hello world', 'foo bar',) ...
0.68458
0.744958
import asyncio import os import time import re from subprocess import Popen, PIPE, check_output from luma.core.interface.serial import i2c from luma.core.render import canvas from luma.oled.device import ssd1306 from PIL import ImageFont from RPi import GPIO class SSD1306InfoButton: def __init__(self, info_btn_p...
ssd1306_infobutton/__init__.py
import asyncio import os import time import re from subprocess import Popen, PIPE, check_output from luma.core.interface.serial import i2c from luma.core.render import canvas from luma.oled.device import ssd1306 from PIL import ImageFont from RPi import GPIO class SSD1306InfoButton: def __init__(self, info_btn_p...
0.389779
0.09899
from tkinter import (BOTH, FLAT, GROOVE, SUNKEN, Button, Frame, Label, Tk, Y, messagebox) import requests from numpy import asarray_chkfinite, sum from wincap import WindowCapture url = "INSERT_WEBHOOK_HERE" data = { "username": "Queue Notifier", "embeds": [ { ...
app.py
from tkinter import (BOTH, FLAT, GROOVE, SUNKEN, Button, Frame, Label, Tk, Y, messagebox) import requests from numpy import asarray_chkfinite, sum from wincap import WindowCapture url = "INSERT_WEBHOOK_HERE" data = { "username": "Queue Notifier", "embeds": [ { ...
0.323808
0.114097
from seatsio.domain import EventObjectInfo, Channel, SocialDistancingRuleset from tests.seatsioClientTest import SeatsioClientTest from tests.util.asserts import assert_that class BookObjectsTest(SeatsioClientTest): def test(self): chart_key = self.create_test_chart() event = self.client.events.c...
tests/events/bookObjectsTest.py
from seatsio.domain import EventObjectInfo, Channel, SocialDistancingRuleset from tests.seatsioClientTest import SeatsioClientTest from tests.util.asserts import assert_that class BookObjectsTest(SeatsioClientTest): def test(self): chart_key = self.create_test_chart() event = self.client.events.c...
0.734596
0.408277
import numpy as np def color_gaps(plot, model, ylim=None, label=False, color_sample_gaps=True): """ Colors the energies of the band-gaps of the model Parameters ---------- plot : matplotlib object plot to add bandgaps model : Model model to get band-data from ylim : array_like...
waveprop/plotting/plot_utils.py
import numpy as np def color_gaps(plot, model, ylim=None, label=False, color_sample_gaps=True): """ Colors the energies of the band-gaps of the model Parameters ---------- plot : matplotlib object plot to add bandgaps model : Model model to get band-data from ylim : array_like...
0.931587
0.648355
import psycopg2 import time from action.lead_actions.case_one import * from connection.connection_variables import pg_user, \ pg_password, \ pg_host, \ pg_port, \ pg_database from parameters.lead.case_1.lead_params import * """Connect to database using connection variables""" connection = psycopg2.conn...
lead_result_validation/case_one_validation/lead_validation.py
import psycopg2 import time from action.lead_actions.case_one import * from connection.connection_variables import pg_user, \ pg_password, \ pg_host, \ pg_port, \ pg_database from parameters.lead.case_1.lead_params import * """Connect to database using connection variables""" connection = psycopg2.conn...
0.209955
0.058025
# Things to fix ''' Nothing yet :) ''' # Importing dependencies import numpy as np # Code class centroid: def __init__(self, pos): self.pos = pos self.oldpos = [] self.reset() self.labels = [] def reset(self): self.assigned = [] self.got_assigned = False def...
clustering/centroidspace.py
# Things to fix ''' Nothing yet :) ''' # Importing dependencies import numpy as np # Code class centroid: def __init__(self, pos): self.pos = pos self.oldpos = [] self.reset() self.labels = [] def reset(self): self.assigned = [] self.got_assigned = False def...
0.488771
0.358521
import numpy as np def compute_distances(X, k, n_data, centroids): distances = np.zeros((n_data, k)) for idx_centroids in range(k): dist = np.sqrt(np.sum((X - centroids[idx_centroids]) ** 2, axis=1)) distances[:, idx_centroids] = dist return distances def init_centroid(X, k, n_data): ...
chapter19/Q8.py
import numpy as np def compute_distances(X, k, n_data, centroids): distances = np.zeros((n_data, k)) for idx_centroids in range(k): dist = np.sqrt(np.sum((X - centroids[idx_centroids]) ** 2, axis=1)) distances[:, idx_centroids] = dist return distances def init_centroid(X, k, n_data): ...
0.440469
0.479686
import tweepy import re import pickle from tweepy import OAuthHandler consumer_key = '' consumer_secret = '' access_token = '' access_secret = '' auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) args = ['facebook'] api = tweepy.api(auth, timeout=...
twitter_semantic.py
import tweepy import re import pickle from tweepy import OAuthHandler consumer_key = '' consumer_secret = '' access_token = '' access_secret = '' auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_secret) args = ['facebook'] api = tweepy.api(auth, timeout=...
0.166167
0.08698
import keras import numpy as np import matplotlib.image as mpimg class DataGenerator(keras.utils.Sequence): 'Generates data for Keras' def __init__(self, list_IDs, labels, data,batch_size=128, dim=(160,320), n_channels=3, shuffle=True): 'Initialization' self.dim = dim self.batch_size =...
data_generator.py
import keras import numpy as np import matplotlib.image as mpimg class DataGenerator(keras.utils.Sequence): 'Generates data for Keras' def __init__(self, list_IDs, labels, data,batch_size=128, dim=(160,320), n_channels=3, shuffle=True): 'Initialization' self.dim = dim self.batch_size =...
0.478041
0.33066
class MethodDescriptor: def __init__(self): self.parameter_types = [] self.return_type = "" def add_parameter_type(self, t): self.parameter_types.append(t) class MethodDescriptorParser: def __init__(self): self.raw = "" self.offset = 0 self.parsed = None ...
runtime_data/heap/method_descriptor.py
class MethodDescriptor: def __init__(self): self.parameter_types = [] self.return_type = "" def add_parameter_type(self, t): self.parameter_types.append(t) class MethodDescriptorParser: def __init__(self): self.raw = "" self.offset = 0 self.parsed = None ...
0.632503
0.152127
import unittest import os from jcast.annots import ReadAnnotations class AnnotationTest(unittest.TestCase): """ Test cases involving reading genome sequence and references """ def setUp(self): """ :return: """ global test_data_loc, human_gtf_loc, rat_gtf_loc ...
tests/test_gtf.py
import unittest import os from jcast.annots import ReadAnnotations class AnnotationTest(unittest.TestCase): """ Test cases involving reading genome sequence and references """ def setUp(self): """ :return: """ global test_data_loc, human_gtf_loc, rat_gtf_loc ...
0.54577
0.512144
import json import pytest import six from mock import Mock, patch from nefertari import json_httpexceptions as jsonex from nefertari.renderers import _JSONEncoder class TestJSONHTTPExceptionsModule(object): def test_includeme(self): config = Mock() jsonex.includeme(config) config.add_vi...
tests/test_json_httpexceptions.py
import json import pytest import six from mock import Mock, patch from nefertari import json_httpexceptions as jsonex from nefertari.renderers import _JSONEncoder class TestJSONHTTPExceptionsModule(object): def test_includeme(self): config = Mock() jsonex.includeme(config) config.add_vi...
0.624294
0.287165
import yfinance as yf import datetime as dt import pandas as pd from pandas_datareader import data as pdr import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.ticker as mticker import datetime as datetime import numpy as np from mplfinance.original_flavor import candlestick_ohlc from pyla...
Portfolio_Strategies/main_indicators_one_graph.py
import yfinance as yf import datetime as dt import pandas as pd from pandas_datareader import data as pdr import matplotlib.pyplot as plt import matplotlib.dates as mdates import matplotlib.ticker as mticker import datetime as datetime import numpy as np from mplfinance.original_flavor import candlestick_ohlc from pyla...
0.202325
0.5835
import urllib.request import logging import configparser import json import time import bz2 import tarfile import io # Start our config parser, and read out config file. # This code is largely required to be as it is for configparser to work config = configparser.ConfigParser() config.sections() # congi...
Downloader/downloader-RAM-intense.py
import urllib.request import logging import configparser import json import time import bz2 import tarfile import io # Start our config parser, and read out config file. # This code is largely required to be as it is for configparser to work config = configparser.ConfigParser() config.sections() # congi...
0.226356
0.081082
from math import exp from typing import Callable __all__ = ["GorEntry", "gor_update", "gor_configure"] EPSILON: float = 0.016 RATING_TO_RANK: Callable[[float], float] = lambda rating: rating / 100 + 9 class GorEntry: rating: float handicap: float def __init__(self, rating: float = 1200.0, handicap: flo...
goratings/math/gor.py
from math import exp from typing import Callable __all__ = ["GorEntry", "gor_update", "gor_configure"] EPSILON: float = 0.016 RATING_TO_RANK: Callable[[float], float] = lambda rating: rating / 100 + 9 class GorEntry: rating: float handicap: float def __init__(self, rating: float = 1200.0, handicap: flo...
0.692954
0.595022
from __future__ import division import os, sys import libtbx.option_parser from cctbx.development import debug_utils from cctbx import sgtbx class space_group_processed_options(libtbx.option_parser.processed_options): def loop_over_space_groups(self, f, **kwds): kwds.update(self.options.__dict__) for sgi in...
cctbx/development/space_group_option_parser.py
from __future__ import division import os, sys import libtbx.option_parser from cctbx.development import debug_utils from cctbx import sgtbx class space_group_processed_options(libtbx.option_parser.processed_options): def loop_over_space_groups(self, f, **kwds): kwds.update(self.options.__dict__) for sgi in...
0.318909
0.108425
import daft from causalgraphicalmodels import CausalGraphicalModel import matplotlib.pyplot as plt class dag_class: class create_dag: def __init__(self): self.nodes = set() self.edges = set() self.coordinates= {} def __init__(self): self.nodes = {} ...
quick_dag/dags.py
import daft from causalgraphicalmodels import CausalGraphicalModel import matplotlib.pyplot as plt class dag_class: class create_dag: def __init__(self): self.nodes = set() self.edges = set() self.coordinates= {} def __init__(self): self.nodes = {} ...
0.291989
0.326137
from .config import Config from .utils import Utils from .exceptions import PhotofuniaException class Photofunia: """docstring for Photofunia""" def __init__(self): self.config = Config() self.utils = Utils() def info(self, name): name = name.replace(' ', '-') n...
main.py
from .config import Config from .utils import Utils from .exceptions import PhotofuniaException class Photofunia: """docstring for Photofunia""" def __init__(self): self.config = Config() self.utils = Utils() def info(self, name): name = name.replace(' ', '-') n...
0.492676
0.091504
import os import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from scipy.optimize import linear_sum_assignment from scipy.spatial import distance import data_generator from model import Generator, Critic from reg_losses import get_regularization_term slim = tf.contrib.slim __eval_step_list__ ...
trainer.py
import os import tensorflow as tf import numpy as np import matplotlib.pyplot as plt from scipy.optimize import linear_sum_assignment from scipy.spatial import distance import data_generator from model import Generator, Critic from reg_losses import get_regularization_term slim = tf.contrib.slim __eval_step_list__ ...
0.793266
0.278021
from math import copysign from typing import Union from sidekick.properties import alias, delegate_to, property as property_ from ..linalg import Vec2d from ..typing import VecLike from .draw_options import draw, drawb from .helpers import get_pyxel # TODO: in the future we should merge camera with DrawOptions cla...
easymunk/pyxel/camera.py
from math import copysign from typing import Union from sidekick.properties import alias, delegate_to, property as property_ from ..linalg import Vec2d from ..typing import VecLike from .draw_options import draw, drawb from .helpers import get_pyxel # TODO: in the future we should merge camera with DrawOptions cla...
0.681091
0.380241
## @file unittests/pytests/feassemble/TestFIATSimplex.py ## @brief Unit testing of FIATSimplex object. import unittest import numpy from pylith.feassemble.FIATSimplex import FIATSimplex from pylith.utils.testarray import test_scalararray # ---------------------------------------------------------------------- class...
unittests/pytests/feassemble/TestFIATSimplex.py
## @file unittests/pytests/feassemble/TestFIATSimplex.py ## @brief Unit testing of FIATSimplex object. import unittest import numpy from pylith.feassemble.FIATSimplex import FIATSimplex from pylith.utils.testarray import test_scalararray # ---------------------------------------------------------------------- class...
0.680879
0.67822
import re import string import emoji def preprocess(text): #remove urls processed_text = re.sub("http\S+", "", text, flags=re.MULTILINE) #handle hashtags and usernames processed_text = re.sub("#", "", processed_text) processed_text = re.sub("@", "", processed_text) #rem...
utils.py
import re import string import emoji def preprocess(text): #remove urls processed_text = re.sub("http\S+", "", text, flags=re.MULTILINE) #handle hashtags and usernames processed_text = re.sub("#", "", processed_text) processed_text = re.sub("@", "", processed_text) #rem...
0.266548
0.086093
import sys import xmltodict import requests class WrongCountry(Exception): pass class Meteoalert(object): def __init__(self, country, province, language='en-GB'): self.country = country.lower() self.province = province self.language = language def get_alert(self): """Re...
meteoalertapi/meteoalertapi.py
import sys import xmltodict import requests class WrongCountry(Exception): pass class Meteoalert(object): def __init__(self, country, province, language='en-GB'): self.country = country.lower() self.province = province self.language = language def get_alert(self): """Re...
0.293911
0.192501
species = { "Aae" : "Aedes aegypti", "Aga" : "Anopheles gambiae", "Ame" : "Apis mellifera", "Afp" : "Aquilegia formosa x Aquilegia pubescens", "At" : "Arabidopsis thaliana", "Bmo" : "Bombyx mori", "Bt" : "Bos taurus", "Bfl" : "Branchiostoma floridae", ...
Python/biopsy/identifiers/unigene.py
species = { "Aae" : "Aedes aegypti", "Aga" : "Anopheles gambiae", "Ame" : "Apis mellifera", "Afp" : "Aquilegia formosa x Aquilegia pubescens", "At" : "Arabidopsis thaliana", "Bmo" : "Bombyx mori", "Bt" : "Bos taurus", "Bfl" : "Branchiostoma floridae", ...
0.402157
0.451931
import pickle import unittest from pathlib import Path from unittest.mock import Mock, patch import lakshmi.cache as cache class Cached(cache.Cacheable): def __init__(self, key, value): self.key = key self.value = value def cache_key(self): return self.key @cache.cache(2) de...
tests/test_cache.py
import pickle import unittest from pathlib import Path from unittest.mock import Mock, patch import lakshmi.cache as cache class Cached(cache.Cacheable): def __init__(self, key, value): self.key = key self.value = value def cache_key(self): return self.key @cache.cache(2) de...
0.6705
0.29604
import tensorflow as tf import keras import numpy as np import os import matplotlib.pyplot as plt PATH = os.path.join(r'C:\Users\shast\.keras\datasets', 'cats_and_dogs_filtered') train_dir = os.path.join(PATH, 'train') validation_dir = os.path.join(PATH, 'validation') train_cats_dir = os.path.join(train_dir, ...
bottleneck_vgg.py
import tensorflow as tf import keras import numpy as np import os import matplotlib.pyplot as plt PATH = os.path.join(r'C:\Users\shast\.keras\datasets', 'cats_and_dogs_filtered') train_dir = os.path.join(PATH, 'train') validation_dir = os.path.join(PATH, 'validation') train_cats_dir = os.path.join(train_dir, ...
0.482917
0.219473
import re from math import inf SPELL_COST = {1: 53, 2: 73, 3: 113, 4: 173, 5: 229} class State: def __init__(self, hp, mana, boss_hp, boss_dmg, hard=False): self.hp = hp self.mana = mana self.boss_hp = boss_hp self.boss_dmg = boss_dmg self.shield = 0 self.poison = ...
day22/script1.py
import re from math import inf SPELL_COST = {1: 53, 2: 73, 3: 113, 4: 173, 5: 229} class State: def __init__(self, hp, mana, boss_hp, boss_dmg, hard=False): self.hp = hp self.mana = mana self.boss_hp = boss_hp self.boss_dmg = boss_dmg self.shield = 0 self.poison = ...
0.443359
0.305374
import math from collections import namedtuple from roboticstoolbox.mobile import PlannerBase import matplotlib.pyplot as plt import numpy as np from spatialmath import * from spatialmath import base def left_straight_left(alpha, beta, d): sa = math.sin(alpha) sb = math.sin(beta) ca = math.cos(alpha) ...
roboticstoolbox/mobile/DubinsPlanner.py
import math from collections import namedtuple from roboticstoolbox.mobile import PlannerBase import matplotlib.pyplot as plt import numpy as np from spatialmath import * from spatialmath import base def left_straight_left(alpha, beta, d): sa = math.sin(alpha) sb = math.sin(beta) ca = math.cos(alpha) ...
0.537041
0.397178
from cmath import pi, tan from fractions import Fraction def norm_or_comp(): """ Returns a boolean value based on user input. True will be returned if 'complex' is given. False will be returned if 'normalized' is given. Use to determine a normalized or complex value. """ while True: ...
impydance.py
from cmath import pi, tan from fractions import Fraction def norm_or_comp(): """ Returns a boolean value based on user input. True will be returned if 'complex' is given. False will be returned if 'normalized' is given. Use to determine a normalized or complex value. """ while True: ...
0.781414
0.440229
import logging from typing import Dict, Optional from qtoggleserver import persist from qtoggleserver.core import ports as core_ports from qtoggleserver.core.typing import GenericJSONDict, GenericJSONList, NullablePortValue, PortValue, PortValueChoices logger = logging.getLogger(__name__) _vport_args: Dict[str, Ge...
qtoggleserver/core/vports.py
import logging from typing import Dict, Optional from qtoggleserver import persist from qtoggleserver.core import ports as core_ports from qtoggleserver.core.typing import GenericJSONDict, GenericJSONList, NullablePortValue, PortValue, PortValueChoices logger = logging.getLogger(__name__) _vport_args: Dict[str, Ge...
0.859457
0.169578
import urlparse from gunicorn.util import normalize_name class HttpParserError(Exception): """ error raised when parsing fail""" class HttpParser(object): def __init__(self): self.status = "" self.headers = [] self.headers_dict = {} self.raw_version = "HTTP/1.0" ...
gunicorn/http/parser.py
import urlparse from gunicorn.util import normalize_name class HttpParserError(Exception): """ error raised when parsing fail""" class HttpParser(object): def __init__(self): self.status = "" self.headers = [] self.headers_dict = {} self.raw_version = "HTTP/1.0" ...
0.552298
0.151938
import logging import sys from itertools import combinations from os.path import join import matplotlib.pyplot as plt import pandas as pd import xarray as xr from src.parameters import FIGURE_DIR, PROCESSED_DATA_DIR, USE_LIKELIHOODS from src.visualization import (compare_jaccard_similarity_of_replays, ...
scripts/create_figures.py
import logging import sys from itertools import combinations from os.path import join import matplotlib.pyplot as plt import pandas as pd import xarray as xr from src.parameters import FIGURE_DIR, PROCESSED_DATA_DIR, USE_LIKELIHOODS from src.visualization import (compare_jaccard_similarity_of_replays, ...
0.486819
0.256273
from fastapi.testclient import TestClient from nohossat_cas_pratique.main import app client = TestClient(app) HTTP_AUTH = "Basic <KEY> PATH_TRAIN = "/train" def test_infer(): response = client.post("/", json={"msg": ["J'ai adoré ce restaurant", "J'ai détesté cet hôtel."]}) assert...
tests/test_main.py
from fastapi.testclient import TestClient from nohossat_cas_pratique.main import app client = TestClient(app) HTTP_AUTH = "Basic <KEY> PATH_TRAIN = "/train" def test_infer(): response = client.post("/", json={"msg": ["J'ai adoré ce restaurant", "J'ai détesté cet hôtel."]}) assert...
0.631026
0.399226
from django.views.generic import ListView, DetailView from django.views.generic.edit import FormView from rest_framework import generics, mixins from django.utils.decorators import method_decorator from fcuser.decoraters import admin_required from order.forms import RegisterForm as OrderRegisterForm from .forms import ...
product/views.py
from django.views.generic import ListView, DetailView from django.views.generic.edit import FormView from rest_framework import generics, mixins from django.utils.decorators import method_decorator from fcuser.decoraters import admin_required from order.forms import RegisterForm as OrderRegisterForm from .forms import ...
0.579162
0.139866
import configparser import copy import os import sys from tempfile import TemporaryDirectory import unittest from screwdrivercd.version import cli from screwdrivercd.version.version_types import versioners class TestCLI(unittest.TestCase): cwd = None orig_argv = None orig_environ =None tempdir = None ...
tests/test_cli.py
import configparser import copy import os import sys from tempfile import TemporaryDirectory import unittest from screwdrivercd.version import cli from screwdrivercd.version.version_types import versioners class TestCLI(unittest.TestCase): cwd = None orig_argv = None orig_environ =None tempdir = None ...
0.192501
0.05328
import unittest import numpy as np import pandas as pd from jurity.fairness import BinaryFairnessMetrics from jurity.utils import InputShapeError class TestBinaryFairness(unittest.TestCase): def test_stat_parity_normal_np(self): # Data y_pred = np.array([1, 1, 0, 1, 0, 0]) is_member =...
tests/test_fairness_binary.py
import unittest import numpy as np import pandas as pd from jurity.fairness import BinaryFairnessMetrics from jurity.utils import InputShapeError class TestBinaryFairness(unittest.TestCase): def test_stat_parity_normal_np(self): # Data y_pred = np.array([1, 1, 0, 1, 0, 0]) is_member =...
0.762778
0.677749
import os import numpy as np import matplotlib.pyplot as plt from keras.datasets import mnist from keras.layers import Input, Dense, Reshape, Flatten, BatchNormalization from keras.layers.advanced_activations import LeakyReLU from keras.models import Sequential, Model from keras.optimizers import Adam if not os.path...
source.py
import os import numpy as np import matplotlib.pyplot as plt from keras.datasets import mnist from keras.layers import Input, Dense, Reshape, Flatten, BatchNormalization from keras.layers.advanced_activations import LeakyReLU from keras.models import Sequential, Model from keras.optimizers import Adam if not os.path...
0.780788
0.45647
import json import logging import os import re import sys import traceback from argparse import ArgumentParser, Namespace from collections import defaultdict from math import ceil from pathlib import Path from typing import Dict, List, Optional from analysis.src.python.evaluation.common.args_util import EvaluationRunT...
analysis/src/python/evaluation/qodana/dataset_labeling.py
import json import logging import os import re import sys import traceback from argparse import ArgumentParser, Namespace from collections import defaultdict from math import ceil from pathlib import Path from typing import Dict, List, Optional from analysis.src.python.evaluation.common.args_util import EvaluationRunT...
0.498291
0.157234
import torch from net import * import numpy as np from collections import deque from optim import Ranger from optim_v2 import Optim import random import time def soft_update(target, source, tau=0.001): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(target_...
agent.py
import torch from net import * import numpy as np from collections import deque from optim import Ranger from optim_v2 import Optim import random import time def soft_update(target, source, tau=0.001): for target_param, param in zip(target.parameters(), source.parameters()): target_param.data.copy_(target_...
0.698432
0.244059
from pathlib import Path from pytorch_lightning.callbacks import Callback import torch import numpy as np import matplotlib.pyplot as plt from diameter_learning.transforms import ControlPointPostprocess class VisualizerCallback(Callback): def __init__( self, result_path: Path, get_pred: ca...
diameter_learning/handlers/visualizers.py
from pathlib import Path from pytorch_lightning.callbacks import Callback import torch import numpy as np import matplotlib.pyplot as plt from diameter_learning.transforms import ControlPointPostprocess class VisualizerCallback(Callback): def __init__( self, result_path: Path, get_pred: ca...
0.900788
0.470007
# ------------------------------------------------------------------------------ from filegetter import PDBFile from urllib.error import URLError from re import search from itertools import groupby from operator import itemgetter from utils import get_hexagon_midpoints from utils import LonePairs from utils i...
overall-counts-YABBI-2019/utils/ma.py
# ------------------------------------------------------------------------------ from filegetter import PDBFile from urllib.error import URLError from re import search from itertools import groupby from operator import itemgetter from utils import get_hexagon_midpoints from utils import LonePairs from utils i...
0.414899
0.236637
import codecs import random from collections import defaultdict from menu import Menu class Quizz(Menu): def __init__(self, game): Menu.__init__(self, game) self.game = game self.points = {} self.questions = None self.read_points() self.state=0 self.fail = Fal...
quizz.py
import codecs import random from collections import defaultdict from menu import Menu class Quizz(Menu): def __init__(self, game): Menu.__init__(self, game) self.game = game self.points = {} self.questions = None self.read_points() self.state=0 self.fail = Fal...
0.179602
0.101367
__all__ = ( # keywords "ANY_KEYWORD", "ALGORITHM", "AND", "ANNOTATION", "BLOCK", "BREAK", "CLASS", "CONNECT", "CONNECTOR", "CONSTANT", "CONSTRAINEDBY", "DER", "DISCRETE", "EACH", "ELSE", "ELSEIF", "ELSEWHEN", "ENCAPSULATED", "END", "ENU...
modelica_language/parsers/syntax/__init__.py
__all__ = ( # keywords "ANY_KEYWORD", "ALGORITHM", "AND", "ANNOTATION", "BLOCK", "BREAK", "CLASS", "CONNECT", "CONNECTOR", "CONSTANT", "CONSTRAINEDBY", "DER", "DISCRETE", "EACH", "ELSE", "ELSEIF", "ELSEWHEN", "ENCAPSULATED", "END", "ENU...
0.447219
0.209793
from copy import deepcopy from unittest import TestCase from telegram.types.message import Message, MessageForwardInfo, MessageSenderType from telegram.types.message_content import MessageText message_base = { '@type': 'message', 'id': 166121701376, 'sender': {'@type': 'messageSenderUser', 'user_id': 1394...
tests/test_types/test_message.py
from copy import deepcopy from unittest import TestCase from telegram.types.message import Message, MessageForwardInfo, MessageSenderType from telegram.types.message_content import MessageText message_base = { '@type': 'message', 'id': 166121701376, 'sender': {'@type': 'messageSenderUser', 'user_id': 1394...
0.542863
0.186929
from __future__ import annotations from typing import Protocol, TYPE_CHECKING, TypeVar if TYPE_CHECKING: from volga.format import Format RT = TypeVar("RT") class supportsDeserialization(Protocol): """This protocol defines methods to be implemented by data fields or data formats so they can be deserial...
volga/protocols.py
from __future__ import annotations from typing import Protocol, TYPE_CHECKING, TypeVar if TYPE_CHECKING: from volga.format import Format RT = TypeVar("RT") class supportsDeserialization(Protocol): """This protocol defines methods to be implemented by data fields or data formats so they can be deserial...
0.915205
0.534855
from .utils import * class DoubletInfo: """ Holds information about doublet for a given spacepoint when it is considered as the middle spacepoint. Output of the doubletCounting step write there """ def __init__(self, nbSpacepoints): # number of inner doublet (other spacepoint has a smalle...
src/hepqpr/qallse/seeding/storage.py
from .utils import * class DoubletInfo: """ Holds information about doublet for a given spacepoint when it is considered as the middle spacepoint. Output of the doubletCounting step write there """ def __init__(self, nbSpacepoints): # number of inner doublet (other spacepoint has a smalle...
0.790934
0.518912
# Copyright (c) 2021, 2022 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ from typing import Any, Optional, Union import oci.data_science.models as data_science_models from ads.common.oci_datascience import OCIDataScienceMixin fro...
ads/model/deployment/model_deployment_properties.py
# Copyright (c) 2021, 2022 Oracle and/or its affiliates. # Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/ from typing import Any, Optional, Union import oci.data_science.models as data_science_models from ads.common.oci_datascience import OCIDataScienceMixin fro...
0.904469
0.370225
import copy as cp from skmultiflow.classification.lazy.knn_adwin import KNNAdwin from skmultiflow.core.base import StreamModel from skmultiflow.drift_detection.adwin import ADWIN from skmultiflow.core.utils.utils import * class OzaBaggingAdwin(StreamModel): """ OzaBagging Classifier with ADWIN change detector ...
src/skmultiflow/classification/meta/oza_bagging_adwin.py
import copy as cp from skmultiflow.classification.lazy.knn_adwin import KNNAdwin from skmultiflow.core.base import StreamModel from skmultiflow.drift_detection.adwin import ADWIN from skmultiflow.core.utils.utils import * class OzaBaggingAdwin(StreamModel): """ OzaBagging Classifier with ADWIN change detector ...
0.725746
0.57075
from . import db from contextlib import contextmanager ''' Column | Type | Collation | Nullable | Default ----------------------+-------------------------+-----------+----------+--------- name | character varying(255) | | | instance_id | ...
voice_api/models/agents.py
from . import db from contextlib import contextmanager ''' Column | Type | Collation | Nullable | Default ----------------------+-------------------------+-----------+----------+--------- name | character varying(255) | | | instance_id | ...
0.437343
0.268592
import re def read_file(file_ish, encoding='utf8', errors='replace'): """ Read and return string contents in `file_ish` Parameters ---------- file_ish : str or file-like String giving filename or file-like object implementing ``read`` method. encoding : str Text encoding o...
rnbgrader/nbparser.py
import re def read_file(file_ish, encoding='utf8', errors='replace'): """ Read and return string contents in `file_ish` Parameters ---------- file_ish : str or file-like String giving filename or file-like object implementing ``read`` method. encoding : str Text encoding o...
0.735547
0.439988
import command_system import db import re def next(vk_id, body): if body in ('1', '2'): return None, None if not re.match("^[0-9]+$", body.strip()): return None, None studnum = 0 try: studnum = int(body) if len(body) not in range(7,9): return 'В номере с...
commands/st2_input.py
import command_system import db import re def next(vk_id, body): if body in ('1', '2'): return None, None if not re.match("^[0-9]+$", body.strip()): return None, None studnum = 0 try: studnum = int(body) if len(body) not in range(7,9): return 'В номере с...
0.066372
0.18188
import numpy as np import random import math from scipy import signal class RoadGenerator(): def __init__(self): self.L = 300 # Length of Road Profile (m) self.B = 0.1 # Sampling Interval (m) self.dn = 1/self.L # Frequency Band (1/m) self.n0 = 0.1 # Spatial Freq...
road_generator.py
import numpy as np import random import math from scipy import signal class RoadGenerator(): def __init__(self): self.L = 300 # Length of Road Profile (m) self.B = 0.1 # Sampling Interval (m) self.dn = 1/self.L # Frequency Band (1/m) self.n0 = 0.1 # Spatial Freq...
0.624523
0.376279
import logging import tempfile import sys import shutil import os import pathlib import fire from pywhlobf.prep import extract_tags, unzip_wheel, locate_py_files from pywhlobf.build import build_py_files_inplace from pywhlobf.post import remove_source_files, generate_whl_name, repack_whl logging.basicConfig(format='...
pywhlobf/cli.py
import logging import tempfile import sys import shutil import os import pathlib import fire from pywhlobf.prep import extract_tags, unzip_wheel, locate_py_files from pywhlobf.build import build_py_files_inplace from pywhlobf.post import remove_source_files, generate_whl_name, repack_whl logging.basicConfig(format='...
0.359701
0.1526
from AccessControl.unauthorized import Unauthorized from plone import api from plone.app.testing import setRoles from plone.app.testing import SITE_OWNER_NAME from plone.app.testing import SITE_OWNER_PASSWORD from plone.app.testing import TEST_USER_ID from plone.dexterity.interfaces import IDexterityFTI from plone.test...
docs/testing/_snippets/test_ct_testing_item.py
from AccessControl.unauthorized import Unauthorized from plone import api from plone.app.testing import setRoles from plone.app.testing import SITE_OWNER_NAME from plone.app.testing import SITE_OWNER_PASSWORD from plone.app.testing import TEST_USER_ID from plone.dexterity.interfaces import IDexterityFTI from plone.test...
0.62223
0.365259
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
benchmarks/SimResults/_bigLittle_hrrs_spec_tugberk_heteroFair/cmp_gcc/power.py
power = {'BUSES': {'Area': 1.33155, 'Bus/Area': 1.33155, 'Bus/Gate Leakage': 0.00662954, 'Bus/Peak Dynamic': 0.0, 'Bus/Runtime Dynamic': 0.0, 'Bus/Subthreshold Leakage': 0.0691322, 'Bus/Subthreshold Leakage with power gating': 0.0259246, 'Gate...
0.592784
0.316026
import error class Op(): def __init__(self, op, left, right): self.op = op self.left = left self.right = right class Func(): def __init__(self, method, parameters, loc=None, builtin=False, returns=False): self.loc = loc self.builtin = builtin self.method = metho...
tree.py
import error class Op(): def __init__(self, op, left, right): self.op = op self.left = left self.right = right class Func(): def __init__(self, method, parameters, loc=None, builtin=False, returns=False): self.loc = loc self.builtin = builtin self.method = metho...
0.509276
0.144209
def _get_system_feature(feature): if feature == "fans": return ( "Fan Location Present Speed of max Redundant Partner Hot-pluggable\n" "--- -------- ------- ----- ------ --------- ------- -------------\n" "#1 SYSTEM Yes NORMAL 13% ...
tests/mocks.py
def _get_system_feature(feature): if feature == "fans": return ( "Fan Location Present Speed of max Redundant Partner Hot-pluggable\n" "--- -------- ------- ----- ------ --------- ------- -------------\n" "#1 SYSTEM Yes NORMAL 13% ...
0.588653
0.113481
import re import upkica class Profiles(upkica.core.Common): def __init__(self, logger, storage): try: super(Profiles, self).__init__(logger) except Exception as err: raise Exception(err) self._storage = storage try: # Detect all profi...
upkica/utils/profiles.py
import re import upkica class Profiles(upkica.core.Common): def __init__(self, logger, storage): try: super(Profiles, self).__init__(logger) except Exception as err: raise Exception(err) self._storage = storage try: # Detect all profi...
0.430387
0.116387
import astropy.units as u from astropy.io import fits from astropy.table import Table import numpy as np from astropy.coordinates.angle_utilities import angular_separation from irf.collection_area import collection_area from irf.energy_dispersion import energy_migration from irf.gadf.hdus import add_meta_information_to...
irf/gadf/response.py
import astropy.units as u from astropy.io import fits from astropy.table import Table import numpy as np from astropy.coordinates.angle_utilities import angular_separation from irf.collection_area import collection_area from irf.energy_dispersion import energy_migration from irf.gadf.hdus import add_meta_information_to...
0.930292
0.570032
import numpy as np from pprint import pprint from qlazy import QState class MyQState(QState): def swap(self,q0,q1): self.cx(q0,q1).cx(q1,q0).cx(q0,q1) return self def qft2(self,q1,q0): self.h(q1).cp(q0,q1,phase=0.5) self.h(q0) self.swap(q0,q1) return self...
example/py/QFT/qft.py
import numpy as np from pprint import pprint from qlazy import QState class MyQState(QState): def swap(self,q0,q1): self.cx(q0,q1).cx(q1,q0).cx(q0,q1) return self def qft2(self,q1,q0): self.h(q1).cp(q0,q1,phase=0.5) self.h(q0) self.swap(q0,q1) return self...
0.298798
0.400867
import threading import websocket import contextlib import ujson as json from time import time as timestamp from .lib.util import objects class SocketHandler: def __init__(self, client, socket_trace = False): websocket.enableTrace(True) self.socket_url = "wss://ws.projz.com/v1/chat/ws" sel...
projz/socket.py
import threading import websocket import contextlib import ujson as json from time import time as timestamp from .lib.util import objects class SocketHandler: def __init__(self, client, socket_trace = False): websocket.enableTrace(True) self.socket_url = "wss://ws.projz.com/v1/chat/ws" sel...
0.191781
0.117876
# %% Set up import warnings import numpy as np from scipy import stats import matplotlib.pyplot as plt from ForcePickle import pickle_protocol import pandas as pd # Set styles and themes # matplotlib.rcParams.update(matplotlib.rcParamsDefault) githubContent = 'https://raw.githubusercontent.com/sckilcoyne/FIRE/' gith...
market analysis.py
# %% Set up import warnings import numpy as np from scipy import stats import matplotlib.pyplot as plt from ForcePickle import pickle_protocol import pandas as pd # Set styles and themes # matplotlib.rcParams.update(matplotlib.rcParamsDefault) githubContent = 'https://raw.githubusercontent.com/sckilcoyne/FIRE/' gith...
0.53777
0.379378
import os import PIL from rect import Rect _imageFolder = '' def setImageFolder(path): ''' set a path to image folder simplifies the path definition for SpriteSheets and SheetImages ''' global _imageFolder _imageFolder = path class CssProp: def __init__(self, selector, pos=(0,0)): ...
spritesticker/sheetimage.py
import os import PIL from rect import Rect _imageFolder = '' def setImageFolder(path): ''' set a path to image folder simplifies the path definition for SpriteSheets and SheetImages ''' global _imageFolder _imageFolder = path class CssProp: def __init__(self, selector, pos=(0,0)): ...
0.750918
0.342393
import pytest import sys from celery_singleton.config import Config from celery_singleton.backends.redis import RedisBackend class TestBackendUrl: @pytest.mark.celery(result_backend="redis://test_backend_url") def test__defaults_to_celery_backend_url(self, celery_app): config = Config(celery_app) ...
tests/test_config.py
import pytest import sys from celery_singleton.config import Config from celery_singleton.backends.redis import RedisBackend class TestBackendUrl: @pytest.mark.celery(result_backend="redis://test_backend_url") def test__defaults_to_celery_backend_url(self, celery_app): config = Config(celery_app) ...
0.370112
0.313919
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class...
caffe2/python/operator_test/reduce_ops_test.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np class...
0.781581
0.444927
from django.db.models import Min from django.views.generic import ( ListView, DetailView, ) from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from webapp.models import Menu from .models import ( SwimTest, Record, ) from .forms import ( SwimTestSearchForm, ) ...
tvdordrecht/swimtest/views.py
from django.db.models import Min from django.views.generic import ( ListView, DetailView, ) from django.contrib.auth.models import User from django.shortcuts import get_object_or_404 from webapp.models import Menu from .models import ( SwimTest, Record, ) from .forms import ( SwimTestSearchForm, ) ...
0.459804
0.151059
from sqlalchemy import text import json from mock_alchemy.mocking import UnifiedAlchemyMagicMock from quarry.web.models.query import Query from quarry.web.models.queryrun import QueryRun from quarry.web.models.queryrevision import QueryRevision def test_health(mocker, client): minutes = 5 session = UnifiedA...
tests/test_health.py
from sqlalchemy import text import json from mock_alchemy.mocking import UnifiedAlchemyMagicMock from quarry.web.models.query import Query from quarry.web.models.queryrun import QueryRun from quarry.web.models.queryrevision import QueryRevision def test_health(mocker, client): minutes = 5 session = UnifiedA...
0.466603
0.14256
from sqlalchemy import Integer, distinct, func from sqlalchemy.sql.expression import cast from analytics.models import ( AttributionRefererReport, AttributionReferrerEvent, DetailPageEvent, DetailPageEvents, Image, ResultClickedEvent, SearchEvent, SearchRatingEvent, SourceUsageRepor...
analytics/report_controller.py
from sqlalchemy import Integer, distinct, func from sqlalchemy.sql.expression import cast from analytics.models import ( AttributionRefererReport, AttributionReferrerEvent, DetailPageEvent, DetailPageEvents, Image, ResultClickedEvent, SearchEvent, SearchRatingEvent, SourceUsageRepor...
0.445047
0.138637
import numpy as np import matplotlib.pyplot as plt import math from matplotlib import cm from mpl_toolkits.mplot3d.axes3d import Axes3D def get_cost_function(h_theta_x, logistic=False): def cost_func(thetas, training_set): result = 0 for training_sample in training_set: nonlocal logisti...
Classification/PSET14-02Emperical.py
import numpy as np import matplotlib.pyplot as plt import math from matplotlib import cm from mpl_toolkits.mplot3d.axes3d import Axes3D def get_cost_function(h_theta_x, logistic=False): def cost_func(thetas, training_set): result = 0 for training_sample in training_set: nonlocal logisti...
0.458106
0.734941
from collections import namedtuple from itertools import product import cvxpy as cp import numpy as np from inferlo.forney.nfg_model import NormalFactorGraphModel map_lp_result = namedtuple('map_lp_result', ['upper_bound', 'lower_bound', ...
inferlo/forney/optimization/nfg_map_lp.py
from collections import namedtuple from itertools import product import cvxpy as cp import numpy as np from inferlo.forney.nfg_model import NormalFactorGraphModel map_lp_result = namedtuple('map_lp_result', ['upper_bound', 'lower_bound', ...
0.829008
0.614134
# IMPORTS import os import tempfile from PyPDF2 import PdfFileReader from tqdm import tqdm from pdf2image import convert_from_path # LISTING ALL FILES IN THE SOURCE DIRECTORY file_list = os.listdir("workspace/source/batch") file_count = 0 # PROVIDING THE ABSOLUTE PATH FOR POPPLER abs_poppler_path = os.path.abspath...
batch_file.py
# IMPORTS import os import tempfile from PyPDF2 import PdfFileReader from tqdm import tqdm from pdf2image import convert_from_path # LISTING ALL FILES IN THE SOURCE DIRECTORY file_list = os.listdir("workspace/source/batch") file_count = 0 # PROVIDING THE ABSOLUTE PATH FOR POPPLER abs_poppler_path = os.path.abspath...
0.127653
0.066843
import re from jinja2 import nodes from jinja2.ext import Extension from ckanext.nhm.lib.taxonomy import find_author_split class TaxonomyFormatExtension(Extension): '''A custom Jinja2 tag for formatting scientific names in HTML.''' tags = {'taxonomy'} # keyed on the format format_to_fields = {} ...
ckanext/nhm/lib/jinja_extensions.py
import re from jinja2 import nodes from jinja2.ext import Extension from ckanext.nhm.lib.taxonomy import find_author_split class TaxonomyFormatExtension(Extension): '''A custom Jinja2 tag for formatting scientific names in HTML.''' tags = {'taxonomy'} # keyed on the format format_to_fields = {} ...
0.690246
0.401453
from ..libgnss import utils, satpos from ..libgnss.constants import * import numpy as np def calculate_nav_soln(receiver, prn_list=None, mc=None, rxTime0=None, rxPos0=None, pOut=False): if prn_list is None: prn_list = sorted(receiver.channels.keys()) if mc is None: mc = receiver._mcount ...
pygnss/pythonreceiver/scalar/naveng.py
from ..libgnss import utils, satpos from ..libgnss.constants import * import numpy as np def calculate_nav_soln(receiver, prn_list=None, mc=None, rxTime0=None, rxPos0=None, pOut=False): if prn_list is None: prn_list = sorted(receiver.channels.keys()) if mc is None: mc = receiver._mcount ...
0.666931
0.312252
import time from mogan.common import exception from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib import exceptions as lib_exc import tempest.test from mogan.tests.tempest.service import client CONF = config.CONF class BaseBaremetalComputeTest(tempest.test.BaseTestCase): ...
mogan/tests/tempest/api/base.py
import time from mogan.common import exception from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib import exceptions as lib_exc import tempest.test from mogan.tests.tempest.service import client CONF = config.CONF class BaseBaremetalComputeTest(tempest.test.BaseTestCase): ...
0.524395
0.188455
import sys import unittest from verboselib import drop_default_language from verboselib import drop_language from verboselib import set_language from verboselib import Translations from .constants import LOCALE_DOMAIN from .constants import LOCALE_DIR_PATH class TranslationsTestCase(unittest.TestCase): def setUp...
tests/test_translations.py
import sys import unittest from verboselib import drop_default_language from verboselib import drop_language from verboselib import set_language from verboselib import Translations from .constants import LOCALE_DOMAIN from .constants import LOCALE_DIR_PATH class TranslationsTestCase(unittest.TestCase): def setUp...
0.393269
0.168686
import datetime import numpy as np import pandas as pd from pysolar import solar import terrain.config as c class TimeSeries(): ''' This class initializes a dataframe. It also provides static methods for _ and _. ''' def __init__(self, date): self.date = date self.df = self._initial...
terrain/time.py
import datetime import numpy as np import pandas as pd from pysolar import solar import terrain.config as c class TimeSeries(): ''' This class initializes a dataframe. It also provides static methods for _ and _. ''' def __init__(self, date): self.date = date self.df = self._initial...
0.713132
0.338514
from makani.avionics.firmware.monitors import analog_types from makani.avionics.firmware.serial import cs_serial_params as rev analog_default = { 'name': '', 'channel': -1, 'type': analog_types.kAnalogTypeVoltage, 'input_divider': 1.0, 'input_offset': 0.0, 'nominal': 0.0, 'min': 0.0, 'm...
avionics/firmware/monitors/cs_analog.py
from makani.avionics.firmware.monitors import analog_types from makani.avionics.firmware.serial import cs_serial_params as rev analog_default = { 'name': '', 'channel': -1, 'type': analog_types.kAnalogTypeVoltage, 'input_divider': 1.0, 'input_offset': 0.0, 'nominal': 0.0, 'min': 0.0, 'm...
0.429429
0.14624
import logging import os import pandas as pd import pytest import time import uuid from modep_client.client import Client from modep_client.datasets import Datasets from modep_client.automl import Frameworks, FrameworkFlights logger = logging.getLogger(__name__) @pytest.fixture def client(): client = Client(os....
tests/test_modep_client.py
import logging import os import pandas as pd import pytest import time import uuid from modep_client.client import Client from modep_client.datasets import Datasets from modep_client.automl import Frameworks, FrameworkFlights logger = logging.getLogger(__name__) @pytest.fixture def client(): client = Client(os....
0.482185
0.428443
import numpy as np from math import floor, ceil, sqrt from numba import jitclass, float64, boolean, int64, prange from typing import List spec = [ ('heads', int64[:]), ('nexts', int64[:]), ('shifts', int64[:]), ('xmin', float64), ('xmax', float64), ('ymin', float64), ('ymax'...
src/Tools/NNLinkedList.py
import numpy as np from math import floor, ceil, sqrt from numba import jitclass, float64, boolean, int64, prange from typing import List spec = [ ('heads', int64[:]), ('nexts', int64[:]), ('shifts', int64[:]), ('xmin', float64), ('xmax', float64), ('ymin', float64), ('ymax'...
0.861232
0.443299
from __future__ import with_statement __copyright__ = "Copyright (c) 2009 <NAME>" __version__ = "$Id$" import threading as _threading import tws.EClientErrors as _EClientErrors class HookTicks(object): '''Installs hook to handle EWrapper.tick*() events. To install construct an instance passing the wr...
tws/helper/_hook_ticks.py
from __future__ import with_statement __copyright__ = "Copyright (c) 2009 <NAME>" __version__ = "$Id$" import threading as _threading import tws.EClientErrors as _EClientErrors class HookTicks(object): '''Installs hook to handle EWrapper.tick*() events. To install construct an instance passing the wr...
0.656328
0.365825