code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
import os from django import forms from django.test import TestCase from django.core.files.uploadedfile import SimpleUploadedFile from cassava.fields import CsvFormsetField class ShoppingListItemForm(forms.Form): item_code = forms.CharField(max_length=20) description = forms.CharField(max_length=255) qu...
cassava/tests/test_forms.py
import os from django import forms from django.test import TestCase from django.core.files.uploadedfile import SimpleUploadedFile from cassava.fields import CsvFormsetField class ShoppingListItemForm(forms.Form): item_code = forms.CharField(max_length=20) description = forms.CharField(max_length=255) qu...
0.343892
0.161254
import argparse from multiprocessing import Pool import requests from bs4 import BeautifulSoup import urllib.parse as urlparse import os, sys, re import socket import validators import time, random def load_file(file): ''' read file line by line and output a list''' if os.path.isfile(file): with open(file) a...
scrabe.py
import argparse from multiprocessing import Pool import requests from bs4 import BeautifulSoup import urllib.parse as urlparse import os, sys, re import socket import validators import time, random def load_file(file): ''' read file line by line and output a list''' if os.path.isfile(file): with open(file) a...
0.140602
0.075517
from datetime import datetime, timedelta import dateutil.parser import json from json import JSONDecoder import re from airflow import DAG from airflow.operators.dummy_operator import DummyOperator from airflow.operators.bash_operator import BashOperator from airflow.operators.sensors import ExternalTaskSensor def da...
dags/utils/functions.py
from datetime import datetime, timedelta import dateutil.parser import json from json import JSONDecoder import re from airflow import DAG from airflow.operators.dummy_operator import DummyOperator from airflow.operators.bash_operator import BashOperator from airflow.operators.sensors import ExternalTaskSensor def da...
0.52829
0.186095
import enum from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import QTextDocument, QTextDocumentWriter from PyQt5.QtSql import QSqlDatabase, QSqlQuery from .recordmodel import RecordModel class Record(): def __init__(self, recordId, fileName, isSaved): self.recordId = recordId ...
RecordDatabasePython/recorddatabase/recordmanager.py
import enum from PyQt5.QtCore import * from PyQt5.QtWidgets import * from PyQt5.QtGui import QTextDocument, QTextDocumentWriter from PyQt5.QtSql import QSqlDatabase, QSqlQuery from .recordmodel import RecordModel class Record(): def __init__(self, recordId, fileName, isSaved): self.recordId = recordId ...
0.290176
0.075585
import torch.nn as nn from torch.distributions import Categorical from ActorCritic import ActorCritic import torch device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class PPO: def __init__(self, state_dim, action_dim, n_agents, lr, betas, gamma, K_epochs, eps_clip): self.lr = lr ...
PPO.py
import torch.nn as nn from torch.distributions import Categorical from ActorCritic import ActorCritic import torch device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu") class PPO: def __init__(self, state_dim, action_dim, n_agents, lr, betas, gamma, K_epochs, eps_clip): self.lr = lr ...
0.905475
0.509825
import logging import clipl.utility.logger as logger log = logging.getLogger(__name__) import hashlib import ROOT from math import sqrt, pow import clipl.analysisbase as analysisbase import clipl.utility.roottools as roottools import clipl.analysis_modules.scaleerrors as scaleerrors class Difference(analysisbase...
clipl/analysis_modules/difference.py
import logging import clipl.utility.logger as logger log = logging.getLogger(__name__) import hashlib import ROOT from math import sqrt, pow import clipl.analysisbase as analysisbase import clipl.utility.roottools as roottools import clipl.analysis_modules.scaleerrors as scaleerrors class Difference(analysisbase...
0.516839
0.301144
import sys import os sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import bson_dataframe import numpy import pyarrow import unittest class TestArrayGenerator(bson_dataframe.TypeVisitor): def __init__(self, n, typ, nullable): self.nullable = nullable ...
python/tests/test.py
import sys import os sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) import bson_dataframe import numpy import pyarrow import unittest class TestArrayGenerator(bson_dataframe.TypeVisitor): def __init__(self, n, typ, nullable): self.nullable = nullable ...
0.265309
0.225353
import sqlite3 import threading conn = sqlite3.connect('bot.db', check_same_thread=False, isolation_level=None) c = conn.cursor() lock = threading.Lock() def acquireLock(func): def wrapper(*args, **kwargs): try: lock.acquire(True) return func(*args, **kwargs) finally: ...
src/db.py
import sqlite3 import threading conn = sqlite3.connect('bot.db', check_same_thread=False, isolation_level=None) c = conn.cursor() lock = threading.Lock() def acquireLock(func): def wrapper(*args, **kwargs): try: lock.acquire(True) return func(*args, **kwargs) finally: ...
0.305076
0.040999
import os import xarray as xr from termcolor import cprint from trace_for_guess.skip import skip def drop_superfluous_trace_vars(data): """Drop all unneeded data variables from a TraCE-21ka xarray dataset.""" return data.drop(["P0", "co2vmr", "gw", "hyai", "date", "date_written", "dat...
trace_for_guess/aggregate_modern_trace.py
import os import xarray as xr from termcolor import cprint from trace_for_guess.skip import skip def drop_superfluous_trace_vars(data): """Drop all unneeded data variables from a TraCE-21ka xarray dataset.""" return data.drop(["P0", "co2vmr", "gw", "hyai", "date", "date_written", "dat...
0.520496
0.422147
import pytest import warnings import numpy as np import scipy.signal as signal from tsfuse.data.synthetic import series, brownian from tsfuse.transformers.frequency import * from tsfuse.transformers.statistics import * @pytest.fixture def x(): return brownian() def test_fft_real(x): result = FFT(attr='real...
tests/transformers/test_frequency.py
import pytest import warnings import numpy as np import scipy.signal as signal from tsfuse.data.synthetic import series, brownian from tsfuse.transformers.frequency import * from tsfuse.transformers.statistics import * @pytest.fixture def x(): return brownian() def test_fft_real(x): result = FFT(attr='real...
0.779825
0.862468
import numpy as np from model.factor import RandomVar from learning.parameter import UniformDirichlet from inference.exact import VariableElimination class NaiveBayes: """Multinomial Naive Bayes implementation. This implementation is inefficient. It serves mainly as a proof of concept that Naive Bayes...
learning/classification.py
import numpy as np from model.factor import RandomVar from learning.parameter import UniformDirichlet from inference.exact import VariableElimination class NaiveBayes: """Multinomial Naive Bayes implementation. This implementation is inefficient. It serves mainly as a proof of concept that Naive Bayes...
0.90703
0.700267
# Python Import Modules: from __future__ import print_function # Instructions: # Part I # Given the following list: # students = [ # {'first_name': 'Michael', 'last_name' : 'Jordan'}, # {'first_name' : 'John', 'last_name' : 'Rosales'}, # {'first_name' : 'Mark', 'last_name' : 'Guillen'}...
python_names.py
# Python Import Modules: from __future__ import print_function # Instructions: # Part I # Given the following list: # students = [ # {'first_name': 'Michael', 'last_name' : 'Jordan'}, # {'first_name' : 'John', 'last_name' : 'Rosales'}, # {'first_name' : 'Mark', 'last_name' : 'Guillen'}...
0.46223
0.275577
from typing import Any, Dict, Iterable from inspect import isclass import abc from ._argument_spec import ArgumentSpec def _needs_spec(bound_object: Any) -> bool: return isclass(bound_object) class BindingSpec(metaclass=abc.ABCMeta): @abc.abstractmethod def has_instance(self) -> bool: """ ...
zanna/_binding_spec.py
from typing import Any, Dict, Iterable from inspect import isclass import abc from ._argument_spec import ArgumentSpec def _needs_spec(bound_object: Any) -> bool: return isclass(bound_object) class BindingSpec(metaclass=abc.ABCMeta): @abc.abstractmethod def has_instance(self) -> bool: """ ...
0.888057
0.16872
import pytest import json from common.testresult import TestResults, TestResult import pickle import base64 def test__testresults_append__type_not_testresult__throws_error(): # Arrange test_results = TestResults() # Act/Assert with pytest.raises(TypeError): test_results.append("Tes...
tests/nutter/test_testresult.py
import pytest import json from common.testresult import TestResults, TestResult import pickle import base64 def test__testresults_append__type_not_testresult__throws_error(): # Arrange test_results = TestResults() # Act/Assert with pytest.raises(TypeError): test_results.append("Tes...
0.317532
0.424889
from django.core.urlresolvers import reverse from django.shortcuts import redirect, render_to_response from django.template.context import RequestContext from guardian.decorators import permission_required_or_403 from userena.decorators import secure_required from accounts.forms import UserAddForm from django.contrib.a...
accounts/views.py
from django.core.urlresolvers import reverse from django.shortcuts import redirect, render_to_response from django.template.context import RequestContext from guardian.decorators import permission_required_or_403 from userena.decorators import secure_required from accounts.forms import UserAddForm from django.contrib.a...
0.453746
0.097433
import pandas as pd import numpy as np def unique_allele_test(row): if row['total_total_alt_allele_counts'] > 0: top_well = sorted(wells, key=lambda w: row[w + '_total_alt_allele_counts'])[-1] if row[top_well + '_total_alt_allele_counts'] / row['total_total_alt_allele_counts'] > 0.9: ...
WGS/.ipynb_checkpoints/process_final_files-checkpoint.py
import pandas as pd import numpy as np def unique_allele_test(row): if row['total_total_alt_allele_counts'] > 0: top_well = sorted(wells, key=lambda w: row[w + '_total_alt_allele_counts'])[-1] if row[top_well + '_total_alt_allele_counts'] / row['total_total_alt_allele_counts'] > 0.9: ...
0.19046
0.122891
import matplotlib matplotlib.use('agg') import cartopy.crs as ccrs import matplotlib.pyplot as plt import seaborn as sns from glob import glob import json import pandas as pd import numpy as np import json from pathlib import Path import pkg_resources def main(): for c in range(2): files = glob(f'./*...
scripts/plots/wasserstein_histogram.py
import matplotlib matplotlib.use('agg') import cartopy.crs as ccrs import matplotlib.pyplot as plt import seaborn as sns from glob import glob import json import pandas as pd import numpy as np import json from pathlib import Path import pkg_resources def main(): for c in range(2): files = glob(f'./*...
0.319758
0.269203
from openmdao.core.vec_wrapper import SrcVecWrapper, TgtVecWrapper from openmdao.core.data_transfer import DataTransfer from openmdao.core.mpi_wrap import FakeComm class BasicImpl(object): """Basic vector and data transfer implementation factory.""" idx_arr_type = int @staticmethod def world_comm()...
openmdao/core/basic_impl.py
from openmdao.core.vec_wrapper import SrcVecWrapper, TgtVecWrapper from openmdao.core.data_transfer import DataTransfer from openmdao.core.mpi_wrap import FakeComm class BasicImpl(object): """Basic vector and data transfer implementation factory.""" idx_arr_type = int @staticmethod def world_comm()...
0.867626
0.399724
import subprocess import warnings from freemoovr.proxy.base_zmq import MultiServerBaseZMQ class _OSGFileParsingMixin(object): @staticmethod def get_animations(path): return _OSGFileParsingMixin._parse_osg_file(path)[1] @staticmethod def get_nodes(path): return _OSGFileParsingMixin._...
src/freemoovr/proxy/stimulus_osg.py
import subprocess import warnings from freemoovr.proxy.base_zmq import MultiServerBaseZMQ class _OSGFileParsingMixin(object): @staticmethod def get_animations(path): return _OSGFileParsingMixin._parse_osg_file(path)[1] @staticmethod def get_nodes(path): return _OSGFileParsingMixin._...
0.634996
0.174656
import tensorflow as tf from tensorflow.keras.layers import Layer class SplitString(Layer): """ String Splitter Layer """ def __init__(self, attr_feats, sep='_', feature_name=None, **kwargs): self.attr_feats = attr_feats ...
core/layers.py
import tensorflow as tf from tensorflow.keras.layers import Layer class SplitString(Layer): """ String Splitter Layer """ def __init__(self, attr_feats, sep='_', feature_name=None, **kwargs): self.attr_feats = attr_feats ...
0.88631
0.273497
import argparse import os from ConfigParser import ConfigParser # Local utils aux = os.path.dirname(sys.argv[2]) sys.path.insert(0, aux) import casa_utils as utils """Perform uvcontsub and apply calibration table if required The input for applycal can be configured in the `lineapplycal` (default) section of the conf...
run_uvcontsub.py
import argparse import os from ConfigParser import ConfigParser # Local utils aux = os.path.dirname(sys.argv[2]) sys.path.insert(0, aux) import casa_utils as utils """Perform uvcontsub and apply calibration table if required The input for applycal can be configured in the `lineapplycal` (default) section of the conf...
0.440469
0.330687
from opt.lowrank import LowRankOp from .base_solver import * from opt.utils import get_size from opt import PruningOp, SPruningOp, BertQuantizeOp from misc.train_bert import get_bert_FIM import matplotlib.pyplot as plt import pickle import os from os.path import exists class BaselineSolver(BaseSolver): def __init...
solver/baseline_solver.py
from opt.lowrank import LowRankOp from .base_solver import * from opt.utils import get_size from opt import PruningOp, SPruningOp, BertQuantizeOp from misc.train_bert import get_bert_FIM import matplotlib.pyplot as plt import pickle import os from os.path import exists class BaselineSolver(BaseSolver): def __init...
0.590189
0.188716
class Solution: def _minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ import sys n_row = len(grid) if (n_row == 0): return 0 n_col = len(grid[0]) size = n_row * n_col dp = [sys.maxsize] * (n_row + 1)...
python/64_minimum_path_sum.py
class Solution: def _minPathSum(self, grid): """ :type grid: List[List[int]] :rtype: int """ import sys n_row = len(grid) if (n_row == 0): return 0 n_col = len(grid[0]) size = n_row * n_col dp = [sys.maxsize] * (n_row + 1)...
0.49048
0.468487
from ClassesDAO.ClienteDAO import ClienteDAO from ClassesDAO.FuncionarioDAO import FuncionarioDAO from ClassesDAO.LivroDAO import LivroDAO from ClassesDAO.CategoriaDAO import CategoriaDAO # Classe que implementa as telas da aplicação e também é classe que inicia a aplicação class AluguelPython(object): # Menu pri...
Sistema_aluguel.py
from ClassesDAO.ClienteDAO import ClienteDAO from ClassesDAO.FuncionarioDAO import FuncionarioDAO from ClassesDAO.LivroDAO import LivroDAO from ClassesDAO.CategoriaDAO import CategoriaDAO # Classe que implementa as telas da aplicação e também é classe que inicia a aplicação class AluguelPython(object): # Menu pri...
0.294621
0.2174
from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from django.contrib.auth.models import Group from applications.access.forms import ClientRegistrationForm, AdminRegistrationForm from applications.core.models impor...
src/applications/access/views.py
from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect from django.contrib.auth.models import Group from applications.access.forms import ClientRegistrationForm, AdminRegistrationForm from applications.core.models impor...
0.497559
0.077134
import json import dataflows as DF import time from common import all_data, city_translations, upload_file from city_images import upload_static_image def ranker(): def func(rows): for i, r in enumerate(rows): r['rank'] = i + 1 yield r return func def sort_limit_scores(): d...
tools/city_ranking.py
import json import dataflows as DF import time from common import all_data, city_translations, upload_file from city_images import upload_static_image def ranker(): def func(rows): for i, r in enumerate(rows): r['rank'] = i + 1 yield r return func def sort_limit_scores(): d...
0.439266
0.13852
import csv import getopt import math import sys from time import localtime, strftime, time # Global variables. # The value can be updated by command line options. __data_type = None __input_file_path = None __output_file_path = None def process_inventory_list(): print("-" * 100) time_str = str...
Python_Test/PyDataMiningSample/com/djs/learn/hdb/PreprocessData.py
import csv import getopt import math import sys from time import localtime, strftime, time # Global variables. # The value can be updated by command line options. __data_type = None __input_file_path = None __output_file_path = None def process_inventory_list(): print("-" * 100) time_str = str...
0.19853
0.093058
import pygame as pg from settings import * from tilemap import collide_hit_rect vec = pg.math.Vector2 def collide_with_walls(sprite, group, dir): if dir == 'x': hits = pg.sprite.spritecollide(sprite, group, False, collide_hit_rect) if hits: if sprite.vel.x > 0: ...
sprites.py
import pygame as pg from settings import * from tilemap import collide_hit_rect vec = pg.math.Vector2 def collide_with_walls(sprite, group, dir): if dir == 'x': hits = pg.sprite.spritecollide(sprite, group, False, collide_hit_rect) if hits: if sprite.vel.x > 0: ...
0.333395
0.312055
import shared_gui_delegate_on_robot import time import rosebot import ev3dev.ev3 as ev3 #Sprint 2 Functions def increasing_rate_of_beep(rate_of_beep,rate_of_beep_increase,robot): """:type robot: rosebot.RoseBot""" robot.drive_system.go(20,20) while True: distance = robot.sensor_system.ir_proximit...
src/m1_extra.py
import shared_gui_delegate_on_robot import time import rosebot import ev3dev.ev3 as ev3 #Sprint 2 Functions def increasing_rate_of_beep(rate_of_beep,rate_of_beep_increase,robot): """:type robot: rosebot.RoseBot""" robot.drive_system.go(20,20) while True: distance = robot.sensor_system.ir_proximit...
0.23092
0.266766
from django.contrib.gis import admin from django.forms import ModelForm from vfwheron import models # The Admin.py is used to create fields in the django admin web page # Register your models here. class EntriesAdminForm(ModelForm): class Meta: model = models.Entries fields = ['title', 'abstract'...
vfwheron/admin.py
from django.contrib.gis import admin from django.forms import ModelForm from vfwheron import models # The Admin.py is used to create fields in the django admin web page # Register your models here. class EntriesAdminForm(ModelForm): class Meta: model = models.Entries fields = ['title', 'abstract'...
0.346873
0.135318
import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots #mapbox_token mapbox_access_token = open('mapbox_access_token').read() #get portugal data portugal_url='https://raw.githubusercontent.com/dssg-pt/covid19pt-data/master/data.csv' portugal_df=pd.read_csv(portugal_ur...
covid19PortugalPT.py
import pandas as pd import plotly.graph_objects as go from plotly.subplots import make_subplots #mapbox_token mapbox_access_token = open('mapbox_access_token').read() #get portugal data portugal_url='https://raw.githubusercontent.com/dssg-pt/covid19pt-data/master/data.csv' portugal_df=pd.read_csv(portugal_ur...
0.270673
0.154727
import argparse from collections import defaultdict from os.path import splitext, dirname from g2p_en import G2p import pandas as pd import time from utils import * def get_parser(): parser = argparse.ArgumentParser(formatter_class = argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--libripath', typ...
libriphrase.py
import argparse from collections import defaultdict from os.path import splitext, dirname from g2p_en import G2p import pandas as pd import time from utils import * def get_parser(): parser = argparse.ArgumentParser(formatter_class = argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('--libripath', typ...
0.164953
0.116111
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import functools import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init import torch.optim as optim import common.images import common.metrics import model...
models/panet.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import functools import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.init as init import torch.optim as optim import common.images import common.metrics import model...
0.866937
0.123049
from django.contrib.auth.models import User # local Django from app.models import Notification from app.models import Task from app.models import Host class Notification_Entity(): def insert_one(self, notification): """Insert Notification""" notification = Notification( highlight=not...
app/modules/entity/notification_entity.py
from django.contrib.auth.models import User # local Django from app.models import Notification from app.models import Task from app.models import Host class Notification_Entity(): def insert_one(self, notification): """Insert Notification""" notification = Notification( highlight=not...
0.346873
0.036666
import os import aiohttp from asyncinit import asyncinit from wow.fight import Fight API_URL = "https://www.warcraftlogs.com:443/v1/report/" @asyncinit class WarcraftlogsAPI(): async def __init__(self, code: str): self.code = code self.log_info = await self.get_log_info() async def get_log...
wow/warcraftlogs.py
import os import aiohttp from asyncinit import asyncinit from wow.fight import Fight API_URL = "https://www.warcraftlogs.com:443/v1/report/" @asyncinit class WarcraftlogsAPI(): async def __init__(self, code: str): self.code = code self.log_info = await self.get_log_info() async def get_log...
0.484624
0.178741
from sklearn.grid_search import GridSearchCV from sklearn.ensemble import GradientBoostingClassifier from sklearn.externals import joblib import deepdish.io as io import cPickle import sys CROSS_VAL = False # ----------------------------------------------------------------- def train(): ''' ''' data = io...
trackjets/trackjet_bdt.py
from sklearn.grid_search import GridSearchCV from sklearn.ensemble import GradientBoostingClassifier from sklearn.externals import joblib import deepdish.io as io import cPickle import sys CROSS_VAL = False # ----------------------------------------------------------------- def train(): ''' ''' data = io...
0.468304
0.278287
from typing import Dict from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.postgres.fields import JSONField from django.core.exceptions import ValidationError from django.db import models from django.utils.encoding import force_text from django.utils.translation import ...
mozilla_django_oidc_db/models.py
from typing import Dict from django.conf import settings from django.contrib.auth import get_user_model from django.contrib.postgres.fields import JSONField from django.core.exceptions import ValidationError from django.db import models from django.utils.encoding import force_text from django.utils.translation import ...
0.768473
0.108992
from django.conf import settings from django.db import models import uuid from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) class UserManager(BaseUserManager): def create_user(self, email, password=<PASSWORD>, **extra_fields): """Creates and saves...
server/src/core/models.py
from django.conf import settings from django.db import models import uuid from django.contrib.auth.models import ( AbstractBaseUser, BaseUserManager, PermissionsMixin, ) class UserManager(BaseUserManager): def create_user(self, email, password=<PASSWORD>, **extra_fields): """Creates and saves...
0.596433
0.13134
__all__ = ['TEST_MODEL_VIEW', 'TEST_API_VIEW'] TEST_MODEL_VIEW = """from django.test import TestCase from {{ app_name }}.factories import {{ model_meta.object_name }}Factory from {{ app_name }}.models import {{ model_meta.object_name }} class {{ model_meta.object_name }}TestCase(TestCase): def setUp(self): ...
drf_app_generators/templates/tests.py
__all__ = ['TEST_MODEL_VIEW', 'TEST_API_VIEW'] TEST_MODEL_VIEW = """from django.test import TestCase from {{ app_name }}.factories import {{ model_meta.object_name }}Factory from {{ app_name }}.models import {{ model_meta.object_name }} class {{ model_meta.object_name }}TestCase(TestCase): def setUp(self): ...
0.437824
0.204799
from __future__ import unicode_literals, absolute_import from django.utils.encoding import python_2_unicode_compatible from django.db import models from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class Author(models.Model): #...
shelf/models.py
from __future__ import unicode_literals, absolute_import from django.utils.encoding import python_2_unicode_compatible from django.db import models from django.core.urlresolvers import reverse_lazy from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class Author(models.Model): #...
0.593256
0.134264
load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository") # buildifier: disable=load load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # buildifier: disable=load load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") # buildifier: disable=load def raze_fetch_remote_crates(...
bazel/cargo/crates.bzl
load("@bazel_tools//tools/build_defs/repo:git.bzl", "new_git_repository") # buildifier: disable=load load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") # buildifier: disable=load load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") # buildifier: disable=load def raze_fetch_remote_crates(...
0.314156
0.142649
"""Experiment utils.""" import os import tensorflow as tf from cen import losses from cen import metrics from cen import models from cen import networks class ModeKeys(object): TRAIN = "train" EVAL = "eval" INFER = "infer" def get_input_dtypes(data): """Returns input shapes.""" return {k: str...
cen/experiment/utils.py
"""Experiment utils.""" import os import tensorflow as tf from cen import losses from cen import metrics from cen import models from cen import networks class ModeKeys(object): TRAIN = "train" EVAL = "eval" INFER = "infer" def get_input_dtypes(data): """Returns input shapes.""" return {k: str...
0.83545
0.22396
from __future__ import absolute_import, unicode_literals import abc import logging from collections import OrderedDict, defaultdict from copy import deepcopy from multiprocessing import cpu_count import numpy as np import six from keras.preprocessing.sequence import pad_sequences as keras_pad_sequences from keras.uti...
texcla/preprocessing/utils.py
from __future__ import absolute_import, unicode_literals import abc import logging from collections import OrderedDict, defaultdict from copy import deepcopy from multiprocessing import cpu_count import numpy as np import six from keras.preprocessing.sequence import pad_sequences as keras_pad_sequences from keras.uti...
0.702632
0.328718
from __future__ import absolute_import import calendar import datetime import decimal import iso8601 import sqlalchemy from sqlalchemy.dialects import mysql from sqlalchemy import types from gnocchi import utils class PreciseTimestamp(types.TypeDecorator): """Represents a timestamp precise to the microsecond. ...
gnocchi/indexer/sqlalchemy_types.py
from __future__ import absolute_import import calendar import datetime import decimal import iso8601 import sqlalchemy from sqlalchemy.dialects import mysql from sqlalchemy import types from gnocchi import utils class PreciseTimestamp(types.TypeDecorator): """Represents a timestamp precise to the microsecond. ...
0.750278
0.199347
import logging import doctest import random from ox_cache.mixins import TimedExpiryMixin from ox_cache.memoizers import OxMemoizer from ox_cache.locks import FakeLock class RandomReplacementMixin: """Example mixin to do random replacement. """ def __init__(self, *args, max_size=128, **kwargs): s...
ox_cache/tests.py
import logging import doctest import random from ox_cache.mixins import TimedExpiryMixin from ox_cache.memoizers import OxMemoizer from ox_cache.locks import FakeLock class RandomReplacementMixin: """Example mixin to do random replacement. """ def __init__(self, *args, max_size=128, **kwargs): s...
0.652463
0.173026
from office365.directory.identities.api_connector import IdentityApiConnector from office365.directory.identities.conditional_access_root import ConditionalAccessRoot from office365.directory.identities.userflows.attribute import IdentityUserFlowAttribute from office365.directory.identities.userflows.b2x.user_flow impo...
office365/directory/identities/identity_container.py
from office365.directory.identities.api_connector import IdentityApiConnector from office365.directory.identities.conditional_access_root import ConditionalAccessRoot from office365.directory.identities.userflows.attribute import IdentityUserFlowAttribute from office365.directory.identities.userflows.b2x.user_flow impo...
0.874761
0.15876
import pandas as pd import numpy as np import math import os from scipy.special import entr csvFolderPath = "../../../COIN/4_Repos/Ready_For_Regression/" resultPath = '../Regression/input.csv' def giniCalculator(array): x = np.array(array) mad = np.abs(np.subtract.outer(x, x)).mean() # Relative mean abso...
scripts/DataPrep/DataPrep.py
import pandas as pd import numpy as np import math import os from scipy.special import entr csvFolderPath = "../../../COIN/4_Repos/Ready_For_Regression/" resultPath = '../Regression/input.csv' def giniCalculator(array): x = np.array(array) mad = np.abs(np.subtract.outer(x, x)).mean() # Relative mean abso...
0.380644
0.233553
from gdcmdtools.perm import GDPerm from gdcmdtools.perm import help_permission_text import argparse from argparse import RawTextHelpFormatter from gdcmdtools.base import BASE_INFO from gdcmdtools.base import DEBUG_LEVEL from pprint import pprint import sys import logging logger = logging.getLogger() __THIS_APP = '...
gdperm.py
from gdcmdtools.perm import GDPerm from gdcmdtools.perm import help_permission_text import argparse from argparse import RawTextHelpFormatter from gdcmdtools.base import BASE_INFO from gdcmdtools.base import DEBUG_LEVEL from pprint import pprint import sys import logging logger = logging.getLogger() __THIS_APP = '...
0.239883
0.123842
from kivy.properties import NumericProperty from kivy.uix.widget import Widget from kivy.uix.floatlayout import FloatLayout from kivy.uix.scatter import Scatter from kivy.clock import Clock from math import atan2, degrees class Card(Scatter): symm_boundary = NumericProperty(120) angle = NumericProperty(0) ...
app/widgets/swiper.py
from kivy.properties import NumericProperty from kivy.uix.widget import Widget from kivy.uix.floatlayout import FloatLayout from kivy.uix.scatter import Scatter from kivy.clock import Clock from math import atan2, degrees class Card(Scatter): symm_boundary = NumericProperty(120) angle = NumericProperty(0) ...
0.777131
0.223441
import unittest from src.utils import * class TestUtilsModule(unittest.TestCase): """Tests the utils.py module.""" def test_get_start_end_values_two_or_more_elements_in_array(self) -> None: arr = np.array([1, 2]) return_value = get_start_end_values(array=arr) self.assertEqual(len(ret...
test/test_utils.py
import unittest from src.utils import * class TestUtilsModule(unittest.TestCase): """Tests the utils.py module.""" def test_get_start_end_values_two_or_more_elements_in_array(self) -> None: arr = np.array([1, 2]) return_value = get_start_end_values(array=arr) self.assertEqual(len(ret...
0.728169
0.751169
#Import Libraries import json import logging from flask import Flask from flask import render_template import logging_formatting import test_covid_news_handling as tcnh import covid_data_handler as cdh import covid_news_handling as cnh import test_covid_data_handler as tcdh #Initalise app app = Flask(__n...
user_interface.py
#Import Libraries import json import logging from flask import Flask from flask import render_template import logging_formatting import test_covid_news_handling as tcnh import covid_data_handler as cdh import covid_news_handling as cnh import test_covid_data_handler as tcdh #Initalise app app = Flask(__n...
0.314682
0.055823
import os import sys from setuptools import setup, find_packages from configparser import ConfigParser if sys.version_info < (3, 6): error = """ GWCS supports Python versions 3.6 and above. """ sys.exit(error) conf = ConfigParser() conf.read(['setup.cfg']) metadata = dict(conf.items('metadata')) ...
setup.py
import os import sys from setuptools import setup, find_packages from configparser import ConfigParser if sys.version_info < (3, 6): error = """ GWCS supports Python versions 3.6 and above. """ sys.exit(error) conf = ConfigParser() conf.read(['setup.cfg']) metadata = dict(conf.items('metadata')) ...
0.310067
0.11187
import math import random from utils.NoteUtils import NoteUtils from utils.ScaleUtils import ScaleUtils class DNA: # TODO: add a parameter called melody_range_octaves def __init__(self, genes_length, key_root_note, octave, mode, composition_parameters, underlying_harmony, is_continuation, i...
composingAlgorithms/DNA.py
import math import random from utils.NoteUtils import NoteUtils from utils.ScaleUtils import ScaleUtils class DNA: # TODO: add a parameter called melody_range_octaves def __init__(self, genes_length, key_root_note, octave, mode, composition_parameters, underlying_harmony, is_continuation, i...
0.30013
0.32122
import os import shutil import logging import subprocess import zipfile import requests class Downloader: def __init__(self, outdir, bookdir, cookies): self.outdir = outdir self.bookdir = bookdir self.cookies = cookies def save_bytes(self, bts, name): fpath = os.path.join(self...
bookmate/downloader.py
import os import shutil import logging import subprocess import zipfile import requests class Downloader: def __init__(self, outdir, bookdir, cookies): self.outdir = outdir self.bookdir = bookdir self.cookies = cookies def save_bytes(self, bts, name): fpath = os.path.join(self...
0.242385
0.106551
import math import random import json class Neuron(): """ Represents a single Neuron/Node """ def __init__(self, alpha, weights): """ Initialise a neuron with INPUT weights and a specific alpha """ self._weights = weights self._alpha = alpha def _input(self, inputs): """ R...
neuralnetwork.py
import math import random import json class Neuron(): """ Represents a single Neuron/Node """ def __init__(self, alpha, weights): """ Initialise a neuron with INPUT weights and a specific alpha """ self._weights = weights self._alpha = alpha def _input(self, inputs): """ R...
0.788257
0.719137
from django.test import TestCase from django.test import Client from django.urls import reverse from django.contrib.auth.models import User from .models import bc_sector class TestSector(TestCase): def setUp(self): # Set up data for the whole TestCase bc_sector.objects.create(name="sector1", desc...
companies/tests.py
from django.test import TestCase from django.test import Client from django.urls import reverse from django.contrib.auth.models import User from .models import bc_sector class TestSector(TestCase): def setUp(self): # Set up data for the whole TestCase bc_sector.objects.create(name="sector1", desc...
0.448185
0.239327
from trash import app from flask import render_template, redirect, url_for, request, Flask from PIL import Image from os import path import json from PIL import Image import requests from io import BytesIO from clarifai.rest import ClarifaiApp from clarifai.rest import Image as ClImage # app = Flask(__name__) capp =...
trash/views.py
from trash import app from flask import render_template, redirect, url_for, request, Flask from PIL import Image from os import path import json from PIL import Image import requests from io import BytesIO from clarifai.rest import ClarifaiApp from clarifai.rest import Image as ClImage # app = Flask(__name__) capp =...
0.275812
0.063978
import unittest from copy import deepcopy from apronpy.texpr1 import PyTexpr1 from apronpy.coeff import PyDoubleScalarCoeff, PyMPQScalarCoeff from apronpy.environment import PyEnvironment from apronpy.lincons0 import ConsTyp from apronpy.lincons1 import PyLincons1 from apronpy.linexpr1 import PyLinexpr1 from apronpy....
tests/test_tcons1.py
import unittest from copy import deepcopy from apronpy.texpr1 import PyTexpr1 from apronpy.coeff import PyDoubleScalarCoeff, PyMPQScalarCoeff from apronpy.environment import PyEnvironment from apronpy.lincons0 import ConsTyp from apronpy.lincons1 import PyLincons1 from apronpy.linexpr1 import PyLinexpr1 from apronpy....
0.446012
0.40751
import os.path import itertools import Tools import random import numpy as np import scipy import scipy.stats NBTESTS = 10 VECDIM = [12,14,20] def entropyTest(config,nb): inputs = [] outputs = [] vecDim = VECDIM[nb % len(VECDIM)] dims=np.array([NBTESTS,vecDim]) for _ in range(0,NBTESTS): ...
CMSIS/DSP/Testing/PatternGeneration/Stats.py
import os.path import itertools import Tools import random import numpy as np import scipy import scipy.stats NBTESTS = 10 VECDIM = [12,14,20] def entropyTest(config,nb): inputs = [] outputs = [] vecDim = VECDIM[nb % len(VECDIM)] dims=np.array([NBTESTS,vecDim]) for _ in range(0,NBTESTS): ...
0.262653
0.27211
from pm4py.algo.enhancement.sna.variants.log import handover as log_handover, jointactivities as log_jointactivities, \ subcontracting as log_subcontracting, working_together as log_workingtogether from pm4py.algo.enhancement.sna.variants.pandas import handover as pd_handover, subcontracting as pd_subcontracting, \...
ws2122-lspm/Lib/site-packages/pm4py/algo/enhancement/sna/algorithm.py
from pm4py.algo.enhancement.sna.variants.log import handover as log_handover, jointactivities as log_jointactivities, \ subcontracting as log_subcontracting, working_together as log_workingtogether from pm4py.algo.enhancement.sna.variants.pandas import handover as pd_handover, subcontracting as pd_subcontracting, \...
0.872958
0.282573
import time import requests import json import sys import getopt mytimeinterval = 30 runcount = 1 def get_key_auth_token(ip,ver,uname,pword): # The url for the post ticket API request post_url = "https://partners.dnaspaces.io/client/v1/partner/activateOnPremiseApp" print(post_url) urllib3.disable_war...
dnaspace_data_Adapt.py
import time import requests import json import sys import getopt mytimeinterval = 30 runcount = 1 def get_key_auth_token(ip,ver,uname,pword): # The url for the post ticket API request post_url = "https://partners.dnaspaces.io/client/v1/partner/activateOnPremiseApp" print(post_url) urllib3.disable_war...
0.036813
0.084003
import logging import os import re import shutil from pprint import pformat from base64 import urlsafe_b64encode import boto3 import yaml from botocore.errorfactory import ClientError from .aws_facts import get_vpc_facts logger = logging.getLogger(__name__) def ensure_aws_facts(self): self.vpc_facts = get_vpc_...
kforce/pre_steps.py
import logging import os import re import shutil from pprint import pformat from base64 import urlsafe_b64encode import boto3 import yaml from botocore.errorfactory import ClientError from .aws_facts import get_vpc_facts logger = logging.getLogger(__name__) def ensure_aws_facts(self): self.vpc_facts = get_vpc_...
0.307774
0.110759
from decouple import config import os from pathlib import Path import cv2 # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/...
Backend/yoga_pose_analyser/settings.py
from decouple import config import os from pathlib import Path import cv2 # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/...
0.462959
0.086131
import sys def set_path(path: str): try: sys.path.index(path) except ValueError: sys.path.insert(0, path) # set programatically the path to 'openai_ros' directory (alternately can also set PYTHONPATH) set_path('/media/suresh/research/awesome-robotics/active-slam/catkin_ws/src/openai-rosbot-env...
localization/src/localization_rl_agent.py
import sys def set_path(path: str): try: sys.path.index(path) except ValueError: sys.path.insert(0, path) # set programatically the path to 'openai_ros' directory (alternately can also set PYTHONPATH) set_path('/media/suresh/research/awesome-robotics/active-slam/catkin_ws/src/openai-rosbot-env...
0.457137
0.198724
from typing import Iterable, Dict class RepositoryStat: """ Contribution statistics for a repository """ def __init__(self, name_with_owner: str): self.name_with_owner: str = name_with_owner self.pull_count: int = 0 self.issue_count: int = 0 self.commit_count: int = 0 ...
show_me/db.py
from typing import Iterable, Dict class RepositoryStat: """ Contribution statistics for a repository """ def __init__(self, name_with_owner: str): self.name_with_owner: str = name_with_owner self.pull_count: int = 0 self.issue_count: int = 0 self.commit_count: int = 0 ...
0.790571
0.173919
import cv2 as cv import numpy as np import torch from detectron2.modeling import GeneralizedRCNN from detectron2.layers import batched_nms from torch.onnx import export from train_net import DetectionCheckpointer, default_argument_parser, setup class RCNNExporter(GeneralizedRCNN): def __init__(self, *args, **kwa...
rcnn_export.py
import cv2 as cv import numpy as np import torch from detectron2.modeling import GeneralizedRCNN from detectron2.layers import batched_nms from torch.onnx import export from train_net import DetectionCheckpointer, default_argument_parser, setup class RCNNExporter(GeneralizedRCNN): def __init__(self, *args, **kwa...
0.877798
0.395718
from common_fixtures import * # NOQA def test_register_physical_host(admin_client): uri = 'sim://{}'.format(random_str()) agent = admin_client.create_agent(uri=uri) agent = admin_client.wait_success(agent) assert agent.state == 'active' hosts = agent.hosts() for _ in range(10): hos...
tests/integration/cattletest/core/test_physical_host.py
from common_fixtures import * # NOQA def test_register_physical_host(admin_client): uri = 'sim://{}'.format(random_str()) agent = admin_client.create_agent(uri=uri) agent = admin_client.wait_success(agent) assert agent.state == 'active' hosts = agent.hosts() for _ in range(10): hos...
0.484624
0.366845
from feedreader.feeds.base import (PREFERRED_LINK_TYPES, PREFERRED_CONTENT_TYPES, Feed, Item, get_element_text, get_attribute, search_child, get_descendant, get_descendant_text, get_descendant_datetime, safe_strip, ...
feedreader/feeds/atom03.py
from feedreader.feeds.base import (PREFERRED_LINK_TYPES, PREFERRED_CONTENT_TYPES, Feed, Item, get_element_text, get_attribute, search_child, get_descendant, get_descendant_text, get_descendant_datetime, safe_strip, ...
0.737158
0.119229
import collections import os.path as osp import sys import PIL.Image import numpy as np import torch from torch.utils import data from .transforms import ImageTransformType, FlipType, apply_transform class CityScape(data.Dataset): class_names = np.array([ 'ego vehicle', 'rectification border', ...
torchfcn/datasets/cityscape.py
import collections import os.path as osp import sys import PIL.Image import numpy as np import torch from torch.utils import data from .transforms import ImageTransformType, FlipType, apply_transform class CityScape(data.Dataset): class_names = np.array([ 'ego vehicle', 'rectification border', ...
0.343452
0.30399
from password import GMAIL_PASSWORD_KEY ALTERNATIVE = "alternative" ASSET = "asset" ASSET_IDX = 0 BALANCE = "balance" BINANCE = "Binance" BOTH = "BOTH" BNB = "BNB" BNBUSDT = "BNBUSDT" BTC = "BTC" BTCUSDT = "BTCUSDT" BUY = "BUY" BYBIT = "Bybit" CEP = "CEP__" CEPS_PATH = "/ceps/" COINBASE = "Coinbase" CURRENT_SIDE = "c...
scripts/constants.py
from password import GMAIL_PASSWORD_KEY ALTERNATIVE = "alternative" ASSET = "asset" ASSET_IDX = 0 BALANCE = "balance" BINANCE = "Binance" BOTH = "BOTH" BNB = "BNB" BNBUSDT = "BNBUSDT" BTC = "BTC" BTCUSDT = "BTCUSDT" BUY = "BUY" BYBIT = "Bybit" CEP = "CEP__" CEPS_PATH = "/ceps/" COINBASE = "Coinbase" CURRENT_SIDE = "c...
0.136234
0.057573
import unittest import os import sys PACKAGE_PARENT = '..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) from parse_display import ParseDisplayOutput from command_generator import Comm...
tests/test_command_generator.py
import unittest import os import sys PACKAGE_PARENT = '..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) sys.path.append(os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_PARENT))) from parse_display import ParseDisplayOutput from command_generator import Comm...
0.163012
0.254509
from TokenType import * from Types import * #begin Interpreter class class Interpreter: #Utility functions #define evaluate function def evaluate(self, node): methodName = node.__class__.__name__ #Get method name method = getattr(self, methodName, self.noVisit) #Get method return m...
src/Interpreter.py
from TokenType import * from Types import * #begin Interpreter class class Interpreter: #Utility functions #define evaluate function def evaluate(self, node): methodName = node.__class__.__name__ #Get method name method = getattr(self, methodName, self.noVisit) #Get method return m...
0.532668
0.316343
import sys aux = [0]*(999999) #Método iterativo (Input: arreglo de denominaciones, monto a cambiar. Output: solución (cantidad mínima de monedas a usar), arreglo que almacena las monedas ocupadas para el cambio) def bottomUpChange(denom, monto): # Se inicializa la tabla que almacena el minimo numero de moneda...
coinChange.py
import sys aux = [0]*(999999) #Método iterativo (Input: arreglo de denominaciones, monto a cambiar. Output: solución (cantidad mínima de monedas a usar), arreglo que almacena las monedas ocupadas para el cambio) def bottomUpChange(denom, monto): # Se inicializa la tabla que almacena el minimo numero de moneda...
0.094788
0.698115
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from de...
pybind/slxos/v16r_1_00b/brocade_mpls_rpc/show_mpls_ldp_fec_vc/output/ldp_fec_vc_rec_list/__init__.py
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from de...
0.555435
0.055669
from django.db import models # Create your models here. class Location(models.Model): location_name = models.CharField(max_length = 25) def __str__(self): return self.location_name def save_location(self): self.save() def delete_location(location_id): Location.objects.filter(...
gallery/models.py
from django.db import models # Create your models here. class Location(models.Model): location_name = models.CharField(max_length = 25) def __str__(self): return self.location_name def save_location(self): self.save() def delete_location(location_id): Location.objects.filter(...
0.510496
0.223165
import pygame as game import time import random game.init() color_white = (255, 255, 255) color_black = (0, 0, 0) color_red = (255, 0, 0) green = (0, 155, 0) display_width = 800 display_height = 600 DisplayScreen = game.display.set_mode((display_width, display_height)) game.display.set_caption('') image = game.im...
Chapter11/SnakeGameFinal.py
import pygame as game import time import random game.init() color_white = (255, 255, 255) color_black = (0, 0, 0) color_red = (255, 0, 0) green = (0, 155, 0) display_width = 800 display_height = 600 DisplayScreen = game.display.set_mode((display_width, display_height)) game.display.set_caption('') image = game.im...
0.330147
0.222954
import sys import ds_format as ds import os import numpy as np from alcf.models import META from alcf import misc import aquarius_time as aq VARS = [ 'gh', 't', 'ciwc', 'clw', 'tcc', 'sp', ] VARS_AUX = [ 'level', 'time', 'latitude', 'longitude', ] TRANS = { 'gh': 'zfull', 'latitude': 'lat', 'longitude':...
alcf/models/jra55.py
import sys import ds_format as ds import os import numpy as np from alcf.models import META from alcf import misc import aquarius_time as aq VARS = [ 'gh', 't', 'ciwc', 'clw', 'tcc', 'sp', ] VARS_AUX = [ 'level', 'time', 'latitude', 'longitude', ] TRANS = { 'gh': 'zfull', 'latitude': 'lat', 'longitude':...
0.094469
0.213152
import json from iamheadless_projects.lookups.pagination import ALLOWED_FORMATS from .. import utils from ..pydantic_models import ItemSchema, NestedItemSchema from .index_filters import filter_by_lookup_indexes def retrieve_item( item_id, lookup_field='id', format='queryset', item_...
iamheadless_publisher/lookups/item_retrieve.py
import json from iamheadless_projects.lookups.pagination import ALLOWED_FORMATS from .. import utils from ..pydantic_models import ItemSchema, NestedItemSchema from .index_filters import filter_by_lookup_indexes def retrieve_item( item_id, lookup_field='id', format='queryset', item_...
0.195594
0.108048
import cvxpy.utilities as u import cvxpy.lin_ops.lin_utils as lu from cvxpy.expressions.constants.parameter import Parameter from cvxpy.atoms.elementwise.elementwise import Elementwise from cvxpy.atoms.elementwise.abs import abs from cvxpy.atoms.elementwise.square import square import numpy as np class huber(Elementwi...
src/tools/ecos/cvxpy/cvxpy/atoms/elementwise/huber.py
import cvxpy.utilities as u import cvxpy.lin_ops.lin_utils as lu from cvxpy.expressions.constants.parameter import Parameter from cvxpy.atoms.elementwise.elementwise import Elementwise from cvxpy.atoms.elementwise.abs import abs from cvxpy.atoms.elementwise.square import square import numpy as np class huber(Elementwi...
0.890711
0.541469
import json buildings = ["HEADQUARTER", "BARRACKS", "STABLE", "WORKSHOP", "ACADEMY", "SMITHY", "RALLY_POINT", "STATUE", "MARKET", "TIMBER_CAMP", "CLAY_PIT", "IRON_MINE", "FARM", "WAREHOUSE", "HIDING_PLACE", "WALL"] requirements = [ {}, {"HEADQUARTER": 3}, {"HEADQUARTER": 10, "BARRACKS": 5, "S...
resources/buildings/generate_files.py
import json buildings = ["HEADQUARTER", "BARRACKS", "STABLE", "WORKSHOP", "ACADEMY", "SMITHY", "RALLY_POINT", "STATUE", "MARKET", "TIMBER_CAMP", "CLAY_PIT", "IRON_MINE", "FARM", "WAREHOUSE", "HIDING_PLACE", "WALL"] requirements = [ {}, {"HEADQUARTER": 3}, {"HEADQUARTER": 10, "BARRACKS": 5, "S...
0.141994
0.346569
import os import shutil from wmt.config import site from wmt.models.submissions import prepend_to_path from wmt.utils.hook import find_simulation_input_file from topoflow_utils.hook import choices_map file_list = [] # ['pixel_file'] def uppercase_choice(choice): """Formats a string for consumption by TopoFlow....
metadata/ErodeD8Global/hooks/pre-stage.py
import os import shutil from wmt.config import site from wmt.models.submissions import prepend_to_path from wmt.utils.hook import find_simulation_input_file from topoflow_utils.hook import choices_map file_list = [] # ['pixel_file'] def uppercase_choice(choice): """Formats a string for consumption by TopoFlow....
0.409929
0.276526
test001=\ { } test002=\ { "name":"counter" } test003=\ { "name":"counter", "description":"Hi there, all okay!", } test0 =\ { "name":"counter", "description":"Hi there, all okay!", "parameters":[] } # Payload to persist FogFunction test101=\ { } test1...
test/UnitTest/persistance/data.py
test001=\ { } test002=\ { "name":"counter" } test003=\ { "name":"counter", "description":"Hi there, all okay!", } test0 =\ { "name":"counter", "description":"Hi there, all okay!", "parameters":[] } # Payload to persist FogFunction test101=\ { } test1...
0.460289
0.51751
from django.conf.urls import include, url from glue2_views_api.views import * # Define our custom URLs # Additionally, we include login URLs for the browseable API. urlpatterns = [ # url(r'^applicationenvironment/$', # ApplicationEnvironment_List.as_view(), # name='applicationenvironment-list'), u...
django_xsede_warehouse/glue2_views_api/urls.py
from django.conf.urls import include, url from glue2_views_api.views import * # Define our custom URLs # Additionally, we include login URLs for the browseable API. urlpatterns = [ # url(r'^applicationenvironment/$', # ApplicationEnvironment_List.as_view(), # name='applicationenvironment-list'), u...
0.287168
0.060975
import torch import torch.functional as F import torch.nn as nn import torch.optim as optim import torch.utils.data as data from util import TUTDataset from model import SELDNet import argparse import sys import os from pprint import pprint # test tensorboardX from tensorboardX import SummaryWriter dummy_input = (to...
test.py
import torch import torch.functional as F import torch.nn as nn import torch.optim as optim import torch.utils.data as data from util import TUTDataset from model import SELDNet import argparse import sys import os from pprint import pprint # test tensorboardX from tensorboardX import SummaryWriter dummy_input = (to...
0.458106
0.300592
from PyQt5 import QtWidgets, QtCore, QtGui from ui import Window class Settings(Window): """Настройка графического инфтерфейса""" def __init__(self): super(Settings, self).__init__() self.style_sheet = "font: 14pt \"Times New Roman\";" # Размер и шрифт текста self.header_list = ["Улиц...
settings.py
from PyQt5 import QtWidgets, QtCore, QtGui from ui import Window class Settings(Window): """Настройка графического инфтерфейса""" def __init__(self): super(Settings, self).__init__() self.style_sheet = "font: 14pt \"Times New Roman\";" # Размер и шрифт текста self.header_list = ["Улиц...
0.400632
0.10307
from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.CreateModel( name='do...
main_app/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 = [ ('auth', '0011_update_proxy_permissions'), ] operations = [ migrations.CreateModel( name='do...
0.572842
0.154058
import argparse import json import os import pdb import sys import time import string import torch from torch.utils.data import DataLoader sys.path.append('.') from config import special_toks, train_conf from dataset import FastDataset from models import BlindStatelessLSTM, MultiAttentiveTransformer from tools.simmc...
mm_response_generation/eval.py
import argparse import json import os import pdb import sys import time import string import torch from torch.utils.data import DataLoader sys.path.append('.') from config import special_toks, train_conf from dataset import FastDataset from models import BlindStatelessLSTM, MultiAttentiveTransformer from tools.simmc...
0.252108
0.182863
import sys from struct import unpack class ProtoBufAnalyserError(Exception): """ Class for error in the parameters provided to this script """ def __init__(self, msg): print(ERROR : " + msg) sys.exit(1) pass class ProtoBufAnalyser(object): ''' This cla...
ProtoBufAnalyser.py
import sys from struct import unpack class ProtoBufAnalyserError(Exception): """ Class for error in the parameters provided to this script """ def __init__(self, msg): print(ERROR : " + msg) sys.exit(1) pass class ProtoBufAnalyser(object): ''' This cla...
0.301259
0.200186
import torch from .base import ModuleBase class YoloLoss(ModuleBase): def __init__(self, num_classes, prior_box, object_scale=5): super().__init__() self.num_classes = num_classes self.prior_box = prior_box self.object_scale = 5 self.negative_location_scale = 0.01 def ...
mitorch/models/modules/yolo_loss.py
import torch from .base import ModuleBase class YoloLoss(ModuleBase): def __init__(self, num_classes, prior_box, object_scale=5): super().__init__() self.num_classes = num_classes self.prior_box = prior_box self.object_scale = 5 self.negative_location_scale = 0.01 def ...
0.85897
0.673146
import sys import json import datetime from tkinter import Tk, Canvas, Entry, Button, Frame, Label, StringVar, ALL from tkinter import ttk from tkinter import messagebox import urllib.request import urllib.parse class WeatherReporter: weather_data = None APIKEY = 'ENTER_YOUR_API_KEY_HERE' def __init__(s...
Chapter 09/9.06_weather_ reporter.py
import sys import json import datetime from tkinter import Tk, Canvas, Entry, Button, Frame, Label, StringVar, ALL from tkinter import ttk from tkinter import messagebox import urllib.request import urllib.parse class WeatherReporter: weather_data = None APIKEY = 'ENTER_YOUR_API_KEY_HERE' def __init__(s...
0.32178
0.146759
from copy import deepcopy from functools import partial from typing import Any, Callable, Dict, Optional, Tuple from .types import Index, KeyAttributeType, TableQuery from .utils.index import ( # noqa # included only for cleaner imports find_index, hash_key_name, range_key_name, require_index, ) def...
xoto3/dynamodb/query.py
from copy import deepcopy from functools import partial from typing import Any, Callable, Dict, Optional, Tuple from .types import Index, KeyAttributeType, TableQuery from .utils.index import ( # noqa # included only for cleaner imports find_index, hash_key_name, range_key_name, require_index, ) def...
0.883889
0.409044
from ._base import BaseTestCase from datetime import datetime, timedelta, timezone import dateutil.parser from django.conf import settings from django.contrib.auth.models import User from django.core.management import call_command from django.test import override_settings from ban.models import Ban, Warn class Tes...
fts/Ban.py
from ._base import BaseTestCase from datetime import datetime, timedelta, timezone import dateutil.parser from django.conf import settings from django.contrib.auth.models import User from django.core.management import call_command from django.test import override_settings from ban.models import Ban, Warn class Tes...
0.496582
0.24289
from typing import Optional from fastapi import APIRouter, Depends, Header from fastapi.security import OAuth2PasswordBearer from sql import schemas, crud, database, models from sql.database import db_state_default from core import exceptions database.db.connect() database.db.create_tables( [ models.User, ...
blog/api/post.py
from typing import Optional from fastapi import APIRouter, Depends, Header from fastapi.security import OAuth2PasswordBearer from sql import schemas, crud, database, models from sql.database import db_state_default from core import exceptions database.db.connect() database.db.create_tables( [ models.User, ...
0.712432
0.088465
from typing import Tuple from django.db import models from django.utils import timezone from jsonfield import JSONField from backend.utils.models import BaseTSModel from .managers import RepositoryAuthManager, RepositoryManager class Repository(BaseTSModel): url = models.URLField('URL') name = models.CharF...
bcs-ui/backend/helm/helm/models/repo.py
from typing import Tuple from django.db import models from django.utils import timezone from jsonfield import JSONField from backend.utils.models import BaseTSModel from .managers import RepositoryAuthManager, RepositoryManager class Repository(BaseTSModel): url = models.URLField('URL') name = models.CharF...
0.424293
0.102799
"""Piecewise-linearly-controlled rotation.""" from typing import List, Optional import numpy as np from qiskit.circuit import QuantumRegister, QuantumCircuit from qiskit.circuit.exceptions import CircuitError from qiskit.circuit.library.arithmetic.linear_pauli_rotations import LinearPauliRotations from unqomp.examp...
unqomp/examples/piecewiselinrot.py
"""Piecewise-linearly-controlled rotation.""" from typing import List, Optional import numpy as np from qiskit.circuit import QuantumRegister, QuantumCircuit from qiskit.circuit.exceptions import CircuitError from qiskit.circuit.library.arithmetic.linear_pauli_rotations import LinearPauliRotations from unqomp.examp...
0.922961
0.646886
#Types. from typing import Dict, List, IO, Any #PartialMeritRemoval class. from PythonTests.Classes.Consensus.MeritRemoval import PartialMeritRemoval #TestError Exception. from PythonTests.Tests.Errors import TestError #Meros classes. from PythonTests.Meros.Meros import MessageType from PythonTests.Meros.RPC import...
PythonTests/Tests/Consensus/MeritRemoval/PartialTest.py
#Types. from typing import Dict, List, IO, Any #PartialMeritRemoval class. from PythonTests.Classes.Consensus.MeritRemoval import PartialMeritRemoval #TestError Exception. from PythonTests.Tests.Errors import TestError #Meros classes. from PythonTests.Meros.Meros import MessageType from PythonTests.Meros.RPC import...
0.662469
0.362377
from configparser import ConfigParser import os import numpy as np import matplotlib.pyplot as plt import gravelamps.lensing #Read in the simple INI file utils_testing.ini config = ConfigParser() config.read("utils_testing.ini") #Check if the data directory exists, if it doesn't make it outdir = config.get("output_se...
review_materials/utils_testing/utils_testing.py
from configparser import ConfigParser import os import numpy as np import matplotlib.pyplot as plt import gravelamps.lensing #Read in the simple INI file utils_testing.ini config = ConfigParser() config.read("utils_testing.ini") #Check if the data directory exists, if it doesn't make it outdir = config.get("output_se...
0.417271
0.591959
from django.contrib.auth import get_user_model from django.test import TestCase from django.test.client import Client from formfactory.tests.test_base import load_fixtures class AdminTestCase(TestCase): def setUp(self): load_fixtures(self) self.client = Client() self.editor = get_user_mod...
formfactory/tests/test_admin.py
from django.contrib.auth import get_user_model from django.test import TestCase from django.test.client import Client from formfactory.tests.test_base import load_fixtures class AdminTestCase(TestCase): def setUp(self): load_fixtures(self) self.client = Client() self.editor = get_user_mod...
0.506836
0.130535
import time from binaryninja import (AddressField, BackgroundTaskThread, ChoiceField, HighlightStandardColor, Settings, execute_on_main_thread_and_wait, get_form_input, log) from binaryninjaui import FileContext, LinearView, UIContext, ViewFrame from emulator.errors im...
emulator/emulatorui/buttons.py
import time from binaryninja import (AddressField, BackgroundTaskThread, ChoiceField, HighlightStandardColor, Settings, execute_on_main_thread_and_wait, get_form_input, log) from binaryninjaui import FileContext, LinearView, UIContext, ViewFrame from emulator.errors im...
0.419172
0.090333
import unittest from mapfmclient import MarkedLocation, Problem from ictsm.solver import solve """ Basic single-agent pathfinding tests using top-level 'solve' interface """ class SolveTestSingle(unittest.TestCase): def setUp(self) -> None: def creator(start, goal): return Problem( ...
src/test/test_solve.py
import unittest from mapfmclient import MarkedLocation, Problem from ictsm.solver import solve """ Basic single-agent pathfinding tests using top-level 'solve' interface """ class SolveTestSingle(unittest.TestCase): def setUp(self) -> None: def creator(start, goal): return Problem( ...
0.614857
0.770939