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
title = 'methoxy decomposition to H + CH2O' description = '' frequencyScaleFactor = 1.0 """ This example illustrates how to manually set up an Arkane input file for a small P-dep reaction system [using only the RRHO assumption, and without tunneling, although this can be easily implemented]. Such a calculation is desi...
arkane/data/methoxy.py
title = 'methoxy decomposition to H + CH2O' description = '' frequencyScaleFactor = 1.0 """ This example illustrates how to manually set up an Arkane input file for a small P-dep reaction system [using only the RRHO assumption, and without tunneling, although this can be easily implemented]. Such a calculation is desi...
0.828627
0.529081
__author__ = '<NAME>' import tweepy import pymongo from pymongo import MongoClient import json import logging logging.basicConfig( filename='emovix_twitter_hashtags.log', level=logging.WARNING, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%d-%m-%y %H:%M') # Configuration pa...
emovix_twitter_hashtags.py
__author__ = '<NAME>' import tweepy import pymongo from pymongo import MongoClient import json import logging logging.basicConfig( filename='emovix_twitter_hashtags.log', level=logging.WARNING, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s', datefmt='%d-%m-%y %H:%M') # Configuration pa...
0.398875
0.154855
load("//ros:utils.bzl", "get_stem") load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc:defs.bzl", "cc_library") load("@rules_python//python:defs.bzl", "py_library") RosInterfaceInfo = provider( "Provides info for interface code generation.", fields = [ "info", "deps", ], ) _...
ros/interfaces.bzl
load("//ros:utils.bzl", "get_stem") load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_cc//cc:defs.bzl", "cc_library") load("@rules_python//python:defs.bzl", "py_library") RosInterfaceInfo = provider( "Provides info for interface code generation.", fields = [ "info", "deps", ], ) _...
0.336985
0.134861
from django.contrib.auth.models import User, Group from rest_framework import serializers from .models import * class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'groups'] # Register Serializer class RegisterSer...
edukasi/serializers.py
from django.contrib.auth.models import User, Group from rest_framework import serializers from .models import * class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['url', 'username', 'email', 'groups'] # Register Serializer class RegisterSer...
0.410166
0.120905
from copy import deepcopy from functools import lru_cache s1 = {'a', 'b', 'c'} s2 = frozenset('abc') # Hashable as long as all elements are hashable print(hash(s2)) s2 = {frozenset({'a', 'b'}), frozenset({1, 2, 3})} # Copy frozenset t1 = (1, 2, [3, 4]) t2 = tuple(t1) print(id(t1), id(t2)) # same l1 = [1, 2, 3] l2...
part-3/2-sets/5-frozensets.py
from copy import deepcopy from functools import lru_cache s1 = {'a', 'b', 'c'} s2 = frozenset('abc') # Hashable as long as all elements are hashable print(hash(s2)) s2 = {frozenset({'a', 'b'}), frozenset({1, 2, 3})} # Copy frozenset t1 = (1, 2, [3, 4]) t2 = tuple(t1) print(id(t1), id(t2)) # same l1 = [1, 2, 3] l2...
0.605916
0.309128
# Check SEM's ability to stay in the neighborhood of the (label) truth # when initialized at the (label) truth. import numpy as np import matplotlib.pyplot as plt from matplotlib.mlab import PCA from Network import Network from Models import StationaryLogistic, NonstationaryLogistic, Blockmodel from Models import al...
minitest_gibbs.py
# Check SEM's ability to stay in the neighborhood of the (label) truth # when initialized at the (label) truth. import numpy as np import matplotlib.pyplot as plt from matplotlib.mlab import PCA from Network import Network from Models import StationaryLogistic, NonstationaryLogistic, Blockmodel from Models import al...
0.766687
0.676847
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Category' db.create_table('imagestore_category', ( ('id', self.gf('django.db.models.fields.AutoF...
imagestore/migrations/0001_initial.py
import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Category' db.create_table('imagestore_category', ( ('id', self.gf('django.db.models.fields.AutoF...
0.471467
0.104249
import asynctest import unittest.mock import os.path from livebridge import LiveBridge, config class RunTests(asynctest.TestCase): async def test_run_with_loop(self): self.loop.run_until_complete = asynctest.CoroutineMock(return_value=True) control_file = os.path.join(os.path.dirname(__file__), "...
tests/test_run.py
import asynctest import unittest.mock import os.path from livebridge import LiveBridge, config class RunTests(asynctest.TestCase): async def test_run_with_loop(self): self.loop.run_until_complete = asynctest.CoroutineMock(return_value=True) control_file = os.path.join(os.path.dirname(__file__), "...
0.365796
0.277216
import os import copy import thornpy from . import TMPLT_ENV from .utilities import read_TO_file, get_cdb_path, get_full_path class DrillSolverSettings(): """Creates an object with all data necessary to write an Adams Drill solver settings (.ssf) file. Note ---- The static funnel is stored as a :...
adamspy/adripy/solver_settings.py
import os import copy import thornpy from . import TMPLT_ENV from .utilities import read_TO_file, get_cdb_path, get_full_path class DrillSolverSettings(): """Creates an object with all data necessary to write an Adams Drill solver settings (.ssf) file. Note ---- The static funnel is stored as a :...
0.809615
0.418043
from ...jvm.lib.compat import * from ...jvm.lib import annotate, Optional from ...jvm.lib import public from ...jvm.lib import classproperty from ... import jni from ...jvm import JVM as _JVM @public class JVM(_JVM): """Represents the Java virtual machine""" jvm = classproperty(lambda cls: JVM._jv...
src/jt/rubicon/java/_jvm.py
from ...jvm.lib.compat import * from ...jvm.lib import annotate, Optional from ...jvm.lib import public from ...jvm.lib import classproperty from ... import jni from ...jvm import JVM as _JVM @public class JVM(_JVM): """Represents the Java virtual machine""" jvm = classproperty(lambda cls: JVM._jv...
0.751375
0.107204
import pathlib import sys import numpy as np from matplotlib import pyplot as plt from gromacs import ( read_gromacs_file, write_gromacs_gro_file, ) plt.style.use('seaborn-talk') def get_positions(frame): """Get positions given indices.""" xpos = np.array([i for i in frame['x']]) ypos = np.array(...
split_bilayer/translate.py
import pathlib import sys import numpy as np from matplotlib import pyplot as plt from gromacs import ( read_gromacs_file, write_gromacs_gro_file, ) plt.style.use('seaborn-talk') def get_positions(frame): """Get positions given indices.""" xpos = np.array([i for i in frame['x']]) ypos = np.array(...
0.501465
0.527134
import json import os import time from pathlib import Path import uuid import paho.mqtt.publish as publish def safe_publish(topic, msg, broker, timeout=5): if not broker: print("No MQTT broker configured") else: try: hostname, port = broker.split(':') return publish.si...
python/choirless_lib/choirless_lib/mqtt_status.py
import json import os import time from pathlib import Path import uuid import paho.mqtt.publish as publish def safe_publish(topic, msg, broker, timeout=5): if not broker: print("No MQTT broker configured") else: try: hostname, port = broker.split(':') return publish.si...
0.223971
0.057467
import FWCore.ParameterSet.Config as cms import DQM.TrackingMonitor.LogMessageMonitor_cfi LocalRecoLogMessageMon = DQM.TrackingMonitor.LogMessageMonitor_cfi.LogMessageMon.clone() LocalRecoLogMessageMon.pluginsMonName = cms.string ( 'LocalReco' ) LocalRecoLogMessageMon.modules = cms.vstring( 'siPixelDigis', 'si...
DQM/TrackingMonitor/python/LogMessageMonitor_cff.py
import FWCore.ParameterSet.Config as cms import DQM.TrackingMonitor.LogMessageMonitor_cfi LocalRecoLogMessageMon = DQM.TrackingMonitor.LogMessageMonitor_cfi.LogMessageMon.clone() LocalRecoLogMessageMon.pluginsMonName = cms.string ( 'LocalReco' ) LocalRecoLogMessageMon.modules = cms.vstring( 'siPixelDigis', 'si...
0.345768
0.193719
import os import sys import time import numpy as np import torch from torch import nn from torchvision import transforms # (N, C, H, W) #t = torch.randint(0, 255, size = (1, 3, 720, 1280), dtype = torch.uint8) def set_resize_layers(p_ls): resize_m_ls = [] for p in p_ls: m = nn.Upsample...
mobilenet_segment/test/test_resize_torch.py
import os import sys import time import numpy as np import torch from torch import nn from torchvision import transforms # (N, C, H, W) #t = torch.randint(0, 255, size = (1, 3, 720, 1280), dtype = torch.uint8) def set_resize_layers(p_ls): resize_m_ls = [] for p in p_ls: m = nn.Upsample...
0.40439
0.352146
from collections import defaultdict train_data = [['Yes', 'No', 'No', 'Yes', 'Some', '$$$', 'No', 'Yes', 'French', '0-10', 'Yes'], ['Yes', 'No', 'No', 'Yes', 'Full', '$', 'No', 'No', 'Thai', '30-60', 'No'], ['No', 'Yes', 'No', 'No', 'Some', '$', 'No', 'No', 'Burger', '0-10', 'Yes'], ...
ht10.py
from collections import defaultdict train_data = [['Yes', 'No', 'No', 'Yes', 'Some', '$$$', 'No', 'Yes', 'French', '0-10', 'Yes'], ['Yes', 'No', 'No', 'Yes', 'Full', '$', 'No', 'No', 'Thai', '30-60', 'No'], ['No', 'Yes', 'No', 'No', 'Some', '$', 'No', 'No', 'Burger', '0-10', 'Yes'], ...
0.237046
0.244848
import proto # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore from google.streetview.publish_v1.types import resources __protobuf__ = proto.module( package='google.streetview.publish.v1', manifest={ 'PhotoView', 'Crea...
google/streetview/publish/v1/streetview-publish-v1-py/google/streetview/publish_v1/types/rpcmessages.py
import proto # type: ignore from google.protobuf import field_mask_pb2 # type: ignore from google.rpc import status_pb2 # type: ignore from google.streetview.publish_v1.types import resources __protobuf__ = proto.module( package='google.streetview.publish.v1', manifest={ 'PhotoView', 'Crea...
0.723016
0.171269
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split # Code starts here df = pd.read_csv(path) print(df.head()) print(df.info) df.columns columns = ['INCOME','HOME_VAL','BLUEBOOK','OLDCLAIM','CLM_AMT'] for col in columns: d...
Imbalance/code.py
import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split # Code starts here df = pd.read_csv(path) print(df.head()) print(df.info) df.columns columns = ['INCOME','HOME_VAL','BLUEBOOK','OLDCLAIM','CLM_AMT'] for col in columns: d...
0.314471
0.300348
import numpy as np import scipy from sklearn.utils import sparsefuncs def normalize_by_umi(matrix): counts_per_bc = matrix.get_counts_per_bc() median_counts_per_bc = max(1.0, np.median(counts_per_bc)) scaling_factors = median_counts_per_bc / counts_per_bc # Normalize each barcode's total count by medi...
lib/python/cellranger/analysis/stats.py
import numpy as np import scipy from sklearn.utils import sparsefuncs def normalize_by_umi(matrix): counts_per_bc = matrix.get_counts_per_bc() median_counts_per_bc = max(1.0, np.median(counts_per_bc)) scaling_factors = median_counts_per_bc / counts_per_bc # Normalize each barcode's total count by medi...
0.870982
0.735547
import tensorflow as tf import numpy as np from tensorflow.keras.layers import Layer from utils import pnsm class PyramidNSMLayer(Layer): ''' ''' def __init__(self, ishape, num_of_rois, nsm_iou_threshold, nsm_score_threshold, anchor_4dtensors, **kwargs): self.ishape = ishape self.num_of_rois = num_of_rois ...
maskrcnn/PyramidNSMLayer.py
import tensorflow as tf import numpy as np from tensorflow.keras.layers import Layer from utils import pnsm class PyramidNSMLayer(Layer): ''' ''' def __init__(self, ishape, num_of_rois, nsm_iou_threshold, nsm_score_threshold, anchor_4dtensors, **kwargs): self.ishape = ishape self.num_of_rois = num_of_rois ...
0.633637
0.474144
from azure import * from azure.servicemanagement import * import errno import getopt import os import shutil import subprocess import sys import time # read env_local.sh def source_env_local(): command = ['bash', '-c', 'source env_local.sh && env'] proc = subprocess.Popen(command, stdout = subprocess.PIPE) ...
udf/bazaar/distribute/azure-client.py
from azure import * from azure.servicemanagement import * import errno import getopt import os import shutil import subprocess import sys import time # read env_local.sh def source_env_local(): command = ['bash', '-c', 'source env_local.sh && env'] proc = subprocess.Popen(command, stdout = subprocess.PIPE) ...
0.273186
0.05875
from typing import List from aws_cdk.aws_lambda import Runtime import jsii from aws_cdk import core as cdk from aws_cdk import aws_lambda_nodejs from aws_cdk.aws_ec2 import IInstance, IVpc, SubnetSelection from aws_cdk.aws_secretsmanager import ISecret from aws_cdk.aws_lambda_nodejs import ICommandHooks, NodejsFunctio...
scanner/stacks/graphql_api_stack.py
from typing import List from aws_cdk.aws_lambda import Runtime import jsii from aws_cdk import core as cdk from aws_cdk import aws_lambda_nodejs from aws_cdk.aws_ec2 import IInstance, IVpc, SubnetSelection from aws_cdk.aws_secretsmanager import ISecret from aws_cdk.aws_lambda_nodejs import ICommandHooks, NodejsFunctio...
0.482917
0.083778
import numpy as np import matplotlib.pyplot as plt import cv2 class GenCoe: def __init__(self, dir:str, filename:str, mode="gray"): self.dir = dir self.filename = filename loc = self.dir + "\\" + self.filename self.img = cv2.imread(loc, cv2.IMREAD_UNCHANGED) self.height, sel...
utils/gen_coe.py
import numpy as np import matplotlib.pyplot as plt import cv2 class GenCoe: def __init__(self, dir:str, filename:str, mode="gray"): self.dir = dir self.filename = filename loc = self.dir + "\\" + self.filename self.img = cv2.imread(loc, cv2.IMREAD_UNCHANGED) self.height, sel...
0.187839
0.148325
# Install boto before running the script # Setup AWS keys to get details from AWS Account import argparse import re import sys import time import boto.ec2 AMI_NAMES_TO_USER = { 'amzn' : 'ec2-user', 'ubuntu' : 'ubuntu', 'CentOS' : 'root', 'DataStax' : 'ubuntu', 'CoreOS' : 'core' } AMI_IDS_TO_USE...
create-sshconfig.py
# Install boto before running the script # Setup AWS keys to get details from AWS Account import argparse import re import sys import time import boto.ec2 AMI_NAMES_TO_USER = { 'amzn' : 'ec2-user', 'ubuntu' : 'ubuntu', 'CentOS' : 'root', 'DataStax' : 'ubuntu', 'CoreOS' : 'core' } AMI_IDS_TO_USE...
0.402979
0.065425
import pandas as pd import pytest from tabelio.mock import mock_table_data from tabelio.table import (FORMATS, BaseFormat, _find_format, convert_table_file, read_table_format, write_table_format) KNOWN_EXT = 'csv' UNKNOWN_EXT = 'unknown' @pytest.fixture def df()...
tests/test_table.py
import pandas as pd import pytest from tabelio.mock import mock_table_data from tabelio.table import (FORMATS, BaseFormat, _find_format, convert_table_file, read_table_format, write_table_format) KNOWN_EXT = 'csv' UNKNOWN_EXT = 'unknown' @pytest.fixture def df()...
0.392803
0.379005
import _thread def init(port): import zigbee; zigbee.init(port); def forward(): import zigbee; zigbee.sendString("w#"); def stop(): import zigbee; zigbee.sendString(" #"); def backward(): import zigbee; zigbee.sendString("s#"); def left(): import zigbee; zigbee.sendString("a#"); def ri...
Codes/examples/functionList.py
import _thread def init(port): import zigbee; zigbee.init(port); def forward(): import zigbee; zigbee.sendString("w#"); def stop(): import zigbee; zigbee.sendString(" #"); def backward(): import zigbee; zigbee.sendString("s#"); def left(): import zigbee; zigbee.sendString("a#"); def ri...
0.173498
0.041696
import json import shutil from collections import namedtuple from ansible.parsing.dataloader import DataLoader from ansible.vars.manager import VariableManager from ansible.inventory.manager import InventoryManager from ansible.playbook.play import Play from ansible.executor.task_queue_manager import TaskQueueManager ...
python/ansible/ansible_2.9_api.py
import json import shutil from collections import namedtuple from ansible.parsing.dataloader import DataLoader from ansible.vars.manager import VariableManager from ansible.inventory.manager import InventoryManager from ansible.playbook.play import Play from ansible.executor.task_queue_manager import TaskQueueManager ...
0.403802
0.171442
import os import csv import shutil from fama.utils.const import ENDS, STATUS_GOOD from fama.utils.utils import autovivify, run_external_program, run_external_program_ignoreerror from fama.gene_assembler.contig import Contig from fama.gene_assembler.gene import Gene from fama.gene_assembler.gene_assembly import GeneAss...
lib/fama/gene_assembler/gene_assembler.py
import os import csv import shutil from fama.utils.const import ENDS, STATUS_GOOD from fama.utils.utils import autovivify, run_external_program, run_external_program_ignoreerror from fama.gene_assembler.contig import Contig from fama.gene_assembler.gene import Gene from fama.gene_assembler.gene_assembly import GeneAss...
0.539954
0.175467
import os tf_version = float(os.environ["TF_VERSION"][:3]) tf_keras = bool(os.environ["TF_KERAS"] == "True") tf_python = bool(os.environ["TF_PYTHON"] == "True") if tf_version >= 2: if tf_keras: from keras_adamw.optimizers_v2 import AdamW, NadamW, SGDW elif tf_python: from keras_adamw.optimiz...
tests/import_selection.py
import os tf_version = float(os.environ["TF_VERSION"][:3]) tf_keras = bool(os.environ["TF_KERAS"] == "True") tf_python = bool(os.environ["TF_PYTHON"] == "True") if tf_version >= 2: if tf_keras: from keras_adamw.optimizers_v2 import AdamW, NadamW, SGDW elif tf_python: from keras_adamw.optimiz...
0.726717
0.325346
import numpy as np from qa_tools.utils import * from qa_tools.prediction import * def qa_pes_errors( df_qc, n_electrons, excitation_level=0, basis_set='aug-cc-pV5Z', bond_length=None, return_energies=False, energy_type='total'): """Computes the error associated with predicting a system's absolute ele...
qa_tools/analysis.py
import numpy as np from qa_tools.utils import * from qa_tools.prediction import * def qa_pes_errors( df_qc, n_electrons, excitation_level=0, basis_set='aug-cc-pV5Z', bond_length=None, return_energies=False, energy_type='total'): """Computes the error associated with predicting a system's absolute ele...
0.857321
0.607197
from django.conf import settings from django_statsd.clients import statsd from lib.geoip import GeoIP import mkt class RegionMiddleware(object): """Figure out the user's region and store it in a cookie.""" def __init__(self): self.geoip = GeoIP(settings) def region_from_request(self, request)...
mkt/regions/middleware.py
from django.conf import settings from django_statsd.clients import statsd from lib.geoip import GeoIP import mkt class RegionMiddleware(object): """Figure out the user's region and store it in a cookie.""" def __init__(self): self.geoip = GeoIP(settings) def region_from_request(self, request)...
0.599837
0.163345
"""Khronos OpenGL gl.xml to C++ GL wrapper generator.""" import argparse import json import os import re import xml.etree.ElementTree as ET from collections import defaultdict from config import ( EXTENSION_SUFFIXES, RESERVED_NAMES, FUNCTION_SUFFIXES, HANDLE_TYPES, EXCLUDED_ENUMS, EXTRA_ENUM_GR...
src/erhe/gl/generate_sources.py
"""Khronos OpenGL gl.xml to C++ GL wrapper generator.""" import argparse import json import os import re import xml.etree.ElementTree as ET from collections import defaultdict from config import ( EXTENSION_SUFFIXES, RESERVED_NAMES, FUNCTION_SUFFIXES, HANDLE_TYPES, EXCLUDED_ENUMS, EXTRA_ENUM_GR...
0.704973
0.122549
import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.ContactModel import ContactModel class AlipayOpenAgentCreateModel(object): def __init__(self): self._account = None self._contact_info = None self._order_ticket = None @property def accou...
alipay/aop/api/domain/AlipayOpenAgentCreateModel.py
import json from alipay.aop.api.constant.ParamConstants import * from alipay.aop.api.domain.ContactModel import ContactModel class AlipayOpenAgentCreateModel(object): def __init__(self): self._account = None self._contact_info = None self._order_ticket = None @property def accou...
0.437703
0.07333
from multiprocessing import Process, Pool from time import sleep, time from express.database import * from express.settings import * from express.logging import Log, f from express.prices import update_pricelist from express.config import * from express.client import Client from express.offer import Offer, valuate fro...
main.py
from multiprocessing import Process, Pool from time import sleep, time from express.database import * from express.settings import * from express.logging import Log, f from express.prices import update_pricelist from express.config import * from express.client import Client from express.offer import Offer, valuate fro...
0.287068
0.161949
import bcrypt from datetime import datetime from app.database import BaseMixin, db class User(BaseMixin, db.Model): __tablename__ = 'users' userID = db.Column(db.Integer, primary_key=True) username = db.Column(db.String, nullable=False) _password = db.Column(db.Binary(60)) vorname = db.Column(...
server/app/api/user/models.py
import bcrypt from datetime import datetime from app.database import BaseMixin, db class User(BaseMixin, db.Model): __tablename__ = 'users' userID = db.Column(db.Integer, primary_key=True) username = db.Column(db.String, nullable=False) _password = db.Column(db.Binary(60)) vorname = db.Column(...
0.332202
0.083965
import logging import os from dataclasses import dataclass from typing import Mapping, Optional, Tuple from pants.base.build_environment import get_buildroot from pants.base.exception_sink import ExceptionSink from pants.base.exiter import PANTS_FAILED_EXIT_CODE, PANTS_SUCCEEDED_EXIT_CODE, ExitCode from pants.base.sp...
src/python/pants/bin/local_pants_runner.py
import logging import os from dataclasses import dataclass from typing import Mapping, Optional, Tuple from pants.base.build_environment import get_buildroot from pants.base.exception_sink import ExceptionSink from pants.base.exiter import PANTS_FAILED_EXIT_CODE, PANTS_SUCCEEDED_EXIT_CODE, ExitCode from pants.base.sp...
0.868172
0.085671
from akashic.arules.transpiler import Transpiler from akashic.ads.data_provider import DataProvider from akashic.env_provider import EnvProvider from akashic.bridges.data_bridge import DataBridge from akashic.bridges.time_bridge import TimeBridge from os.path import join, dirname, abspath import json def test_rule_...
test/main.py
from akashic.arules.transpiler import Transpiler from akashic.ads.data_provider import DataProvider from akashic.env_provider import EnvProvider from akashic.bridges.data_bridge import DataBridge from akashic.bridges.time_bridge import TimeBridge from os.path import join, dirname, abspath import json def test_rule_...
0.41324
0.267214
from RLBench import Bench, BenchConfig from RLBench.bench import BenchRun from RLBench.algo import PolicyGradient from RLBench.envs import LinearCar from mock import Mock, MagicMock, patch from unittest2 import TestCase import logging logger = logging.getLogger(__name__) class TestBench(TestCase): """Bench te...
RLBench/test/test_bench.py
from RLBench import Bench, BenchConfig from RLBench.bench import BenchRun from RLBench.algo import PolicyGradient from RLBench.envs import LinearCar from mock import Mock, MagicMock, patch from unittest2 import TestCase import logging logger = logging.getLogger(__name__) class TestBench(TestCase): """Bench te...
0.898514
0.453201
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def train_test_compare(train_df, test_df): """ Comparing the details of train and test datasets PARAMETERS train_df : Training set pandas dataframe (dataframe) test_df : Testing set pandas dataframe (dataframe) ...
utils/data_background.py
import pandas as pd import matplotlib.pyplot as plt import seaborn as sns def train_test_compare(train_df, test_df): """ Comparing the details of train and test datasets PARAMETERS train_df : Training set pandas dataframe (dataframe) test_df : Testing set pandas dataframe (dataframe) ...
0.602763
0.700312
import json from datatypes import Metrics def loadMetrics(metricsFilename): metrics = {} try: with open(metricsFilename, 'r') as f: js = json.load(f) # expecting dict of prj name to sub-dict for prj_name, prj_dict in js.items(): prj_metrics = {} ...
metricsfile.py
import json from datatypes import Metrics def loadMetrics(metricsFilename): metrics = {} try: with open(metricsFilename, 'r') as f: js = json.load(f) # expecting dict of prj name to sub-dict for prj_name, prj_dict in js.items(): prj_metrics = {} ...
0.386069
0.168925
from sys import stdin, stdout from copy import deepcopy def extendAtlas(atlas): global showAtlas innerAtlas = deepcopy(atlas) incrementLine = (lambda line: list(map((lambda number: number+1 if number < 9 else 1), line))) incrementAtlas = (lambda atlas: list(map(incrementLine, atlas))) for i in r...
2021/day15/part2/main.py
from sys import stdin, stdout from copy import deepcopy def extendAtlas(atlas): global showAtlas innerAtlas = deepcopy(atlas) incrementLine = (lambda line: list(map((lambda number: number+1 if number < 9 else 1), line))) incrementAtlas = (lambda atlas: list(map(incrementLine, atlas))) for i in r...
0.06101
0.409634
import utilAlgorithm from numpy import * from logger import logger from utilfile import * from utilconfigration import cfg class utilAlg_Mean(utilAlgorithm.utilAlgorithm): def __init__(self): print('utilAlg_Mean __init__', self.__class__.__name__) def trainData(self, trainX, trainY, train_attri_dict,...
Algorithm/MachineLearning/TianChi/CarSellPredict/src/utilAlg_Mean.py
import utilAlgorithm from numpy import * from logger import logger from utilfile import * from utilconfigration import cfg class utilAlg_Mean(utilAlgorithm.utilAlgorithm): def __init__(self): print('utilAlg_Mean __init__', self.__class__.__name__) def trainData(self, trainX, trainY, train_attri_dict,...
0.250179
0.188175
import tensorflow as tf import numpy as np class VGG19: def __init__(self,VGG19_Model_Path = None): self.wDict = np.load(VGG19_Model_Path, encoding="bytes").item() def build(self,picture): self.conv1_1 = tf.nn.conv2d( input=picture, filter=self...
models/vgg19_tf.py
import tensorflow as tf import numpy as np class VGG19: def __init__(self,VGG19_Model_Path = None): self.wDict = np.load(VGG19_Model_Path, encoding="bytes").item() def build(self,picture): self.conv1_1 = tf.nn.conv2d( input=picture, filter=self...
0.549761
0.322673
import subprocess import time import datetime import os import threading import pandas as pd ''' shop_code = 'kkakka001' acc = 'qtumai' passwd = '<PASSWORD>' ip = '192.168.0.59' port = '554' ch = 'stream_ch00_0' add = 'rtsp://' + acc + ':' + passwd + '@' + ip + ':' + port + '/' + ch save_path = './s...
B2C/video_recoding.py
import subprocess import time import datetime import os import threading import pandas as pd ''' shop_code = 'kkakka001' acc = 'qtumai' passwd = '<PASSWORD>' ip = '192.168.0.59' port = '554' ch = 'stream_ch00_0' add = 'rtsp://' + acc + ':' + passwd + '@' + ip + ':' + port + '/' + ch save_path = './s...
0.112808
0.05498
import random # Call comes in call = '' # Good morning, Thistle Hyundai computer speaking, how can I direct your call? print('Good morning, <NAME>, this is computer speaking.\n\nHow can I direct your call?') call = input() # Sales call if call.lower() == 'sales': print('Thanks, please hold fo...
callTest.py
import random # Call comes in call = '' # Good morning, Thistle Hyundai computer speaking, how can I direct your call? print('Good morning, <NAME>, this is computer speaking.\n\nHow can I direct your call?') call = input() # Sales call if call.lower() == 'sales': print('Thanks, please hold fo...
0.043043
0.051201
from env.tic_tac_toe_env import TicTacToe from agent.agent import Agent import random import numpy as np from PIL import Image class TicTacToeGameManager(): def __init__(self, strategy=None, saved_model=None): self.game = TicTacToe() self.agent_first_cmap = {0: 177, 1: 255, 2: 0} self.agen...
tic_tac_toe/env/game_manager.py
from env.tic_tac_toe_env import TicTacToe from agent.agent import Agent import random import numpy as np from PIL import Image class TicTacToeGameManager(): def __init__(self, strategy=None, saved_model=None): self.game = TicTacToe() self.agent_first_cmap = {0: 177, 1: 255, 2: 0} self.agen...
0.403567
0.310662
from app import db from flask_login import LoginManager, UserMixin from datetime import date, datetime from flask_restful import Resource, Api, abort, reqparse class User(UserMixin, db.Model): user_id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100), unique=True) password = db...
app/models.py
from app import db from flask_login import LoginManager, UserMixin from datetime import date, datetime from flask_restful import Resource, Api, abort, reqparse class User(UserMixin, db.Model): user_id = db.Column(db.Integer, primary_key=True) email = db.Column(db.String(100), unique=True) password = db...
0.448185
0.058723
# @Author: <NAME> <valle> # @Date: 10-May-2017 # @Email: <EMAIL> # @Last modified by: valle # @Last modified time: 16-Mar-2018 # @License: Apache license vesion 2.0 from kivy.uix.anchorlayout import AnchorLayout from kivy.storage.jsonstore import JsonStore from kivy.properties import ObjectProperty, ListProperty...
tpv_for_eetop/tpv/controllers/listadopdwidget.py
# @Author: <NAME> <valle> # @Date: 10-May-2017 # @Email: <EMAIL> # @Last modified by: valle # @Last modified time: 16-Mar-2018 # @License: Apache license vesion 2.0 from kivy.uix.anchorlayout import AnchorLayout from kivy.storage.jsonstore import JsonStore from kivy.properties import ObjectProperty, ListProperty...
0.189821
0.102619
import unittest from dependency_injector import containers, providers class TraverseProviderTests(unittest.TestCase): def test_nested_providers(self): class Container(containers.DeclarativeContainer): obj_factory = providers.DelegatedFactory( dict, foo=provide...
tests/unit/containers/test_traversal_py3.py
import unittest from dependency_injector import containers, providers class TraverseProviderTests(unittest.TestCase): def test_nested_providers(self): class Container(containers.DeclarativeContainer): obj_factory = providers.DelegatedFactory( dict, foo=provide...
0.618204
0.363958
import torch import torch.nn as nn import torch.nn.functional as F class SSIM(nn.Module): """Layer to compute the SSIM loss between a pair of images """ def __init__(self): super(SSIM, self).__init__() self.mu_x_pool = nn.AvgPool2d(3, 1) self.mu_y_pool = nn.AvgPool2d(3, 1) ...
u_mvs_mvsnet/losses/modules.py
import torch import torch.nn as nn import torch.nn.functional as F class SSIM(nn.Module): """Layer to compute the SSIM loss between a pair of images """ def __init__(self): super(SSIM, self).__init__() self.mu_x_pool = nn.AvgPool2d(3, 1) self.mu_y_pool = nn.AvgPool2d(3, 1) ...
0.903746
0.603348
import sys import numpy as np import pickle import scipy from scipy.spatial.distance import squareform from scipy.stats import zscore from scipy.cluster import hierarchy from tqdm import tqdm from collections import namedtuple from idpflex.distances import (rmsd_matrix, extract_coordinates) from idpflex.cnextend imp...
idpflex/cluster.py
import sys import numpy as np import pickle import scipy from scipy.spatial.distance import squareform from scipy.stats import zscore from scipy.cluster import hierarchy from tqdm import tqdm from collections import namedtuple from idpflex.distances import (rmsd_matrix, extract_coordinates) from idpflex.cnextend imp...
0.78789
0.58948
import unittest from tplink_wr.parse import html class TestScriptFinder(unittest.TestCase): def test_exist(self): finder = html.ScriptFinder() finder.feed("<script>var abc = true;</script>") scripts = finder.get_scripts() self.assertEqual(scripts, ["var abc = true;"]) def tes...
tests/parse/test_html.py
import unittest from tplink_wr.parse import html class TestScriptFinder(unittest.TestCase): def test_exist(self): finder = html.ScriptFinder() finder.feed("<script>var abc = true;</script>") scripts = finder.get_scripts() self.assertEqual(scripts, ["var abc = true;"]) def tes...
0.400632
0.198122
"""Misc utils. Currently largely for assistance testing domain models.""" import copy from typing import Any from typing import Callable from typing import Dict from typing import List from typing import Optional from typing import Tuple from typing import Union from domain_model import DomainModel import pytest def...
src/misc_test_utils/misc_test_utils.py
"""Misc utils. Currently largely for assistance testing domain models.""" import copy from typing import Any from typing import Callable from typing import Dict from typing import List from typing import Optional from typing import Tuple from typing import Union from domain_model import DomainModel import pytest def...
0.905673
0.386908
import numpy as np import os from numpy import linalg as LA import matplotlib.pyplot as plt #datapath = '../Chair_parts' datapath = 'data/examples' def renderBoxes2mesh_new(boxes, boxes_type, obj_names): results = [] for box_i in range(boxes.shape[0]): vertices = [] faces = [] obj_name ...
render2mesh.py
import numpy as np import os from numpy import linalg as LA import matplotlib.pyplot as plt #datapath = '../Chair_parts' datapath = 'data/examples' def renderBoxes2mesh_new(boxes, boxes_type, obj_names): results = [] for box_i in range(boxes.shape[0]): vertices = [] faces = [] obj_name ...
0.119871
0.29922
__all__ = ['mahalanobis_pca_outliers'] import numpy as np def mahalanobis_pca_outliers(X, n_components=2, threshold=2, plot=False): """ Compute PCA on X, then compute the malanobis distance of all data points from the PCA components. Params ------ X: data n_components: int (default=2) ...
python_data_utils/sklearn/data/utils.py
__all__ = ['mahalanobis_pca_outliers'] import numpy as np def mahalanobis_pca_outliers(X, n_components=2, threshold=2, plot=False): """ Compute PCA on X, then compute the malanobis distance of all data points from the PCA components. Params ------ X: data n_components: int (default=2) ...
0.90652
0.742235
from mininet.net import Mininet from mininet.node import Controller, RemoteController, OVSController from mininet.node import CPULimitedHost, Host, Node from mininet.node import OVSKernelSwitch, UserSwitch from mininet.node import IVSSwitch from mininet.cli import CLI from mininet.log import setLogLevel, info from min...
Chapter10/10_7_sdn_miniedit.py
from mininet.net import Mininet from mininet.node import Controller, RemoteController, OVSController from mininet.node import CPULimitedHost, Host, Node from mininet.node import OVSKernelSwitch, UserSwitch from mininet.node import IVSSwitch from mininet.cli import CLI from mininet.log import setLogLevel, info from min...
0.644001
0.061312
import os import unittest import typing import math import collections def get_file_contents() -> str: dir_path = os.path.dirname(os.path.realpath(__file__)) file_path = os.path.join(dir_path, "..", "data", "d14.txt") with open(file_path, "r") as f: lines = f.read() return lines ChemicalName...
python/p14.py
import os import unittest import typing import math import collections def get_file_contents() -> str: dir_path = os.path.dirname(os.path.realpath(__file__)) file_path = os.path.join(dir_path, "..", "data", "d14.txt") with open(file_path, "r") as f: lines = f.read() return lines ChemicalName...
0.409221
0.373333
from lib.cuckoo.common.abstracts import Signature class RansomwareExtensions(Signature): name = "ransomware_extensions" description = "Appends known ransomware file extensions to files that have been encrypted" severity = 3 categories = ["ransomware"] authors = ["<NAME>"] indicators = [ ...
modules/signatures/windows/ransomware_fileextensions.py
from lib.cuckoo.common.abstracts import Signature class RansomwareExtensions(Signature): name = "ransomware_extensions" description = "Appends known ransomware file extensions to files that have been encrypted" severity = 3 categories = ["ransomware"] authors = ["<NAME>"] indicators = [ ...
0.510252
0.224459
from plugin.core.constants import PLUGIN_VERSION_BASE from plugin.core.helpers.variable import all from lxml import etree import shutil import os class FSMigrator(object): migrations = [] @classmethod def register(cls, migration): cls.migrations.append(migration()) @classmethod def run(...
Trakttv.bundle/Contents/Code/fs_migrator.py
from plugin.core.constants import PLUGIN_VERSION_BASE from plugin.core.helpers.variable import all from lxml import etree import shutil import os class FSMigrator(object): migrations = [] @classmethod def register(cls, migration): cls.migrations.append(migration()) @classmethod def run(...
0.500488
0.099996
from itertools import chain from util import nub import numpy as np import string from collections import OrderedDict UNK_TOKEN = "*UNK*" START_TOKEN = "*START*" END_TOKEN = "*END*" PRINTABLE = set(string.printable) def main(): validation_data_file, validation_label_file, train_data_file, train_label_file = "./so...
my_soft_pattern.py
from itertools import chain from util import nub import numpy as np import string from collections import OrderedDict UNK_TOKEN = "*UNK*" START_TOKEN = "*START*" END_TOKEN = "*END*" PRINTABLE = set(string.printable) def main(): validation_data_file, validation_label_file, train_data_file, train_label_file = "./so...
0.327346
0.244775
from pyradur import Dict from pyradur.db import Sqlite3DB from pyradur.server import SockServer import tempfile import threading import unittest import shutil import os import logging import sys class CommonTests(object): use_cache = True close_on_cleanup = True def _server_thread(self, event): t...
pyradur/tests/test_pyradur.py
from pyradur import Dict from pyradur.db import Sqlite3DB from pyradur.server import SockServer import tempfile import threading import unittest import shutil import os import logging import sys class CommonTests(object): use_cache = True close_on_cleanup = True def _server_thread(self, event): t...
0.412648
0.152789
from linked_list import SinglyLinkedList, SinglyLinkedNode def inner_step(n1, n2, n3, sum_ll, carry): total = carry if n1: total += n1.value n1 = n1.next if n2: total += n2.value n2 = n2.next result = total % 10 carry = total // 10 new_node = SinglyLinkedNode(res...
ch02_linked_lists/q05_sum_lists.py
from linked_list import SinglyLinkedList, SinglyLinkedNode def inner_step(n1, n2, n3, sum_ll, carry): total = carry if n1: total += n1.value n1 = n1.next if n2: total += n2.value n2 = n2.next result = total % 10 carry = total // 10 new_node = SinglyLinkedNode(res...
0.328314
0.369002
import os import json from typing import Dict, List, Optional, Union, cast import requests from requests import get import bs4 from bs4 import BeautifulSoup import pandas as pd from env import github_token, github_username #----------------------------------------------------------------------------------------------...
acquire.py
import os import json from typing import Dict, List, Optional, Union, cast import requests from requests import get import bs4 from bs4 import BeautifulSoup import pandas as pd from env import github_token, github_username #----------------------------------------------------------------------------------------------...
0.278061
0.239427
print('Start next file, \'page_04\'') # imports from openpyxl import load_workbook from openpyxl.styles import Alignment, Border, Side, NamedStyle, Font, PatternFill wb = load_workbook(filename = 'Plymouth_Daily_Rounds.xlsx') sheet = wb["Page_04"] print('Active sheet is ', sheet) print('04-01') wb.save('Plymouth_Daily_...
archive/page_04_firepprm_docking - Copy.py
print('Start next file, \'page_04\'') # imports from openpyxl import load_workbook from openpyxl.styles import Alignment, Border, Side, NamedStyle, Font, PatternFill wb = load_workbook(filename = 'Plymouth_Daily_Rounds.xlsx') sheet = wb["Page_04"] print('Active sheet is ', sheet) print('04-01') wb.save('Plymouth_Daily_...
0.261897
0.259204
import random import string from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.text import slugify from .utils import upload_track_to, upload_image_to class Genre(models.Model): ...
edmproducers/models.py
import random import string from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.text import slugify from .utils import upload_track_to, upload_image_to class Genre(models.Model): ...
0.516595
0.065515
import getopt import os import subprocess import sys import toml # Set the path to the configuration file CONFIG_PATH = "" def decrypt(config, key): # Call gocryptfs process path_cipher = config[key]["cipher"] path_plain = config[key]["plain"] subprocess.run(["gocryptfs", path_cipher, path_plain]) d...
main.py
import getopt import os import subprocess import sys import toml # Set the path to the configuration file CONFIG_PATH = "" def decrypt(config, key): # Call gocryptfs process path_cipher = config[key]["cipher"] path_plain = config[key]["plain"] subprocess.run(["gocryptfs", path_cipher, path_plain]) d...
0.137532
0.103612
description = 'Vacuum gauges in the neutron guide' devices = dict( vac1 = device('nicos.devices.generic.VirtualMotor', description = 'Vacuum sensor 1 in neutron guide', abslimits = (0, 1000), pollinterval = 10, maxage = 12, unit = 'mbar', curvalue = 1.1e-4, f...
nicos_ess/cspec/setups/vacuum.py
description = 'Vacuum gauges in the neutron guide' devices = dict( vac1 = device('nicos.devices.generic.VirtualMotor', description = 'Vacuum sensor 1 in neutron guide', abslimits = (0, 1000), pollinterval = 10, maxage = 12, unit = 'mbar', curvalue = 1.1e-4, f...
0.646906
0.520984
import numpy as np from scipy import ndimage from time import clock from pygeonet_rasterio import * from pygeonet_vectorio import * from pygeonet_plot import * def Channel_Head_Definition(skeletonFromFlowAndCurvatureArray, geodesicDistanceArray): # Locating end points print 'Locating skeleton end po...
pygeonet_channel_head_definition.py
import numpy as np from scipy import ndimage from time import clock from pygeonet_rasterio import * from pygeonet_vectorio import * from pygeonet_plot import * def Channel_Head_Definition(skeletonFromFlowAndCurvatureArray, geodesicDistanceArray): # Locating end points print 'Locating skeleton end po...
0.479504
0.521167
import json from itertools import combinations from math import log import scipy.interpolate from pymatgen.entries.computed_entries import ComputedEntry from s4.data import open_data __author__ = '<NAME>' __email__ = '<EMAIL>' __maintainer__ = '<NAME>' __all__ = [ 'finite_dg_correction', ] with open_data('Elem...
s4/thermo/calc/finite_g.py
import json from itertools import combinations from math import log import scipy.interpolate from pymatgen.entries.computed_entries import ComputedEntry from s4.data import open_data __author__ = '<NAME>' __email__ = '<EMAIL>' __maintainer__ = '<NAME>' __all__ = [ 'finite_dg_correction', ] with open_data('Elem...
0.744471
0.263671
import unicodedata combining = set() col_widths = [7, 54, 20] rows = [['MacRom', 'UTF-8 NFC', 'UTF-8 NFD']] for i in range(256): rows.append(['[%02X]' % i]) for form in ('NFC', 'NFD'): unistr = bytes([i]).decode('mac_roman') unistr = unicodedata.normalize(form, unistr) codepoints = []...
MacRomanExploration.py
import unicodedata combining = set() col_widths = [7, 54, 20] rows = [['MacRom', 'UTF-8 NFC', 'UTF-8 NFD']] for i in range(256): rows.append(['[%02X]' % i]) for form in ('NFC', 'NFD'): unistr = bytes([i]).decode('mac_roman') unistr = unicodedata.normalize(form, unistr) codepoints = []...
0.094278
0.503113
import math import time t1 = time.time() size = 2000 sizet = size*size s = [0]*sizet for k in range(1,56): s[k-1] = (100003-200003*k+300007*k*k*k)%1000000-500000 for k in range(56,4000001): s[k-1] = (s[k-1-24]+s[k-1-55]+1000000)%1000000-500000 #print(s[10-1],s[100-1]) ''' # test case s = [-2,5,3,2,9,-...
Problem 001-150 Python/pb149.py
import math import time t1 = time.time() size = 2000 sizet = size*size s = [0]*sizet for k in range(1,56): s[k-1] = (100003-200003*k+300007*k*k*k)%1000000-500000 for k in range(56,4000001): s[k-1] = (s[k-1-24]+s[k-1-55]+1000000)%1000000-500000 #print(s[10-1],s[100-1]) ''' # test case s = [-2,5,3,2,9,-...
0.07107
0.239161
from datetime import datetime from flask import request from flask_restx import Resource import json from io import StringIO import boto3 import pandas as pd import numpy as np from .security import require_auth from . import api_rest class SecureResource(Resource): """ Calls require_auth decorator on all reque...
app/api/resources.py
from datetime import datetime from flask import request from flask_restx import Resource import json from io import StringIO import boto3 import pandas as pd import numpy as np from .security import require_auth from . import api_rest class SecureResource(Resource): """ Calls require_auth decorator on all reque...
0.460046
0.144209
"""Create a new CA pool.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.api_lib.privateca import base as privateca_base from googlecloudsdk.api_lib.privateca import request_utils from googlecloudsdk.calliope import base from google...
lib/surface/privateca/pools/create.py
"""Create a new CA pool.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from googlecloudsdk.api_lib.privateca import base as privateca_base from googlecloudsdk.api_lib.privateca import request_utils from googlecloudsdk.calliope import base from google...
0.727104
0.120983
from django.db import models from django.utils.translation import ugettext_lazy as _ from ...core.models import TimeStampedModel from ...core.utils.slug import slugify_uniquely_for_queryset from ..choices import RANK_OPTIONS from ..mixins import DueDateMixin from .. import models as proj_models class IssueStatus(m...
project_dashboard/projects/models/issue.py
from django.db import models from django.utils.translation import ugettext_lazy as _ from ...core.models import TimeStampedModel from ...core.utils.slug import slugify_uniquely_for_queryset from ..choices import RANK_OPTIONS from ..mixins import DueDateMixin from .. import models as proj_models class IssueStatus(m...
0.567337
0.086671
import time import os import mido from mido import Message, MidiFile, MidiTrack, tempo2bpm from pynput import keyboard key_dict = { # c4 "a4+":22, "b4-":22, "b4": 23, # c3 "c3": 24, "c3+": 25, "d3-": 25, "d3": 26, "d3+": 27, "e3-": 27, "e3": 28, "f3": 29, "f3+": 30, "g3-": 30, ...
vimusic.py
import time import os import mido from mido import Message, MidiFile, MidiTrack, tempo2bpm from pynput import keyboard key_dict = { # c4 "a4+":22, "b4-":22, "b4": 23, # c3 "c3": 24, "c3+": 25, "d3-": 25, "d3": 26, "d3+": 27, "e3-": 27, "e3": 28, "f3": 29, "f3+": 30, "g3-": 30, ...
0.406862
0.403861
from numpy.core.arrayprint import BoolFormat from game import * from encoder import * from arena import * from dataManager import * from network import * class Program: def __init__(self,the_game): self.the_game = the_game self.best_network = readNeuralNetwork("networks/best_network") self...
program_test.py
from numpy.core.arrayprint import BoolFormat from game import * from encoder import * from arena import * from dataManager import * from network import * class Program: def __init__(self,the_game): self.the_game = the_game self.best_network = readNeuralNetwork("networks/best_network") self...
0.446253
0.278994
import flask import glob import json import os import pandas as pd import sys import webbrowser from datetime import datetime from flask import Flask, request from flask_cors import CORS app = Flask(__name__, static_url_path='') app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # TODO remove in prod CORS(app) project_dir ...
tools/server.py
import flask import glob import json import os import pandas as pd import sys import webbrowser from datetime import datetime from flask import Flask, request from flask_cors import CORS app = Flask(__name__, static_url_path='') app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # TODO remove in prod CORS(app) project_dir ...
0.186391
0.109634
import logging import os import re import pandas as pd import gamechangerml.src.text_classif.utils.entity_mentions as em from gamechangerml.src.text_classif.utils.predict_glob import predict_glob from gamechangerml.src.text_classif.utils.top_k_entities import top_k_entities logger = logging.getLogger(__name__) cla...
gamechangerml/src/text_classif/utils/entity_link.py
import logging import os import re import pandas as pd import gamechangerml.src.text_classif.utils.entity_mentions as em from gamechangerml.src.text_classif.utils.predict_glob import predict_glob from gamechangerml.src.text_classif.utils.top_k_entities import top_k_entities logger = logging.getLogger(__name__) cla...
0.66072
0.150778
import urllib import urllib2 import requests import threading import json from time import sleep url = 'http://localhost:8545/' import os.path def get_result(json_content): content = json.loads(json_content) try: return content["result"] except Exception as e: print e print json_con...
contract_data/contracts_collector.py
import urllib import urllib2 import requests import threading import json from time import sleep url = 'http://localhost:8545/' import os.path def get_result(json_content): content = json.loads(json_content) try: return content["result"] except Exception as e: print e print json_con...
0.080936
0.089097
from typing import Optional from typing import Tuple from typing import Union import numpy as np import pandas as pd from pyspark import sql from pyspark.sql import functions from cape_privacy.spark import dtypes from cape_privacy.spark.transformations import base from cape_privacy.utils import typecheck _FREQUENCY_...
cape_privacy/spark/transformations/perturbation.py
from typing import Optional from typing import Tuple from typing import Union import numpy as np import pandas as pd from pyspark import sql from pyspark.sql import functions from cape_privacy.spark import dtypes from cape_privacy.spark.transformations import base from cape_privacy.utils import typecheck _FREQUENCY_...
0.897741
0.624637
import random regs = ['ra', 'rb', 'rc', 'rd', 're'] def generate_imm(): return hex(random.randint(0, 0xffffffffffffffff)) def generate_mpc(): if random.randint(0, 1) == 0: return 'mpc {}'.format(random.choice(regs)) else: return 'mpc {} #{}'.format(random.choice(regs), generate_imm()) de...
b01lers-ctf-2020/300_railed/src/generate_random_instructions.py
import random regs = ['ra', 'rb', 'rc', 'rd', 're'] def generate_imm(): return hex(random.randint(0, 0xffffffffffffffff)) def generate_mpc(): if random.randint(0, 1) == 0: return 'mpc {}'.format(random.choice(regs)) else: return 'mpc {} #{}'.format(random.choice(regs), generate_imm()) de...
0.115025
0.200969
import torch import torchvision import torchvision.transforms as transforms class BinaryDataset(torch.utils.data.Dataset): def __init__(self, root, transform=None, return_idx=False): x, y = torch.load(root) self.data = x self.labels = y self.root = root self.transform = tra...
dataset.py
import torch import torchvision import torchvision.transforms as transforms class BinaryDataset(torch.utils.data.Dataset): def __init__(self, root, transform=None, return_idx=False): x, y = torch.load(root) self.data = x self.labels = y self.root = root self.transform = tra...
0.912801
0.675737
import json __author__ = '<NAME>' class SiteInfo: def __init__(self,dataname='SiteData',sitedatafile=[]): """ __init__: initialization """ self.sitedatafile = sitedatafile self.nCase = 0 self.nameCase = [] self.SiteCase = {} self...
pyhca/SiteSpecificInformation.py
import json __author__ = '<NAME>' class SiteInfo: def __init__(self,dataname='SiteData',sitedatafile=[]): """ __init__: initialization """ self.sitedatafile = sitedatafile self.nCase = 0 self.nameCase = [] self.SiteCase = {} self...
0.089318
0.166404
from mvnc import mvncapi as mvnc import NeuralNetwork import cv2 import argparse import time import threading #Argument parser arg = argparse.ArgumentParser() arg.add_argument("-m", "--mode", required=True, type=str, default="image", help="Mode of Neural Network, options: image, video") arg.add_argument("-n", "--num",...
run.py
from mvnc import mvncapi as mvnc import NeuralNetwork import cv2 import argparse import time import threading #Argument parser arg = argparse.ArgumentParser() arg.add_argument("-m", "--mode", required=True, type=str, default="image", help="Mode of Neural Network, options: image, video") arg.add_argument("-n", "--num",...
0.143023
0.138695
import os import re from .ply import lex, yacc from collections import OrderedDict import sublime class Parser: """ Base class for a lexer/parser that has the rules defined as methods """ tokens = () precedence = () def __init__(self, **kw): self.debug = kw.get('debug', 0) sel...
proto_formatter.py
import os import re from .ply import lex, yacc from collections import OrderedDict import sublime class Parser: """ Base class for a lexer/parser that has the rules defined as methods """ tokens = () precedence = () def __init__(self, **kw): self.debug = kw.get('debug', 0) sel...
0.430267
0.172677
import os import re import logging from unidecode import unidecode from onecodex.exceptions import OneCodexException, UploadException R1_FILENAME_RE = re.compile(".*[._][Rr]?[1][_.].*") R2_FILENAME_RE = re.compile(".*[._][Rr]?[2][_.].*") log = logging.getLogger("onecodex") def _check_for_ascii_filename(filename, co...
onecodex/lib/files.py
import os import re import logging from unidecode import unidecode from onecodex.exceptions import OneCodexException, UploadException R1_FILENAME_RE = re.compile(".*[._][Rr]?[1][_.].*") R2_FILENAME_RE = re.compile(".*[._][Rr]?[2][_.].*") log = logging.getLogger("onecodex") def _check_for_ascii_filename(filename, co...
0.4206
0.176601
import time import board import neopixel import threading from datetime import datetime from gpiozero import Button from signal import pause #Setup the pin #GPIO.setmode(GPIO.BOARD) buttonPin = 16 # board.D23 button = Button(23) # Choose an open pin connected to the Data In of the NeoPixel strip, i.e. board.D18 # NeoP...
main.py
import time import board import neopixel import threading from datetime import datetime from gpiozero import Button from signal import pause #Setup the pin #GPIO.setmode(GPIO.BOARD) buttonPin = 16 # board.D23 button = Button(23) # Choose an open pin connected to the Data In of the NeoPixel strip, i.e. board.D18 # NeoP...
0.487795
0.418697
import os import sqlite3 import pandas as pd import pymongo from dotenv import load_dotenv ''' "How was working with MongoDB different from working with PostgreSQL? What was easier, and what was harder?" I would say that my biggest hurdle was simply figuring out how to get data into each system, once I was past that...
module3-nosql-and-document-oriented-databases/rpg_nosql.py
import os import sqlite3 import pandas as pd import pymongo from dotenv import load_dotenv ''' "How was working with MongoDB different from working with PostgreSQL? What was easier, and what was harder?" I would say that my biggest hurdle was simply figuring out how to get data into each system, once I was past that...
0.096153
0.254871
import abc import tensorflow as tf from tensor_annotations import tensorflow as ttf from tensor_annotations import axes from src.channelcoding.dataclasses import FixedPermuteInterleaverSettings, RandomPermuteInterleaverSettings from .codes import Code from .types import Batch, Time, Channels class Interleaver(Code...
turbo-codes/src/channelcoding/interleavers.py
import abc import tensorflow as tf from tensor_annotations import tensorflow as ttf from tensor_annotations import axes from src.channelcoding.dataclasses import FixedPermuteInterleaverSettings, RandomPermuteInterleaverSettings from .codes import Code from .types import Batch, Time, Channels class Interleaver(Code...
0.832271
0.249082
import getopt import os from os import path import sys import acg INDENT = ' ' def declare_namespaces(namespaces, source): return '\n'.join(['namespace %s {' % i for i in namespaces]) + '\n' + source + '\n' +'\n'.join(['}'] * len(namespaces)) def output_tofile(content, filename, outputdir): if outputd...
tools/python/gen_string_table.py
import getopt import os from os import path import sys import acg INDENT = ' ' def declare_namespaces(namespaces, source): return '\n'.join(['namespace %s {' % i for i in namespaces]) + '\n' + source + '\n' +'\n'.join(['}'] * len(namespaces)) def output_tofile(content, filename, outputdir): if outputd...
0.210442
0.096323
import numpy as np import pandas as pd from multiprocessing import Pool from scipy.special import expit from scipy.stats import beta from scipy.stats import powerlaw from opaque.betabinomial_regression import BetaBinomialRegressor from opaque.stats import equal_tailed_interval, KL_beta class EndtoEndSimulator: de...
opaque/simulations/end_to_end.py
import numpy as np import pandas as pd from multiprocessing import Pool from scipy.special import expit from scipy.stats import beta from scipy.stats import powerlaw from opaque.betabinomial_regression import BetaBinomialRegressor from opaque.stats import equal_tailed_interval, KL_beta class EndtoEndSimulator: de...
0.620507
0.40536
import json import string import sys from geopy.geocoders import Nominatim #Open a file with tweets and get the coordinates, if it's not null geolocator = Nominatim() file_list = ['stream_Alice.json', 'stream_Clank_2105.json', 'stream_deadpool0803.json', 'stream_deadpool1103.json', 'stream_deadpool.json', 'stream_De...
infoprocessing.py
import json import string import sys from geopy.geocoders import Nominatim #Open a file with tweets and get the coordinates, if it's not null geolocator = Nominatim() file_list = ['stream_Alice.json', 'stream_Clank_2105.json', 'stream_deadpool0803.json', 'stream_deadpool1103.json', 'stream_deadpool.json', 'stream_De...
0.077997
0.179297
from PIL import Image, ImageOps from pathlib import Path import os import json import re MISC_IDS = { (220, 255, 166, 255): 200, #Invisible Wall (Boundary) (128, 128, 128, 255): 206, #Surface 0 (100, 100, 100, 255): 206, #Surface 0 (204, 186, 143, 255): 206, #Surface 0 (204, 176, 143, ...
Starbound Dungeon Converter v2/SDVv2.py
from PIL import Image, ImageOps from pathlib import Path import os import json import re MISC_IDS = { (220, 255, 166, 255): 200, #Invisible Wall (Boundary) (128, 128, 128, 255): 206, #Surface 0 (100, 100, 100, 255): 206, #Surface 0 (204, 186, 143, 255): 206, #Surface 0 (204, 176, 143, ...
0.375936
0.117446
__author__ = 'carlos.diaz' # Autoencoder for the context data based on residual networks import numpy as np import matplotlib.pyplot as plt from torch import nn import torch import time import os import nde_utils import nde_ae from tqdm import tqdm import sys mdouble = False if mdouble is True: print('[INFO] Us...
nlte/AEcontext.py
__author__ = 'carlos.diaz' # Autoencoder for the context data based on residual networks import numpy as np import matplotlib.pyplot as plt from torch import nn import torch import time import os import nde_utils import nde_ae from tqdm import tqdm import sys mdouble = False if mdouble is True: print('[INFO] Us...
0.383526
0.294836
from oci_cli import cli_util from oci_cli.cli_util import option from oci_cli.aliasing import CommandGroupWithAlias from services.dns.src.oci_cli_dns.generated import dns_cli from oci_cli import json_skeleton_utils import click @dns_cli.dns_root_group.command('record', cls=CommandGroupWithAlias, help="""A DNS recor...
services/dns/src/oci_cli_dns/dns_cli_extended.py
from oci_cli import cli_util from oci_cli.cli_util import option from oci_cli.aliasing import CommandGroupWithAlias from services.dns.src.oci_cli_dns.generated import dns_cli from oci_cli import json_skeleton_utils import click @dns_cli.dns_root_group.command('record', cls=CommandGroupWithAlias, help="""A DNS recor...
0.549641
0.096238
from blackjack.card import Card from blackjack.deck import Deck from blackjack.player import Player class _Blackjack: def __init__(self, player: Player, dealer: Player, deck: Deck) -> None: """init""" self.player = player self.dealer = dealer self.deck = deck def _get_cards(se...
blackjack/blackjack.py
from blackjack.card import Card from blackjack.deck import Deck from blackjack.player import Player class _Blackjack: def __init__(self, player: Player, dealer: Player, deck: Deck) -> None: """init""" self.player = player self.dealer = dealer self.deck = deck def _get_cards(se...
0.724481
0.163612
from __future__ import print_function, division, absolute_import import os import pytest from sdss_brain import cfg_params from sdss_brain.auth import Netrc from sdss_brain.exceptions import BrainError @pytest.fixture() def netrc(monkeypatch, tmpdir): tmpnet = tmpdir.mkdir('netrc').join('.netrc') monkeypa...
tests/auth/test_netrc.py
from __future__ import print_function, division, absolute_import import os import pytest from sdss_brain import cfg_params from sdss_brain.auth import Netrc from sdss_brain.exceptions import BrainError @pytest.fixture() def netrc(monkeypatch, tmpdir): tmpnet = tmpdir.mkdir('netrc').join('.netrc') monkeypa...
0.553023
0.205555
import os import re from .single import FileSinglePermission, _BaseVariables class FileUserPermission(FileSinglePermission): """ Overview: Single permission of the user part of a file. Inherited from :class:`pysyslimit.models.permission.single.FileSinglePermission`. With re...
pysyslimit/models/permission/full.py
import os import re from .single import FileSinglePermission, _BaseVariables class FileUserPermission(FileSinglePermission): """ Overview: Single permission of the user part of a file. Inherited from :class:`pysyslimit.models.permission.single.FileSinglePermission`. With re...
0.734215
0.119229
try: from os import makedirs from shutil import copyfile from os.path import join, exists except ImportError as err: exit(err) if __name__ == "__main__": # The path to the directory where the original # dataset was uncompressed original_dataset_dir = "C:/Users/e_sgouge/Documents/Etienne/Pyt...
src/prepare_datasets/animals_data_preparation.py
try: from os import makedirs from shutil import copyfile from os.path import join, exists except ImportError as err: exit(err) if __name__ == "__main__": # The path to the directory where the original # dataset was uncompressed original_dataset_dir = "C:/Users/e_sgouge/Documents/Etienne/Pyt...
0.31237
0.319519
import enum import os import sys from typing import Optional import unittest sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) # pylint: disable=wrong-import-position import deserialize # pylint: enable=wrong-import-position class SomeStringEnum(enum.Enum): """Enum example.""" ...
tests/test_enums.py
import enum import os import sys from typing import Optional import unittest sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) # pylint: disable=wrong-import-position import deserialize # pylint: enable=wrong-import-position class SomeStringEnum(enum.Enum): """Enum example.""" ...
0.542863
0.245741
import numpy as np class CameraIntr(): def __init__(self, u0, v0, fx, fy, sk=0, dtype=np.float32): camera_xyz = np.array([ [fx, sk, u0], [0, fy, v0], [0, 0, 1], ], dtype=dtype).transpose() pull_back_xyz = np.array([ [1 / fx, 0, -u0 / fx], ...
src/detector/graphics/camera.py
import numpy as np class CameraIntr(): def __init__(self, u0, v0, fx, fy, sk=0, dtype=np.float32): camera_xyz = np.array([ [fx, sk, u0], [0, fy, v0], [0, 0, 1], ], dtype=dtype).transpose() pull_back_xyz = np.array([ [1 / fx, 0, -u0 / fx], ...
0.770206
0.344581