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 django.db import models from django.urls import reverse from django.db.models import F class CountryArea(models.Model): country_area_id = models.AutoField(primary_key=True) country_area_name = models.CharField(unique=True, max_length=100) m49_code = models.SmallIntegerField() iso_alpha3_code = mod...
movies/models.py
from django.db import models from django.urls import reverse from django.db.models import F class CountryArea(models.Model): country_area_id = models.AutoField(primary_key=True) country_area_name = models.CharField(unique=True, max_length=100) m49_code = models.SmallIntegerField() iso_alpha3_code = mod...
0.644561
0.140926
import contextlib import json from unittest.mock import patch import pytest from sm.engine.db import DB from sm.rest import api from sm.rest.databases import MALFORMED_CSV, BAD_DATA from sm.rest.utils import ALREADY_EXISTS from .utils import create_test_molecular_db GROUP_ID = '123e4567-e89b-12d3-a456-426655440000' ...
metaspace/engine/tests/test_api_databases.py
import contextlib import json from unittest.mock import patch import pytest from sm.engine.db import DB from sm.rest import api from sm.rest.databases import MALFORMED_CSV, BAD_DATA from sm.rest.utils import ALREADY_EXISTS from .utils import create_test_molecular_db GROUP_ID = '123e4567-e89b-12d3-a456-426655440000' ...
0.47926
0.287293
import unittest from pyfuzzy.operators import dot class dotTestCase(unittest.TestCase): # Test input type - Input argument should be a dictionary. def test_dot_1(self): A = [(1,0.1), (2,0.8), (3,0.5)] B = [(1, 0.2), (2, 0.7), (3, 0.4)] self.assertRaises(TypeError, lambda: dot.dot(A, ...
tests/operators/test_dot.py
import unittest from pyfuzzy.operators import dot class dotTestCase(unittest.TestCase): # Test input type - Input argument should be a dictionary. def test_dot_1(self): A = [(1,0.1), (2,0.8), (3,0.5)] B = [(1, 0.2), (2, 0.7), (3, 0.4)] self.assertRaises(TypeError, lambda: dot.dot(A, ...
0.751101
0.84039
# imports import os import argparse # constants LPORT_DEFAULT = 33777 LOG_LEVELS = ['CRITICAL','ERROR','WARNING','WARN','INFO','DEBUG'] # exception classes class ArgparseError(Exception):pass # interface functions def vdeploy_options(): parser = argparse.ArgumentParser(description= 'Deploy VMs into your cloud i...
src/getopts.py
# imports import os import argparse # constants LPORT_DEFAULT = 33777 LOG_LEVELS = ['CRITICAL','ERROR','WARNING','WARN','INFO','DEBUG'] # exception classes class ArgparseError(Exception):pass # interface functions def vdeploy_options(): parser = argparse.ArgumentParser(description= 'Deploy VMs into your cloud i...
0.24726
0.05848
import pickle from collections import defaultdict from operator import itemgetter import config import parse_midas_data cohort = 'hmp' # hmp or infant good_species_list = parse_midas_data.parse_good_species_list() # Dictionaries for storing pickled data gene_snp_change_dict = defaultdict(int) gene_gainloss_dict = d...
archive/old_plots/gene_changes_pickle_analysis.py
import pickle from collections import defaultdict from operator import itemgetter import config import parse_midas_data cohort = 'hmp' # hmp or infant good_species_list = parse_midas_data.parse_good_species_list() # Dictionaries for storing pickled data gene_snp_change_dict = defaultdict(int) gene_gainloss_dict = d...
0.35768
0.153232
import os from unittest import TestCase from cloudshell.cm.ansible.ansible_shell import AnsibleShell from cloudshell.cm.ansible.domain.Helpers.ansible_connection_helper import AnsibleConnectionHelper from cloudshell.cm.ansible.domain.exceptions import AnsibleException from cloudshell.cm.ansible.domain.ansible_configur...
package/tests/test_ansible_shell.py
import os from unittest import TestCase from cloudshell.cm.ansible.ansible_shell import AnsibleShell from cloudshell.cm.ansible.domain.Helpers.ansible_connection_helper import AnsibleConnectionHelper from cloudshell.cm.ansible.domain.exceptions import AnsibleException from cloudshell.cm.ansible.domain.ansible_configur...
0.384219
0.118717
import numpy import cellprofiler_core.image import cellprofiler_core.measurement import cellprofiler.modules.invertforprinting import cellprofiler_core.object import cellprofiler_core.pipeline import cellprofiler_core.workspace I_RED_IN = "RedInput" I_GREEN_IN = "GreenInput" I_BLUE_IN = "BlueInput" I_COLOR_IN = "Co...
CellProfiler/tests/modules/test_invertforprinting.py
import numpy import cellprofiler_core.image import cellprofiler_core.measurement import cellprofiler.modules.invertforprinting import cellprofiler_core.object import cellprofiler_core.pipeline import cellprofiler_core.workspace I_RED_IN = "RedInput" I_GREEN_IN = "GreenInput" I_BLUE_IN = "BlueInput" I_COLOR_IN = "Co...
0.506591
0.302713
import argparse from jinja2 import Template def main(): parser = argparse.ArgumentParser(description=__doc__.strip()) parser.add_argument('-r', '--regs', type=str, help="register list") parser.add_argument('-n', '--name', type=str, help="module name") parser.add_argument('-o', '--output', type=str,...
example/HTG9200/fpga_10g/rtl/si5341_i2c_init.py
import argparse from jinja2 import Template def main(): parser = argparse.ArgumentParser(description=__doc__.strip()) parser.add_argument('-r', '--regs', type=str, help="register list") parser.add_argument('-n', '--name', type=str, help="module name") parser.add_argument('-o', '--output', type=str,...
0.392453
0.100304
import datetime import time from SuperGLU.Core.Messaging import Message from SuperGLU.Core.MessagingGateway import BaseService class BaseLearnLogger(BaseService): ''' Initialize the standard ITS logger service @param gateway: The parent gateway for this service @type gateway: Messaging_Gateway...
python_module/SuperGLU/Services/LoggingService/Base_Learn_Logger.py
import datetime import time from SuperGLU.Core.Messaging import Message from SuperGLU.Core.MessagingGateway import BaseService class BaseLearnLogger(BaseService): ''' Initialize the standard ITS logger service @param gateway: The parent gateway for this service @type gateway: Messaging_Gateway...
0.654453
0.188828
import numpy as np from scipy import stats import statsmodels.tsa.ar_model from statsmodels.tools.sm_exceptions import MissingDataError from ..computation import Transformer, Graph, Constant from .util import apply_to_axis, length from .calculators.statistics import * from .queries import Count, Slice from .mathematic...
tsfuse/transformers/statistics.py
import numpy as np from scipy import stats import statsmodels.tsa.ar_model from statsmodels.tools.sm_exceptions import MissingDataError from ..computation import Transformer, Graph, Constant from .util import apply_to_axis, length from .calculators.statistics import * from .queries import Count, Slice from .mathematic...
0.866486
0.556821
import os import numpy as np from astropy.io import fits from astropy import units as u import sys import string import matplotlib.pylab as plot import nrm_analysis from nrm_analysis.fringefitting.LG_Model import NRM_Model from nrm_analysis.misctools import utils from nrm_analysis import nrm_core, InstrumentData fro...
scripts/driver_abdor.py
import os import numpy as np from astropy.io import fits from astropy import units as u import sys import string import matplotlib.pylab as plot import nrm_analysis from nrm_analysis.fringefitting.LG_Model import NRM_Model from nrm_analysis.misctools import utils from nrm_analysis import nrm_core, InstrumentData fro...
0.544801
0.214403
from django.test import TestCase from datetime import date from TheBlueAlliance.event import * class EventTestCase(TestCase): def test_get_event(self): #Should be successful print("Testing TBA get_event") event2018crc = get_event('2018crc') self.assertEqual(event2018crc.name,'China...
FRCScouting/TheBlueAlliance/tests/test_event.py
from django.test import TestCase from datetime import date from TheBlueAlliance.event import * class EventTestCase(TestCase): def test_get_event(self): #Should be successful print("Testing TBA get_event") event2018crc = get_event('2018crc') self.assertEqual(event2018crc.name,'China...
0.471223
0.221761
import logging import tempfile from PIL import Image from typing import Dict, Optional, Any from assemblyline.common import forge from assemblyline.common import log as al_log from assemblyline.common.classification import Classification from assemblyline_v4_service.common.result import Result from assemblyline_v4_se...
assemblyline_v4_service/common/request.py
import logging import tempfile from PIL import Image from typing import Dict, Optional, Any from assemblyline.common import forge from assemblyline.common import log as al_log from assemblyline.common.classification import Classification from assemblyline_v4_service.common.result import Result from assemblyline_v4_se...
0.87821
0.304291
import usb.core import usb.util import threading _USB_HID_CLASS_CTRL_bmRequestType = 0x21 _USB_HID_CLASS_CTRL_bRequest_SET_REPORT = 0x09 _USB_HID_CLASS_CTRL_wValue_REPORT_TYPE_INPUT = 0x01 << 8 _USB_HID_CLASS_CTRL_wValue_REPORT_TYPE_OUTPUT = 0x02 << 8 _USB_HID_CLASS_CTRL_wValue_REPORT_TYPE_FEATURE = 0x03 << 8 _USB_...
lpc4357_usb_custom_hid/tools/custom_hid.py
import usb.core import usb.util import threading _USB_HID_CLASS_CTRL_bmRequestType = 0x21 _USB_HID_CLASS_CTRL_bRequest_SET_REPORT = 0x09 _USB_HID_CLASS_CTRL_wValue_REPORT_TYPE_INPUT = 0x01 << 8 _USB_HID_CLASS_CTRL_wValue_REPORT_TYPE_OUTPUT = 0x02 << 8 _USB_HID_CLASS_CTRL_wValue_REPORT_TYPE_FEATURE = 0x03 << 8 _USB_...
0.272121
0.073663
import sys import numpy as np from PyQt5.QtGui import QColor from OpenGL import GL, GLU import hmath.mm_math as mm import motion.motion as motion import renderer.draw_figure as df DEFAULT_COLOR = (0., 1., 1., 1.) DEFAULT_LINK_WIDTH = 5 LINE_MODE = True class Renderer: def __init__(self): self._visible ...
modules/renderer/renderer.py
import sys import numpy as np from PyQt5.QtGui import QColor from OpenGL import GL, GLU import hmath.mm_math as mm import motion.motion as motion import renderer.draw_figure as df DEFAULT_COLOR = (0., 1., 1., 1.) DEFAULT_LINK_WIDTH = 5 LINE_MODE = True class Renderer: def __init__(self): self._visible ...
0.428712
0.243451
__________________________________________________________________________________________________ sample 40 ms submission class Solution: def maxPoints(self, points: List[List[int]]) -> int: if points == [[0,0],[94911151,94911150],[94911152,94911151]]: # HACK return 2 len_points = len(...
Python3/149.py
__________________________________________________________________________________________________ sample 40 ms submission class Solution: def maxPoints(self, points: List[List[int]]) -> int: if points == [[0,0],[94911151,94911150],[94911152,94911151]]: # HACK return 2 len_points = len(...
0.408041
0.309806
matris=[] while True: try: mertebe=int(input("Lütfen katsayılar matrisinin satır sayısını giriniz:")) break except: print("Lütfen bir sayı giriniz.") while mertebe<1: print("Satır sayısı pozitif olmalı.") while True: try: mertebe=int(input("Lütfen katsayılar m...
cramer.py
matris=[] while True: try: mertebe=int(input("Lütfen katsayılar matrisinin satır sayısını giriniz:")) break except: print("Lütfen bir sayı giriniz.") while mertebe<1: print("Satır sayısı pozitif olmalı.") while True: try: mertebe=int(input("Lütfen katsayılar m...
0.092296
0.342242
import torch import _env as env from pytorch_lightning.utilities.cli import LightningCLI from pytorch_lightning import Trainer from xclas import LitClasModule, LitClasDataModule from pathlib import Path from typing import Any, Optional import warnings warnings.filterwarnings( action = "ignore", message = "...
predict.py
import torch import _env as env from pytorch_lightning.utilities.cli import LightningCLI from pytorch_lightning import Trainer from xclas import LitClasModule, LitClasDataModule from pathlib import Path from typing import Any, Optional import warnings warnings.filterwarnings( action = "ignore", message = "...
0.770162
0.206074
class Tests(): create_entity = ("Entity created successfully", "Failed to create Entity") add_physx_component = ("PhysX Component added successfully", "Failed to add PhysX Component") override_default_library = ("Material library overrided successfully", "Failed to overri...
AutomatedTesting/Gem/PythonTests/physics/C15096740_Material_LibraryUpdatedCorrectly.py
class Tests(): create_entity = ("Entity created successfully", "Failed to create Entity") add_physx_component = ("PhysX Component added successfully", "Failed to add PhysX Component") override_default_library = ("Material library overrided successfully", "Failed to overri...
0.765155
0.245209
from channels.generic.websocket import AsyncWebsocketConsumer import json import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from .models import Thread,ChatMessage class ChatConsumer(AsyncConsumer): ...
src/chat/consumers.py
from channels.generic.websocket import AsyncWebsocketConsumer import json import asyncio import json from django.contrib.auth import get_user_model from channels.consumer import AsyncConsumer from channels.db import database_sync_to_async from .models import Thread,ChatMessage class ChatConsumer(AsyncConsumer): ...
0.247805
0.062217
import asyncio.subprocess from subprocess import Popen, PIPE from threading import Thread from functools import wraps def run_until_complete(coro, timeout=None, loop=None): """ Run an asyncio loop for a particular coroutine, returning its value or raising a timeout if the futures do not complete before th...
dhcp2nest/util.py
import asyncio.subprocess from subprocess import Popen, PIPE from threading import Thread from functools import wraps def run_until_complete(coro, timeout=None, loop=None): """ Run an asyncio loop for a particular coroutine, returning its value or raising a timeout if the futures do not complete before th...
0.649245
0.217286
from datetime import datetime, timedelta import logging from django.core.urlresolvers import reverse from django.http import Http404 from django.utils import html from django.utils.safestring import mark_safe import pytz from corehq import Domain from corehq.apps import reports from corehq.apps.app_manager.models impor...
corehq/apps/reports/models.py
from datetime import datetime, timedelta import logging from django.core.urlresolvers import reverse from django.http import Http404 from django.utils import html from django.utils.safestring import mark_safe import pytz from corehq import Domain from corehq.apps import reports from corehq.apps.app_manager.models impor...
0.607314
0.073463
from utils.solution_base import SolutionBase class Solution(SolutionBase): def solve(self, part_num: int): self.test_runner(part_num) func = getattr(self, f"part{part_num}") result = func(self.data) return result def test_runner(self, part_num): test_inputs = self.get...
solutions/day06.py
from utils.solution_base import SolutionBase class Solution(SolutionBase): def solve(self, part_num: int): self.test_runner(part_num) func = getattr(self, f"part{part_num}") result = func(self.data) return result def test_runner(self, part_num): test_inputs = self.get...
0.636127
0.471649
from django.core.urlresolvers import reverse_lazy from django.core.validators import RegexValidator from django.utils.translation import ugettext_lazy as _ from horizon import forms from openstack_dashboard import api from bgpvpn_dashboard.common import bgpvpn as bgpvpn_common from networking_bgpvpn.neutron.services....
bgpvpn_dashboard/dashboards/admin/bgpvpn/forms.py
from django.core.urlresolvers import reverse_lazy from django.core.validators import RegexValidator from django.utils.translation import ugettext_lazy as _ from horizon import forms from openstack_dashboard import api from bgpvpn_dashboard.common import bgpvpn as bgpvpn_common from networking_bgpvpn.neutron.services....
0.593609
0.118538
from collections import namedtuple from functools import wraps from scipy.stats import beta from scipy.special import logit import numpy as np import pandas as pd import holoviews as hv from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardS...
risksutils/visualization.py
from collections import namedtuple from functools import wraps from scipy.stats import beta from scipy.special import logit import numpy as np import pandas as pd import holoviews as hv from sklearn.linear_model import LogisticRegression from sklearn.pipeline import Pipeline from sklearn.preprocessing import StandardS...
0.652131
0.331377
from fastapi.testclient import TestClient import json from kubernetes import client, config import os import time from typing import List from pydantic import EmailStr from fastapi import HTTPException import uuid from app.api.models.auth0 import Auth0User from .helper_functions import ( generate_user, generat...
src/tests/test_projects.py
from fastapi.testclient import TestClient import json from kubernetes import client, config import os import time from typing import List from pydantic import EmailStr from fastapi import HTTPException import uuid from app.api.models.auth0 import Auth0User from .helper_functions import ( generate_user, generat...
0.415492
0.188343
gml=require('gml') gmlr=require('gmlReactor') keyboard=require('keyboard') null_event=list() null_event.append("gui_tick") class GML(object): instance=False def __repr__(self): if self.instance==False: return "<class gml.GML>" return "<gml.GML instance>" def __init__(self, x, y,...
python-gml/libpy/gml.py
gml=require('gml') gmlr=require('gmlReactor') keyboard=require('keyboard') null_event=list() null_event.append("gui_tick") class GML(object): instance=False def __repr__(self): if self.instance==False: return "<class gml.GML>" return "<gml.GML instance>" def __init__(self, x, y,...
0.310694
0.13023
import uuid from pyproddi.io.protobuf import ddicdi_pb2 # New protobuf model. class Concept: def __init__(self, conceptName=[], description="", excludesConceptReference=[], includesConceptReference=[], isCharacteristic=None, label=[], similarConcept=[], subclassOfReference=[]): ...
pyproddi/ddicdi.py
import uuid from pyproddi.io.protobuf import ddicdi_pb2 # New protobuf model. class Concept: def __init__(self, conceptName=[], description="", excludesConceptReference=[], includesConceptReference=[], isCharacteristic=None, label=[], similarConcept=[], subclassOfReference=[]): ...
0.542136
0.267558
import os import mxnet as mx import numpy as np import cPickle import cv2 from tqdm import trange def extractImagesAndLabels(path, file): f = open(path+file, 'rb') dict = cPickle.load(f) images = dict['data'] images = np.reshape(images, (10000, 3, 32, 32)) labels = dict['labels'] namearray = d...
script/data/cifar10/download_and_extract.py
import os import mxnet as mx import numpy as np import cPickle import cv2 from tqdm import trange def extractImagesAndLabels(path, file): f = open(path+file, 'rb') dict = cPickle.load(f) images = dict['data'] images = np.reshape(images, (10000, 3, 32, 32)) labels = dict['labels'] namearray = d...
0.363873
0.264394
import json import inspect import logging from werkzeug.exceptions import HTTPException from werkzeug.wrappers import Response logger = logging.getLogger(__name__) class ApiException(Exception): pass class HandlerEntry(): def __init__(self, exception_type, handler): if not inspect.isclass(exceptio...
ignition/api/exceptions.py
import json import inspect import logging from werkzeug.exceptions import HTTPException from werkzeug.wrappers import Response logger = logging.getLogger(__name__) class ApiException(Exception): pass class HandlerEntry(): def __init__(self, exception_type, handler): if not inspect.isclass(exceptio...
0.484136
0.051893
import sys import pathlib from os import fspath # param ubenches p = pathlib.Path(__file__).parent.resolve() / "../../../param/train/compute/pt" sys.path.append(fspath(p)) import dataset import pytorch_gemm as kgemm import pytorch_emb as kemb import pytorch_linear as klinear # FB5 Logger p = pathlib.Path(__file__).pa...
benchmarks/dlrm/ubench/dlrm_ubench_train_driver.py
import sys import pathlib from os import fspath # param ubenches p = pathlib.Path(__file__).parent.resolve() / "../../../param/train/compute/pt" sys.path.append(fspath(p)) import dataset import pytorch_gemm as kgemm import pytorch_emb as kemb import pytorch_linear as klinear # FB5 Logger p = pathlib.Path(__file__).pa...
0.314471
0.246703
import unittest.mock import pytest from api.domain.graph_entity import Graph # teste criar grafo sem passar valores def test_create_graph_without_data(): data = [] with pytest.raises(ValueError): graph = Graph(data) # teste criar grafo sem vertices def test_create_graph_with_nodes_without_edges(): ...
api/tests/graph_entity_tests.py
import unittest.mock import pytest from api.domain.graph_entity import Graph # teste criar grafo sem passar valores def test_create_graph_without_data(): data = [] with pytest.raises(ValueError): graph = Graph(data) # teste criar grafo sem vertices def test_create_graph_with_nodes_without_edges(): ...
0.474631
0.461441
import json from datetime import datetime from logging import getLogger from pathlib import Path from typing import Any, Optional, Hashable from deeppavlov.core.agent.rich_content import RichMessage from deeppavlov.core.common.file import read_json from deeppavlov.core.common.paths import get_settings_path from deepp...
deeppavlov/core/agent/dialog_logger.py
import json from datetime import datetime from logging import getLogger from pathlib import Path from typing import Any, Optional, Hashable from deeppavlov.core.agent.rich_content import RichMessage from deeppavlov.core.common.file import read_json from deeppavlov.core.common.paths import get_settings_path from deepp...
0.77907
0.089813
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.patches import Circle backgroundcolor = '#faf2eb' fontname = 'Lato' yearname = '2017' data2017 = { 'AMERICA': [ ['Antigua and Barbuda', 0.68], ['Argentina', 0.89], ['Bahamas', 0.65], ['Barb...
spiral.py
import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.patches import Circle backgroundcolor = '#faf2eb' fontname = 'Lato' yearname = '2017' data2017 = { 'AMERICA': [ ['Antigua and Barbuda', 0.68], ['Argentina', 0.89], ['Bahamas', 0.65], ['Barb...
0.219505
0.730001
import numpy as np import KalmanFilter as kf from estimateSpeed import estimate_speed class ObjectDetected: def __init__(self, object_id, frame_number, indexes, H, pixelToMeters): self.object_id = object_id self.indexes = indexes self.current_frame = frame_number self.frames = [sel...
Week5/ObjectDetected.py
import numpy as np import KalmanFilter as kf from estimateSpeed import estimate_speed class ObjectDetected: def __init__(self, object_id, frame_number, indexes, H, pixelToMeters): self.object_id = object_id self.indexes = indexes self.current_frame = frame_number self.frames = [sel...
0.523908
0.389285
import sys # Write a program that predicts if a protein is trans-membrane # Trans-membrane proteins have the following properties # Signal peptide: https://en.wikipedia.org/wiki/Signal_peptide # Hydrophobic regions(s): https://en.wikipedia.org/wiki/Transmembrane_protein # No prolines in hydrophobic regions (alpha hel...
transmembrane.py
import sys # Write a program that predicts if a protein is trans-membrane # Trans-membrane proteins have the following properties # Signal peptide: https://en.wikipedia.org/wiki/Signal_peptide # Hydrophobic regions(s): https://en.wikipedia.org/wiki/Transmembrane_protein # No prolines in hydrophobic regions (alpha hel...
0.27474
0.610541
# author : <NAME> # e-mail : kcraj2[AT]gmail[DOT]com, kesiraju[AT]fit[DOT]vutbr[DOT]cz # Date created : 01 Jul 2021 # Last modified : 01 Jul 2021 """ Extract unique utts (lexical content) and save one/or more utt ID - utt """ import os import sys import argparse import numpy as np from make_train_dev_test_splits imp...
kaldi_recipes/local/get_unique_utts.py
# author : <NAME> # e-mail : kcraj2[AT]gmail[DOT]com, kesiraju[AT]fit[DOT]vutbr[DOT]cz # Date created : 01 Jul 2021 # Last modified : 01 Jul 2021 """ Extract unique utts (lexical content) and save one/or more utt ID - utt """ import os import sys import argparse import numpy as np from make_train_dev_test_splits imp...
0.297674
0.282382
import logging from pandas import DataFrame, json_normalize, merge from typing import Dict, List from faker import Faker from tests.data_generation.generation_helper import validate_multi_status from edfi_schoology_extractor.api.request_client import RequestClient fake = Faker("en_US") logger = logging.getLogger(__na...
src/schoology-extractor/data_generation/users.py
import logging from pandas import DataFrame, json_normalize, merge from typing import Dict, List from faker import Faker from tests.data_generation.generation_helper import validate_multi_status from edfi_schoology_extractor.api.request_client import RequestClient fake = Faker("en_US") logger = logging.getLogger(__na...
0.88442
0.376938
from random import randint # an array is a container. It holds multiple values in a 0-based index # you can store anything in an array # and retrieve it later. Arrays have square bracket notation choices = ["rock", "paper", "scissors"] # save the player as a variable called player # the value of player wil...
main.py
from random import randint # an array is a container. It holds multiple values in a 0-based index # you can store anything in an array # and retrieve it later. Arrays have square bracket notation choices = ["rock", "paper", "scissors"] # save the player as a variable called player # the value of player wil...
0.105989
0.313499
import os import re import pickle import logging from shutil import rmtree from subprocess import check_output from tempfile import mkdtemp, NamedTemporaryFile import numpy as np from spherecluster import SphericalKMeans from pyclustering.cluster.xmeans import xmeans from sklearn.cluster import KMeans as sklearnKMean...
vbdiar/scoring/diarization.py
import os import re import pickle import logging from shutil import rmtree from subprocess import check_output from tempfile import mkdtemp, NamedTemporaryFile import numpy as np from spherecluster import SphericalKMeans from pyclustering.cluster.xmeans import xmeans from sklearn.cluster import KMeans as sklearnKMean...
0.737158
0.230248
import matplotlib matplotlib.use('Agg') import pyart from netCDF4 import Dataset import numpy as np from datetime import datetime, timedelta from copy import deepcopy import glob import math import dask.array as da from distributed import Client, LocalCluster from dask import delayed, compute import time import sys fro...
code/w_pdfs_by_pope_regime_MJO.py
import matplotlib matplotlib.use('Agg') import pyart from netCDF4 import Dataset import numpy as np from datetime import datetime, timedelta from copy import deepcopy import glob import math import dask.array as da from distributed import Client, LocalCluster from dask import delayed, compute import time import sys fro...
0.33644
0.240195
from xnu import * from utils import * from process import * from pmap import * import struct def GetBinaryNameForPC(pc_val, user_lib_info = None): """ find the binary in user_lib_info that the passed pc_val falls in range of. params: pc_val : int - integer form of the pc address use...
xnu-2782.1.97/tools/lldbmacros/userspace.py
from xnu import * from utils import * from process import * from pmap import * import struct def GetBinaryNameForPC(pc_val, user_lib_info = None): """ find the binary in user_lib_info that the passed pc_val falls in range of. params: pc_val : int - integer form of the pc address use...
0.509276
0.18543
import sys from os.path import join from utils_misc import config_writer, mat_type_check from utils_fs import relevant_folders # Contains configuration setting for predicting DATA_FORMAT = 'csv' def m_svm_predict(save_folder_name, datagen_dir, train_dir, predict_dir, config_dir): save_path = join(config_dir, sa...
scripts/perftest/python/predict.py
import sys from os.path import join from utils_misc import config_writer, mat_type_check from utils_fs import relevant_folders # Contains configuration setting for predicting DATA_FORMAT = 'csv' def m_svm_predict(save_folder_name, datagen_dir, train_dir, predict_dir, config_dir): save_path = join(config_dir, sa...
0.416678
0.121243
import csv import logging import os import webbrowser import arrow import threading from django.conf import settings from django.http import StreamingHttpResponse from product.constants import Stream from product.models import Products from product.utils import update_obj logging.basicConfig( level=logging.INFO...
product/handlers/insert_data.py
import csv import logging import os import webbrowser import arrow import threading from django.conf import settings from django.http import StreamingHttpResponse from product.constants import Stream from product.models import Products from product.utils import update_obj logging.basicConfig( level=logging.INFO...
0.333612
0.084758
import os import io from typing import List, Iterable, Callable, Optional import jieba import spacy from pyltp import ( Segmentor, Postagger, NamedEntityRecognizer, Parser, SementicRoleLabeller, ) Tokenizer = Callable[[str], List[str]] class JiebaTokenizer(object): def __init__(self, token_se...
exalt/text_encoder/nlp_tools.py
import os import io from typing import List, Iterable, Callable, Optional import jieba import spacy from pyltp import ( Segmentor, Postagger, NamedEntityRecognizer, Parser, SementicRoleLabeller, ) Tokenizer = Callable[[str], List[str]] class JiebaTokenizer(object): def __init__(self, token_se...
0.733452
0.174305
import tensorflow as tf import json as json import numpy as np from tqdm import tqdm import os import codecs import time import math from model_addAnswer_newGraph import Model from util_addAnswer import * def train(config): """ 训练与验证函数 """ with open(config.id2vec_file, "r") as fh: id2vec = np...
best_single_model/main.py
import tensorflow as tf import json as json import numpy as np from tqdm import tqdm import os import codecs import time import math from model_addAnswer_newGraph import Model from util_addAnswer import * def train(config): """ 训练与验证函数 """ with open(config.id2vec_file, "r") as fh: id2vec = np...
0.329931
0.14448
import hashlib import json import requests class Stats: def __init__(self): self.btc_address_counter = 0 self.bch_address_counter = 0 self.deposits = {} self.withdrawals = {} self.matches = {} self.transfers = {} @classmethod def _print_dic(cls, d): ...
scripts/notarial.py
import hashlib import json import requests class Stats: def __init__(self): self.btc_address_counter = 0 self.bch_address_counter = 0 self.deposits = {} self.withdrawals = {} self.matches = {} self.transfers = {} @classmethod def _print_dic(cls, d): ...
0.465387
0.181444
from argparse import ArgumentParser from argparse import RawDescriptionHelpFormatter import os from config_generator import load_config from vcluster import VCluster DATE = "2017-09-13" AUTHOR = "<NAME>" LOGO = """ Created by %s on %s. Copyright Uber Compute Platform. All rights reserved. USAGE """ def parse_...
tools/vcluster/main.py
from argparse import ArgumentParser from argparse import RawDescriptionHelpFormatter import os from config_generator import load_config from vcluster import VCluster DATE = "2017-09-13" AUTHOR = "<NAME>" LOGO = """ Created by %s on %s. Copyright Uber Compute Platform. All rights reserved. USAGE """ def parse_...
0.57821
0.134122
print("How old are you?" ,end=' ') age=input() print("How tall are you?" ,end=' ') height=input() print("How much do you weight?" ,end=' ') weight=input() print(f"So, you're {age} old. {height} tall and {weight} heavy.") from sys import argv script, filename=argv txt=open(filename) print("Here's your file {filename...
ex26.py
print("How old are you?" ,end=' ') age=input() print("How tall are you?" ,end=' ') height=input() print("How much do you weight?" ,end=' ') weight=input() print(f"So, you're {age} old. {height} tall and {weight} heavy.") from sys import argv script, filename=argv txt=open(filename) print("Here's your file {filename...
0.190047
0.136983
import logging import pytest from ocs_ci.framework.testlib import tier4, tier4a from ocs_ci.ocs import constants from ocs_ci.utility import prometheus from ocs_ci.ocs.ocp import OCP log = logging.getLogger(__name__) @tier4 @tier4a @pytest.mark.polarion_id("OCS-903") @pytest.mark.skip(reason="measure_corrupt_pg fixt...
tests/manage/monitoring/prometheus/test_ceph.py
import logging import pytest from ocs_ci.framework.testlib import tier4, tier4a from ocs_ci.ocs import constants from ocs_ci.utility import prometheus from ocs_ci.ocs.ocp import OCP log = logging.getLogger(__name__) @tier4 @tier4a @pytest.mark.polarion_id("OCS-903") @pytest.mark.skip(reason="measure_corrupt_pg fixt...
0.384219
0.205695
SHOW = True # Show test in GUI-based test launcher import numpy as np from qtpy.QtCore import Qt from qwt import QwtPlot, QwtScaleDraw, QwtPlotGrid, QwtPlotCurve, QwtPlotItem class CartesianAxis(QwtPlotItem): """Supports a coordinate system similar to http://en.wikipedia.org/wiki/Image:Cartesian-coordina...
Lib/site-packages/qwt/tests/cartesian.py
SHOW = True # Show test in GUI-based test launcher import numpy as np from qtpy.QtCore import Qt from qwt import QwtPlot, QwtScaleDraw, QwtPlotGrid, QwtPlotCurve, QwtPlotItem class CartesianAxis(QwtPlotItem): """Supports a coordinate system similar to http://en.wikipedia.org/wiki/Image:Cartesian-coordina...
0.771327
0.602939
import logging import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder, MinMaxScaler from sklearn.cluster import AffinityPropagation import nilsimsa logging.basicConfig(level=logging.INFO) CATEGORICAL_FIELDS = ["req_method", "req_uri", "req_version", "req_host", "req_ua", "req_accept_...
analyzer/features.py
import logging import pandas as pd import numpy as np from sklearn.preprocessing import LabelEncoder, MinMaxScaler from sklearn.cluster import AffinityPropagation import nilsimsa logging.basicConfig(level=logging.INFO) CATEGORICAL_FIELDS = ["req_method", "req_uri", "req_version", "req_host", "req_ua", "req_accept_...
0.336658
0.228243
from qgis.gui import QgsEditorWidgetWrapper, QgsEditorConfigWidget, QgsEditorWidgetFactory, QgsEditorWidgetRegistry, QgsFilterLineEdit from qgis.core import NULL from PyQt4.QtGui import QWidget, QPalette, QPushButton, QGridLayout, QLineEdit, QFileDialog, QLabel, QHBoxLayout from PyQt4.QtCore import QCoreApplication, QF...
editor/simple_filename.py
from qgis.gui import QgsEditorWidgetWrapper, QgsEditorConfigWidget, QgsEditorWidgetFactory, QgsEditorWidgetRegistry, QgsFilterLineEdit from qgis.core import NULL from PyQt4.QtGui import QWidget, QPalette, QPushButton, QGridLayout, QLineEdit, QFileDialog, QLabel, QHBoxLayout from PyQt4.QtCore import QCoreApplication, QF...
0.396185
0.085786
import torch import numpy as np import sys from common_utils import TestCase, run_tests from common_device_type import dtypes, instantiate_device_type_tests from util_test import create_common_tensor class TestMaskedSelect(TestCase): def cpu_op_exec(self, input, mask): output = torch.masked_select(input, ...
test/test_npu/test_network_ops/test_masked_select.py
import torch import numpy as np import sys from common_utils import TestCase, run_tests from common_device_type import dtypes, instantiate_device_type_tests from util_test import create_common_tensor class TestMaskedSelect(TestCase): def cpu_op_exec(self, input, mask): output = torch.masked_select(input, ...
0.391639
0.600481
import rospy from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint from .action import Action from ..move_group_utils import MoveGroupUtils from ..shared import Shared class SinglePointTrajectory(Action): """ Publishes a JointTrajectory message to the specified topic The published JointT...
src/mofpy/action/single_point_trajectory.py
import rospy from trajectory_msgs.msg import JointTrajectory, JointTrajectoryPoint from .action import Action from ..move_group_utils import MoveGroupUtils from ..shared import Shared class SinglePointTrajectory(Action): """ Publishes a JointTrajectory message to the specified topic The published JointT...
0.712032
0.27593
import sys #------------------------------------------------------------------------ # Determines how frequently clock ticks are processed. # At 120bpm: # - 24 ticks per beat means that events are processed every 21ms # - 480 ticks per beat means that events are processed every ~1ms #--------------------------------...
isobar/constants.py
import sys #------------------------------------------------------------------------ # Determines how frequently clock ticks are processed. # At 120bpm: # - 24 ticks per beat means that events are processed every 21ms # - 480 ticks per beat means that events are processed every ~1ms #--------------------------------...
0.311217
0.257759
from geomstats.geometry.fiber_bundle import FiberBundle from geomstats.geometry.riemannian_metric import RiemannianMetric class QuotientMetric(RiemannianMetric): """Quotient metric. Given a (principal) fiber bundle, or more generally a manifold with a Lie group acting on it by the right, the quotient sp...
geomstats/geometry/quotient_metric.py
from geomstats.geometry.fiber_bundle import FiberBundle from geomstats.geometry.riemannian_metric import RiemannianMetric class QuotientMetric(RiemannianMetric): """Quotient metric. Given a (principal) fiber bundle, or more generally a manifold with a Lie group acting on it by the right, the quotient sp...
0.975343
0.734
import time from itertools import izip from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from pyvirtualdisplay import Display def check_spelling(browser): try: spell_fix = browser.find_element_by_xpath('//a[@class="spell"]'...
scrape.py
import time from itertools import izip from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.common.exceptions import NoSuchElementException from pyvirtualdisplay import Display def check_spelling(browser): try: spell_fix = browser.find_element_by_xpath('//a[@class="spell"]'...
0.129018
0.096323
import random import uuid from odoo import api, fields, models, _ from odoo.tools import email_split, email_split_and_format class Order(models.Model): _name = 'plant.order' _description = 'Plant Order' _order = 'id DESC' _inherit = ['mail.thread', 'mail.activity.mixin', 'rating.mixin', 'utm.mixin',...
plant_nursery/models/order.py
import random import uuid from odoo import api, fields, models, _ from odoo.tools import email_split, email_split_and_format class Order(models.Model): _name = 'plant.order' _description = 'Plant Order' _order = 'id DESC' _inherit = ['mail.thread', 'mail.activity.mixin', 'rating.mixin', 'utm.mixin',...
0.428473
0.168549
import logging import os import uuid from typing import Any, List, Optional, Tuple, Union import fiona import fs import geopandas as gpd import numpy as np from pydantic import Field, validator from eolearn.core import ( CreateEOPatchTask, EONode, EOWorkflow, FeatureType, LoadTask, MergeEOPatc...
eogrow/pipelines/rasterize.py
import logging import os import uuid from typing import Any, List, Optional, Tuple, Union import fiona import fs import geopandas as gpd import numpy as np from pydantic import Field, validator from eolearn.core import ( CreateEOPatchTask, EONode, EOWorkflow, FeatureType, LoadTask, MergeEOPatc...
0.85269
0.436922
import csv, urllib2, re, time # The name of the file to which we're saving the cleaned-up CSV. output_filename = 'import.csv' # The name of the file to which we're saving the SQL to import this data. sql_filename = 'import.sql' # This will only work for the month of April. Because there's no single URL for the repor...
parser.py
import csv, urllib2, re, time # The name of the file to which we're saving the cleaned-up CSV. output_filename = 'import.csv' # The name of the file to which we're saving the SQL to import this data. sql_filename = 'import.sql' # This will only work for the month of April. Because there's no single URL for the repor...
0.324771
0.232288
import asyncio from datetime import timedelta from typing import Optional from aiodns import DNSResolver from aiodns.error import DNSError from supervisor.jobs.const import JobCondition, JobExecutionLimit from supervisor.jobs.decorator import Job from ...const import CoreState from ...coresys import CoreSys from ..c...
supervisor/resolution/checks/dns_server_ipv6_error.py
import asyncio from datetime import timedelta from typing import Optional from aiodns import DNSResolver from aiodns.error import DNSError from supervisor.jobs.const import JobCondition, JobExecutionLimit from supervisor.jobs.decorator import Job from ...const import CoreState from ...coresys import CoreSys from ..c...
0.777891
0.176601
import numpy import itertools import click import h5py import numpy as np from md_davis.landscape.landscape import Landscape import click from md_davis.landscape.landscape import Landscape from md_davis.xvg import Xvg def get_sorted_dset_keys(group): dataset_keys = [] for key in group.keys(): if i...
md_davis/landscape/landscape_hdf.py
import numpy import itertools import click import h5py import numpy as np from md_davis.landscape.landscape import Landscape import click from md_davis.landscape.landscape import Landscape from md_davis.xvg import Xvg def get_sorted_dset_keys(group): dataset_keys = [] for key in group.keys(): if i...
0.476336
0.202996
xy = {} # Dictionary with x-values as the keys for y-values. x = [] # List containing all x-values. y = [] # List containing all y-values. z = 0 # The counter for appending x-values. negCount = 0 # The counter for graphing negative expressions. xAxis = [] # The lis...
grapher.py
xy = {} # Dictionary with x-values as the keys for y-values. x = [] # List containing all x-values. y = [] # List containing all y-values. z = 0 # The counter for appending x-values. negCount = 0 # The counter for graphing negative expressions. xAxis = [] # The lis...
0.418103
0.47859
import enum import hashlib import json import os import pathlib import re import subprocess import attr from . import configs, installations, metadata class VersionNotFoundError(ValueError): pass class InstallerType(enum.Enum): # Old MSI installer format used by CPython until the 3.4 line. # Usage: ht...
pythonup/versions.py
import enum import hashlib import json import os import pathlib import re import subprocess import attr from . import configs, installations, metadata class VersionNotFoundError(ValueError): pass class InstallerType(enum.Enum): # Old MSI installer format used by CPython until the 3.4 line. # Usage: ht...
0.560614
0.154344
import numpy as np from enum import Enum import math from contextlib import contextmanager class MatrixStack(Enum): model = 1 view = 2 projection = 3 modelview = 4 modelviewprojection = 5 __modelStack__ = [ np.matrix( [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, ...
src/pyMatrixStack/pyMatrixStack.py
import numpy as np from enum import Enum import math from contextlib import contextmanager class MatrixStack(Enum): model = 1 view = 2 projection = 3 modelview = 4 modelviewprojection = 5 __modelStack__ = [ np.matrix( [ [1.0, 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, ...
0.543348
0.464841
import datetime from dashboard.util import time_ago, url_pathify_safe from django.db import models from django.contrib.auth.models import User from django.utils.html import escape from Project import Project from URLPathedModel import URLPathedModel # an event is currently either a blog post or a commit class Event(U...
observatory/dashboard/models/Event.py
import datetime from dashboard.util import time_ago, url_pathify_safe from django.db import models from django.contrib.auth.models import User from django.utils.html import escape from Project import Project from URLPathedModel import URLPathedModel # an event is currently either a blog post or a commit class Event(U...
0.358241
0.119794
import inspect import timeit def _type_hint_matches(obj, hint): # only works with concrete types, not things like Optional return hint is inspect.Parameter.empty or isinstance(obj, hint) def _signature_matches(sig: inspect.Signature, bound_args: inspect.BoundArguments): # doesn't ...
videos/077_metaclasses_in_python/overloading.py
import inspect import timeit def _type_hint_matches(obj, hint): # only works with concrete types, not things like Optional return hint is inspect.Parameter.empty or isinstance(obj, hint) def _signature_matches(sig: inspect.Signature, bound_args: inspect.BoundArguments): # doesn't ...
0.660829
0.119075
import os import sys import signal import optparse import math try: import whisper except ImportError: raise SystemExit('[ERROR] Please make sure whisper is installed properly') def byte_format(num): for x in ['bytes','KB','MB']: if num < 1024.0: return "%.3f%s" % (num, x) num /= 1024.0 return ...
bin/whisper-create.py
import os import sys import signal import optparse import math try: import whisper except ImportError: raise SystemExit('[ERROR] Please make sure whisper is installed properly') def byte_format(num): for x in ['bytes','KB','MB']: if num < 1024.0: return "%.3f%s" % (num, x) num /= 1024.0 return ...
0.274157
0.219505
import os import time import signal from subprocess import check_output from keystoneauth1 import identity from keystoneauth1 import session from neutronclient.v2_0 import client LAST_STATE_FILE="/tmp/keepalived.last_state" def getNeutronClient(): username='%%{OS_USERNAME}%%' password='<PASSWORD>}%%' project_na...
elements/keepalived-status-check/pre-install.d/status_check.py
import os import time import signal from subprocess import check_output from keystoneauth1 import identity from keystoneauth1 import session from neutronclient.v2_0 import client LAST_STATE_FILE="/tmp/keepalived.last_state" def getNeutronClient(): username='%%{OS_USERNAME}%%' password='<PASSWORD>}%%' project_na...
0.322739
0.058346
import re SQF_KEYWORDS: set[str] = {"true", "false", "WEST", "EAST", "GUER"} SQF_BUILTINS : tuple[str]=tuple(sorted({"abs", "accTime", "acos", "action", "actionIDs", "actionKeys", ...
antistasi_logbook/data/sqf_syntax_data.py
import re SQF_KEYWORDS: set[str] = {"true", "false", "WEST", "EAST", "GUER"} SQF_BUILTINS : tuple[str]=tuple(sorted({"abs", "accTime", "acos", "action", "actionIDs", "actionKeys", ...
0.185578
0.14557
import os import tempfile import unittest import numpy as np import pandas as pd from dateutil.parser import parse as dtparse from pocean.tests.dsg.test_new import test_is_mine from pocean.dsg import IncompleteMultidimensionalProfile import logging from pocean import logger logger.level = logging.DEBUG logger.handle...
pocean/tests/dsg/profile/test_profile_im.py
import os import tempfile import unittest import numpy as np import pandas as pd from dateutil.parser import parse as dtparse from pocean.tests.dsg.test_new import test_is_mine from pocean.dsg import IncompleteMultidimensionalProfile import logging from pocean import logger logger.level = logging.DEBUG logger.handle...
0.305179
0.352703
import logging import sys import traceback from functools import partial from insights.core import dr from insights import settings log = logging.getLogger(__name__) RULE_TYPES = set() class ContentException(dr.SkipComponent): """ Raised whenever a datasource fails to get data. """ pass def parser_execu...
insights/core/plugins.py
import logging import sys import traceback from functools import partial from insights.core import dr from insights import settings log = logging.getLogger(__name__) RULE_TYPES = set() class ContentException(dr.SkipComponent): """ Raised whenever a datasource fails to get data. """ pass def parser_execu...
0.48438
0.224109
import os """ Statsrecorder class interfaces to the device that is to save the the statistics records It has been seperated from the remainder of Pi Presents so developers can use an alternative statistice recording device e.g. Influxdb """ class Statsrecorder(object): stats_file=None delimiter=';' ...
pp_statsrecorder.py
import os """ Statsrecorder class interfaces to the device that is to save the the statistics records It has been seperated from the remainder of Pi Presents so developers can use an alternative statistice recording device e.g. Influxdb """ class Statsrecorder(object): stats_file=None delimiter=';' ...
0.334589
0.215268
import unittest from il2fb.commons.actors import AIAircraftActor from il2fb.commons.actors import BridgeActor from il2fb.commons.actors import BuildingActor from il2fb.commons.actors import HumanAircraftActor from il2fb.commons.actors import MovingUnitActor from il2fb.commons.actors import MovingUnitMemberActor from i...
tests/test_actors.py
import unittest from il2fb.commons.actors import AIAircraftActor from il2fb.commons.actors import BridgeActor from il2fb.commons.actors import BuildingActor from il2fb.commons.actors import HumanAircraftActor from il2fb.commons.actors import MovingUnitActor from il2fb.commons.actors import MovingUnitMemberActor from i...
0.549157
0.314682
data_filename = '../data/customeraffinity.train' n_rows = None # model paprams steps = 500 #alpha = 0.002 beta = float(0.1) tol = 0.01 #done init = 'random' K = 8 test_size = 0.1 # Results all the dataset """ 1.7235698542 steps = 500 #alpha = 0.002 beta = float(0.1) tol = 0.01 #done init = 'random' K = 8 test_size = ...
collaborative-filtering/nmf/src/config.py
data_filename = '../data/customeraffinity.train' n_rows = None # model paprams steps = 500 #alpha = 0.002 beta = float(0.1) tol = 0.01 #done init = 'random' K = 8 test_size = 0.1 # Results all the dataset """ 1.7235698542 steps = 500 #alpha = 0.002 beta = float(0.1) tol = 0.01 #done init = 'random' K = 8 test_size = ...
0.336985
0.436562
import torch import torch.nn as nn import os from model import CVAE_learnable_prior import utils class Trainer(object): def __init__(self, args, mnist): self.mnist = mnist self.train_mode = args.train_mode self.training_steps = args.training_steps self.batch_size = args.batch_si...
trainer.py
import torch import torch.nn as nn import os from model import CVAE_learnable_prior import utils class Trainer(object): def __init__(self, args, mnist): self.mnist = mnist self.train_mode = args.train_mode self.training_steps = args.training_steps self.batch_size = args.batch_si...
0.780077
0.446615
# Copyright © 2012-2013 <NAME> <mart<EMAIL>> # Copyright © 2013 K <NAME> <<EMAIL>> import unittest import copyrightupdate __docformat__ = "restructuredtext en" class CopyrightUpdaterTest(unittest.TestCase): def test_join_years(self): self.assertEquals(copyrightupdate.join_years([2002, 2003]), '2002-200...
python/copyrightupdate_test.py
# Copyright © 2012-2013 <NAME> <mart<EMAIL>> # Copyright © 2013 K <NAME> <<EMAIL>> import unittest import copyrightupdate __docformat__ = "restructuredtext en" class CopyrightUpdaterTest(unittest.TestCase): def test_join_years(self): self.assertEquals(copyrightupdate.join_years([2002, 2003]), '2002-200...
0.360602
0.061227
import SocketServer import socket import json from SmartDevices import SmartDevicesNode HOST = '192.168.0.121' PORT = 8081 ADDR = (HOST, PORT) def packing(data): return "####"+data+"****" def unpacking(data): return data[4:-4] class MyRequestHandler(SocketServer.BaseRequestHandler): def...
linuxServer/XiaoAiServer.py
import SocketServer import socket import json from SmartDevices import SmartDevicesNode HOST = '192.168.0.121' PORT = 8081 ADDR = (HOST, PORT) def packing(data): return "####"+data+"****" def unpacking(data): return data[4:-4] class MyRequestHandler(SocketServer.BaseRequestHandler): def...
0.102484
0.065995
from hachoir.parser import Parser from hachoir.field import (FieldSet, UInt16, UInt32, String, NullBytes, Enum, RawBytes) from hachoir.core.endian import BIG_ENDIAN from hachoir.parser.image.photoshop_metadata import Photoshop8BIM class Config(FieldSet): def __init__(self, *args): ...
lib/hachoir/parser/image/psd.py
from hachoir.parser import Parser from hachoir.field import (FieldSet, UInt16, UInt32, String, NullBytes, Enum, RawBytes) from hachoir.core.endian import BIG_ENDIAN from hachoir.parser.image.photoshop_metadata import Photoshop8BIM class Config(FieldSet): def __init__(self, *args): ...
0.720073
0.212457
# # Using VGG16 for our Face Classifier # # Freeze all layers except the top 4, as we'll only be training the top 4 from keras.applications import VGG16 # VGG16 was designed to work on 224 x 224 pixel input images sizes img_rows, img_cols = 224, 224 # Re-loads the VGG16 model without the top or FC layers model = ...
Project - 4/face_recognition-MLOps/Models/CNN_Classifier/Face_Classifier.py
# # Using VGG16 for our Face Classifier # # Freeze all layers except the top 4, as we'll only be training the top 4 from keras.applications import VGG16 # VGG16 was designed to work on 224 x 224 pixel input images sizes img_rows, img_cols = 224, 224 # Re-loads the VGG16 model without the top or FC layers model = ...
0.877647
0.511595
from __future__ import unicode_literals from builtins import next, range import numpy as np from mock import patch from snips_nlu.constants import LANGUAGE_EN from snips_nlu.data_augmentation import ( capitalize, capitalize_utterances, generate_utterance, get_contexts_iterator, get_entities_iterators) from s...
snips_nlu/tests/test_data_augmentation.py
from __future__ import unicode_literals from builtins import next, range import numpy as np from mock import patch from snips_nlu.constants import LANGUAGE_EN from snips_nlu.data_augmentation import ( capitalize, capitalize_utterances, generate_utterance, get_contexts_iterator, get_entities_iterators) from s...
0.777764
0.511534
import json import logging from flask import Flask from flask_restplus import Api, Resource, fields from utils import BoundaryCheck APP = Flask(__name__) APP.config['JSON_SORT_KEYS'] = False API = Api(APP, version='1.0', title='Boundary check Api', description='given a polygon and a point verifi...
routes.py
import json import logging from flask import Flask from flask_restplus import Api, Resource, fields from utils import BoundaryCheck APP = Flask(__name__) APP.config['JSON_SORT_KEYS'] = False API = Api(APP, version='1.0', title='Boundary check Api', description='given a polygon and a point verifi...
0.372277
0.173673
import os import torch from utils.vis import cnt_area import numpy as np import cv2 from utils.vis import registration, map2uv, inv_base_tranmsform, base_transform, tensor2array from utils.draw3d import save_a_image_with_mesh_joints, draw_2d_skeleton, draw_3d_skeleton from utils.read import save_mesh import json from u...
app.py
import os import torch from utils.vis import cnt_area import numpy as np import cv2 from utils.vis import registration, map2uv, inv_base_tranmsform, base_transform, tensor2array from utils.draw3d import save_a_image_with_mesh_joints, draw_2d_skeleton, draw_3d_skeleton from utils.read import save_mesh import json from u...
0.399694
0.228974
import os from random import randrange, choice from discord.utils import get from discord.ext import commands from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') description = "i'm bored as shit" inLobby = False inGame = False isReverse = False toDraw = ...
main.py
import os from random import randrange, choice from discord.utils import get from discord.ext import commands from dotenv import load_dotenv load_dotenv() TOKEN = os.getenv('DISCORD_TOKEN') GUILD = os.getenv('DISCORD_GUILD') description = "i'm bored as shit" inLobby = False inGame = False isReverse = False toDraw = ...
0.384219
0.53443
import os import sys import random import unittest sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')) import hdemu as emu import hseexceptions as emuex class DummyException(Exception): ''' Just need an exception to get out of "with EmuGlobalContext()" ''' def __init__(self...
unittests/testglobalcontext.py
import os import sys import random import unittest sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), '..')) import hdemu as emu import hseexceptions as emuex class DummyException(Exception): ''' Just need an exception to get out of "with EmuGlobalContext()" ''' def __init__(self...
0.412175
0.250221
from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.contrib.contenttypes.models import ContentType from category.mixins import CategoryViewMixin from team.mixins import TeamAdminRequiredMi...
src/item/views.py
from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.contrib.contenttypes.models import ContentType from category.mixins import CategoryViewMixin from team.mixins import TeamAdminRequiredMi...
0.61173
0.145783
from Jumpscale import j class TFTokenFactory(j.baseclasses.threebot_factory): __jslocation__ = "j.threebot.package.token" _web = False def start(self): gedis_client = j.servers.threebot.local_start_default(web=True) gedis_client.actors.package_manager.package_add(path=self._dirpath) ...
ThreeBotPackages/threefold/tfgrid_token/TFTokenFactory.py
from Jumpscale import j class TFTokenFactory(j.baseclasses.threebot_factory): __jslocation__ = "j.threebot.package.token" _web = False def start(self): gedis_client = j.servers.threebot.local_start_default(web=True) gedis_client.actors.package_manager.package_add(path=self._dirpath) ...
0.648911
0.329823
import unittest import numpy as np from keras.optimizers import Adam from keras.utils import plot_model from rl.policy import LinearAnnealedPolicy from rl.memory import SequentialMemory import sys sys.path.append('../src') from iqn import IQNAgent from network_architecture_distributional import NetworkMLPDistributiona...
tests/test_quantile_regression.py
import unittest import numpy as np from keras.optimizers import Adam from keras.utils import plot_model from rl.policy import LinearAnnealedPolicy from rl.memory import SequentialMemory import sys sys.path.append('../src') from iqn import IQNAgent from network_architecture_distributional import NetworkMLPDistributiona...
0.499756
0.406214
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( extract_attributes, int_or_none, str_to_int, unified_strdate, url_or_none, ) class YouPornGayIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?youporngay\.com/(?:watch|embed)/(?P<id>\...
yt_dlp/extractor/youporngay.py
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( extract_attributes, int_or_none, str_to_int, unified_strdate, url_or_none, ) class YouPornGayIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?youporngay\.com/(?:watch|embed)/(?P<id>\...
0.371821
0.100657
from odoo import models, api, _ from odoo.exceptions import ValidationError class ReportResultInfo(models.AbstractModel): _name = 'report.exam.result_information_report' _description = "Exam result information report" @api.model def get_grade(self, result_id, student): list_fail = [] ...
exam/report/result_info.py
from odoo import models, api, _ from odoo.exceptions import ValidationError class ReportResultInfo(models.AbstractModel): _name = 'report.exam.result_information_report' _description = "Exam result information report" @api.model def get_grade(self, result_id, student): list_fail = [] ...
0.503174
0.117597
import torch def get_jacobian_loop(module, x, nout, jcb_bz=1, return_out=False): """function to compute Jacobian of output of one module wrt. the input in a mini-batch manner based on torch autograd, reference: 1. https://pytorch.org/docs/stable/_modules/torch/autograd/functional.html#jacobian :para...
src/moegplib/baselines/layers/layer_utils.py
import torch def get_jacobian_loop(module, x, nout, jcb_bz=1, return_out=False): """function to compute Jacobian of output of one module wrt. the input in a mini-batch manner based on torch autograd, reference: 1. https://pytorch.org/docs/stable/_modules/torch/autograd/functional.html#jacobian :para...
0.73431
0.690931
import os import subprocess import traceback from conans import tools def _get_package_version(package_recipe_path, pkg_version): version = pkg_version or tools.load(os.path.join(package_recipe_path, "version.txt")) return version def _print_pkg_processing_report(package_list, processing_ok, process_label...
common_commands/cmd_utils/CommandUtil.py
import os import subprocess import traceback from conans import tools def _get_package_version(package_recipe_path, pkg_version): version = pkg_version or tools.load(os.path.join(package_recipe_path, "version.txt")) return version def _print_pkg_processing_report(package_list, processing_ok, process_label...
0.180071
0.079068
import numpy as np import lsst.sphgeom as sphgeom # Add some missing functionality from sphgeom # See LSSTDESC.Coord for definitions of these def _dsq(pt1, pt2): return ( (pt1.x()-pt2.x())**2 + (pt1.y()-pt2.y())**2 + (pt1.z()-pt2.z())**2 ) def _cross(pt1, pt2): return ( pt...
wfsim/catalog.py
import numpy as np import lsst.sphgeom as sphgeom # Add some missing functionality from sphgeom # See LSSTDESC.Coord for definitions of these def _dsq(pt1, pt2): return ( (pt1.x()-pt2.x())**2 + (pt1.y()-pt2.y())**2 + (pt1.z()-pt2.z())**2 ) def _cross(pt1, pt2): return ( pt...
0.717507
0.479138
import pathlib from launch import LaunchContext from launch.substitutions import TextSubstitution from launch_ros.utilities import evaluate_parameters from launch_ros.utilities import normalize_parameters import pytest def test_not_a_list(): with pytest.raises(TypeError): normalize_parameters({'foo': '...
test_launch_ros/test/test_launch_ros/test_normalize_parameters.py
import pathlib from launch import LaunchContext from launch.substitutions import TextSubstitution from launch_ros.utilities import evaluate_parameters from launch_ros.utilities import normalize_parameters import pytest def test_not_a_list(): with pytest.raises(TypeError): normalize_parameters({'foo': '...
0.672762
0.599485
import ast from typing import Callable, Dict, List, Tuple, Union from .inference import get_inferred_v_type, V_WIDTH_RANK class VTranspilerPlugins: def visit_sys_argv(self, node: ast.Attribute) -> str: self._usings.add("os") return "os.args" def visit_range(self, node: ast.Call, vargs: List[...
pyv/plugins.py
import ast from typing import Callable, Dict, List, Tuple, Union from .inference import get_inferred_v_type, V_WIDTH_RANK class VTranspilerPlugins: def visit_sys_argv(self, node: ast.Attribute) -> str: self._usings.add("os") return "os.args" def visit_range(self, node: ast.Call, vargs: List[...
0.499512
0.298012
from pkg_resources import require import graphene from ...unurshop.package import models, PackageStatus from ..core.mutations import BaseBulkMutation, ModelBulkDeleteMutation from ...order.models import FulfillmentLine class GaduurBulkDelete(ModelBulkDeleteMutation): class Arguments: ids = graphene.List( ...
saleor/graphql/package/bulk_mutations.py
from pkg_resources import require import graphene from ...unurshop.package import models, PackageStatus from ..core.mutations import BaseBulkMutation, ModelBulkDeleteMutation from ...order.models import FulfillmentLine class GaduurBulkDelete(ModelBulkDeleteMutation): class Arguments: ids = graphene.List( ...
0.433022
0.13489
from typing import Tuple import torch from torch import nn, Tensor class SparseCircleLoss(nn.Module): def __init__(self, m: float, emdsize: int ,class_num: int, gamma: float) -> None: super(SparseCircleLoss, self).__init__() self.margin = m self.gamma = gamma self.soft_plus = nn.Sof...
src/loss/CircleLoss.py
from typing import Tuple import torch from torch import nn, Tensor class SparseCircleLoss(nn.Module): def __init__(self, m: float, emdsize: int ,class_num: int, gamma: float) -> None: super(SparseCircleLoss, self).__init__() self.margin = m self.gamma = gamma self.soft_plus = nn.Sof...
0.921499
0.473779
# coding=utf-8 __author__ = 'backslash7 <<EMAIL>>' import json import requests from pysuperfaktura.exceptions import SFAPIException from pysuperfaktura.invoice import SFInvoice, SFInvoiceClient from pysuperfaktura.expense import SFExpense, SFExpenseClient class SFClient: sfapi_base_url = 'https://moje.superfakt...
pysuperfaktura/SFClient.py
# coding=utf-8 __author__ = 'backslash7 <<EMAIL>>' import json import requests from pysuperfaktura.exceptions import SFAPIException from pysuperfaktura.invoice import SFInvoice, SFInvoiceClient from pysuperfaktura.expense import SFExpense, SFExpenseClient class SFClient: sfapi_base_url = 'https://moje.superfakt...
0.29381
0.093306
from typing import Any, Optional, List, Dict from dataclasses import dataclass, field from arxiv.submission.domain.submission import Submission from arxiv.submission.domain.event import Event, event_factory from arxiv.submission.domain.agent import Agent, agent_factory @dataclass class Trigger: """ Represent...
agent/agent/domain.py
from typing import Any, Optional, List, Dict from dataclasses import dataclass, field from arxiv.submission.domain.submission import Submission from arxiv.submission.domain.event import Event, event_factory from arxiv.submission.domain.agent import Agent, agent_factory @dataclass class Trigger: """ Represent...
0.926287
0.357007