code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import maya.cmds
import maya.OpenMaya as OpenMaya
import IECore
import IECoreMaya
class MayaSceneTest( IECoreMaya.TestCase ) :
def setUp( self ) :
maya.cmds.file( new=True, f=True )
def testFileName( self ) :
scene = IECoreMaya.MayaScene()
self.assertRaises( RuntimeError, scene.fileName )
def testChi... | test/IECoreMaya/MayaSceneTest.py |
import maya.cmds
import maya.OpenMaya as OpenMaya
import IECore
import IECoreMaya
class MayaSceneTest( IECoreMaya.TestCase ) :
def setUp( self ) :
maya.cmds.file( new=True, f=True )
def testFileName( self ) :
scene = IECoreMaya.MayaScene()
self.assertRaises( RuntimeError, scene.fileName )
def testChi... | 0.311322 | 0.251492 |
import discord
from discord.ext.commands import Bot as BotBase
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from lib.bingo import Bingo
import asyncio
PREFIX = "-"
OWNER_IDS = []
class Bot(BotBase):
def __init__(self):
self.PREFIX = PREFIX
self.ready = False
self.guild = Non... | lib/bot/__init__.py | import discord
from discord.ext.commands import Bot as BotBase
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from lib.bingo import Bingo
import asyncio
PREFIX = "-"
OWNER_IDS = []
class Bot(BotBase):
def __init__(self):
self.PREFIX = PREFIX
self.ready = False
self.guild = Non... | 0.40251 | 0.105948 |
import osmnx as ox
import networkx as nx
import json
import shapely.wkt
from shapely.geometry import LineString
print('reading previous stage results')
with open('tmp/houseNodes.json', encoding='utf-8') as f:
houseRawNodes=json.load(f)
for house in houseRawNodes:
if type(house['geometry']) == str:
... | prepare/5_addFootprintsToGraph.py | import osmnx as ox
import networkx as nx
import json
import shapely.wkt
from shapely.geometry import LineString
print('reading previous stage results')
with open('tmp/houseNodes.json', encoding='utf-8') as f:
houseRawNodes=json.load(f)
for house in houseRawNodes:
if type(house['geometry']) == str:
... | 0.109849 | 0.394959 |
import sys
import logging
import argparse
import datetime
import pytz
import numpy as np
from icalendar import Calendar
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4, landscape
logger = logging.getLogger(__name__)
local_tz = pytz.timezone('Europe/Stockholm') # beware of daylight savin... | icalpdf.py | import sys
import logging
import argparse
import datetime
import pytz
import numpy as np
from icalendar import Calendar
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4, landscape
logger = logging.getLogger(__name__)
local_tz = pytz.timezone('Europe/Stockholm') # beware of daylight savin... | 0.191479 | 0.246947 |
from unipath import Path
from fabric.api import task, run, env, require, settings, hide, fastprint, get, put, prompt
from fabric.contrib.files import append, sed
from deploy import restart
@task(default=True)
def list():
"""
List remote configurations.
"""
require('PROJECT')
fastprint(run('cat %... | jetpack/config.py | from unipath import Path
from fabric.api import task, run, env, require, settings, hide, fastprint, get, put, prompt
from fabric.contrib.files import append, sed
from deploy import restart
@task(default=True)
def list():
"""
List remote configurations.
"""
require('PROJECT')
fastprint(run('cat %... | 0.471953 | 0.207395 |
import json
import tensorflow as tf
from transformers import DistilBertTokenizer
from datetime import datetime
review_body_column_idx_tsv = 13
classes=[1, 2, 3, 4, 5]
max_seq_length=128
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
def input_handler(data, context):
start_time = dat... | 09_deploy/wip/src_batch_tsv/inference.py | import json
import tensorflow as tf
from transformers import DistilBertTokenizer
from datetime import datetime
review_body_column_idx_tsv = 13
classes=[1, 2, 3, 4, 5]
max_seq_length=128
tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-uncased')
def input_handler(data, context):
start_time = dat... | 0.37399 | 0.180071 |
import json
import math
from google.appengine.api import search
"""
Limitations:
1. Providers can only enter a single territory whose set of points does not result in a radius larger than 250 m. So providers need to enter their territories in a piecemeal fashion.
2. When searching for a latitude and long... | api/geofencesearch.py | import json
import math
from google.appengine.api import search
"""
Limitations:
1. Providers can only enter a single territory whose set of points does not result in a radius larger than 250 m. So providers need to enter their territories in a piecemeal fashion.
2. When searching for a latitude and long... | 0.651244 | 0.819026 |
import abc
import copy
import warnings
from typing import Any, Dict, Optional, cast # noqa
import dataproperty
import typepy
from dataproperty import DataProperty
from tabledata import TableData
from typepy import Integer
from .._common import import_error_msg_template
from ._excel_workbook import ExcelWorkbookInter... | pytablewriter/writer/binary/_excel.py | import abc
import copy
import warnings
from typing import Any, Dict, Optional, cast # noqa
import dataproperty
import typepy
from dataproperty import DataProperty
from tabledata import TableData
from typepy import Integer
from .._common import import_error_msg_template
from ._excel_workbook import ExcelWorkbookInter... | 0.82755 | 0.286862 |
import unittest
from permadict import PermaDict
class PermaDictTests(unittest.TestCase):
"""Tests for PermaDict."""
def test_can_add_key(self):
d = PermaDict()
with self.assertRaises(KeyError):
d[4]
d[4] = "the number four"
self.assertEqual(d[4], "the number four... | 20-29/23. permadict/test_permadict.py | import unittest
from permadict import PermaDict
class PermaDictTests(unittest.TestCase):
"""Tests for PermaDict."""
def test_can_add_key(self):
d = PermaDict()
with self.assertRaises(KeyError):
d[4]
d[4] = "the number four"
self.assertEqual(d[4], "the number four... | 0.678007 | 0.745908 |
from typing import Optional
import pathlib
import datetime
import pandas as pd
from pydantic import validate_arguments, BaseModel
from dff.core import Context, Actor
from dff.core.types import ActorStage
class Stats(BaseModel):
csv_file: pathlib.Path
start_time: Optional[datetime.datetime] = None
dfs: l... | dff_node_stats/stats.py | from typing import Optional
import pathlib
import datetime
import pandas as pd
from pydantic import validate_arguments, BaseModel
from dff.core import Context, Actor
from dff.core.types import ActorStage
class Stats(BaseModel):
csv_file: pathlib.Path
start_time: Optional[datetime.datetime] = None
dfs: l... | 0.850841 | 0.185228 |
from dinopass.encryption import encrypt, decrypt
from dinopass.models import MasterPassword, Password
class PasswordViewMixin:
model = None
def __init__(self, db_session):
if not self.model:
raise NotImplementedError('Please specify a model!')
self._db_session = db_session
d... | dinopass/views.py | from dinopass.encryption import encrypt, decrypt
from dinopass.models import MasterPassword, Password
class PasswordViewMixin:
model = None
def __init__(self, db_session):
if not self.model:
raise NotImplementedError('Please specify a model!')
self._db_session = db_session
d... | 0.789153 | 0.153676 |
import json
import logging
from datetime import datetime
from pathlib import Path
from typing import Union
from game import Position
from game.client.controller.menu import Menu
from game.client.model.action import Action, ActionType, MoveAction, InventoryAction, ItemAction
from game.client.model.model import Model
fr... | game/client/controller/controller.py | import json
import logging
from datetime import datetime
from pathlib import Path
from typing import Union
from game import Position
from game.client.controller.menu import Menu
from game.client.model.action import Action, ActionType, MoveAction, InventoryAction, ItemAction
from game.client.model.model import Model
fr... | 0.412057 | 0.060947 |
import json
import hashlib
import os
import tarfile
import rocketbase.exceptions
# --- CONSTANTS ---
# List of all the required information
LIST_REQUIRED_INFO = [
'username',
'modelName',
'family',
'trainingDataset',
'isTrainable',
'rocketRepoUrl',
'originRepoUrl',
'description',
'... | rocketbase/utils.py | import json
import hashlib
import os
import tarfile
import rocketbase.exceptions
# --- CONSTANTS ---
# List of all the required information
LIST_REQUIRED_INFO = [
'username',
'modelName',
'family',
'trainingDataset',
'isTrainable',
'rocketRepoUrl',
'originRepoUrl',
'description',
'... | 0.717309 | 0.312632 |
import requests
import logging
import httplib2
# Console colors
W = '\033[0m' # white (normal)
R = '\033[31m' # red
G = '\033[32m' # green
class Humax():
def __init__(self, target_list):
self.target_list = target_list
self.findings =[]
def check_host(self, target, port):
"""
... | exploits/Humax_HG100R.py |
import requests
import logging
import httplib2
# Console colors
W = '\033[0m' # white (normal)
R = '\033[31m' # red
G = '\033[32m' # green
class Humax():
def __init__(self, target_list):
self.target_list = target_list
self.findings =[]
def check_host(self, target, port):
"""
... | 0.253306 | 0.105533 |
# Copyright: (c) 2020, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: tag
short_description: create tungsten... | plugins/modules/tag.py |
# Copyright: (c) 2020, <NAME> <<EMAIL>>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: tag
short_description: create tungsten... | 0.464902 | 0.16975 |
import os
from typing import Dict, Any
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(
os.path.dirname(os.path.abspath(os.path.join(__file__, "../")))
)
SHARED_URL = "https://shared.acdh.oeaw.ac.at/"
ACDH_IMPRINT_URL = "https://shared.acdh.oeaw.ac.at/acdh-commo... | apis/settings/base.py | import os
from typing import Dict, Any
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(
os.path.dirname(os.path.abspath(os.path.join(__file__, "../")))
)
SHARED_URL = "https://shared.acdh.oeaw.ac.at/"
ACDH_IMPRINT_URL = "https://shared.acdh.oeaw.ac.at/acdh-commo... | 0.518546 | 0.172416 |
import tensorflow as tf
import numpy as np
import io
import struct
import lzma
from ._bit_manipulation import BitsAccumulator, BitsReader
def _iter_max_size(values, max_value):
for v in values:
while v >= max_value:
yield max_value - 1
v -= max_value
yield v
def get_bits_... | nnet/compression/coding.py | import tensorflow as tf
import numpy as np
import io
import struct
import lzma
from ._bit_manipulation import BitsAccumulator, BitsReader
def _iter_max_size(values, max_value):
for v in values:
while v >= max_value:
yield max_value - 1
v -= max_value
yield v
def get_bits_... | 0.887443 | 0.661458 |
import pytest
from google import showcase
from google.rpc import error_details_pb2
from google.protobuf import any_pb2
from grpc_status import rpc_status
from google.api_core import exceptions
def create_status(error_details=None):
status = rpc_status.status_pb2.Status()
status.code = 3
status.message = ... | tests/system/test_error_details.py |
import pytest
from google import showcase
from google.rpc import error_details_pb2
from google.protobuf import any_pb2
from grpc_status import rpc_status
from google.api_core import exceptions
def create_status(error_details=None):
status = rpc_status.status_pb2.Status()
status.code = 3
status.message = ... | 0.326593 | 0.261941 |
from __future__ import absolute_import, division, print_function
from time import process_time
import energyflow as ef
import numpy as np
import matplotlib.pyplot as plt
class ParticleDistributionCMS:
def __init__(self, sim):
sim_numbers = set(sim.evns)
t1_start = process_time()
self.ev... | build/lib/particledist/ParticleDistributionCMS.py |
from __future__ import absolute_import, division, print_function
from time import process_time
import energyflow as ef
import numpy as np
import matplotlib.pyplot as plt
class ParticleDistributionCMS:
def __init__(self, sim):
sim_numbers = set(sim.evns)
t1_start = process_time()
self.ev... | 0.300027 | 0.211335 |
import asyncio
import math
import os
from collections import deque
from typing import List
import rplidar
from serial.tools import list_ports
from highlevel.adapter.http import HTTPClient
from highlevel.adapter.lidar import LIDARAdapter
from highlevel.adapter.lidar.rplidar import RPLIDARAdapter
from highlevel.adapter... | highlevel/main.py | import asyncio
import math
import os
from collections import deque
from typing import List
import rplidar
from serial.tools import list_ports
from highlevel.adapter.http import HTTPClient
from highlevel.adapter.lidar import LIDARAdapter
from highlevel.adapter.lidar.rplidar import RPLIDARAdapter
from highlevel.adapter... | 0.578686 | 0.190611 |
import sys
import matplotlib
import wx
matplotlib.use("WXAgg")
matplotlib.rcParams['toolbar'] = 'None'
import matplotlib.pyplot as plt
import pylab
import btceapi
class Chart(object):
def __init__(self, symbol):
self.symbol = symbol
self.base = symbol.split("_")[0].upper()
self.alt = s... | samples/watch.py | import sys
import matplotlib
import wx
matplotlib.use("WXAgg")
matplotlib.rcParams['toolbar'] = 'None'
import matplotlib.pyplot as plt
import pylab
import btceapi
class Chart(object):
def __init__(self, symbol):
self.symbol = symbol
self.base = symbol.split("_")[0].upper()
self.alt = s... | 0.38168 | 0.203411 |
import time
import zmq
import hashlib
import os
import json
NAME_DATAFILE = "dataFiles.json" #Json que mapea hash global con lista de hashes
information_dict = {}
NAME_NAMEFILES = "nameFiles.json" #Json que mapea nombre con hash global
names_dict = {}
with open(NAME_DATAFILE, "r") as dataFiles:
information_dic... | manejador_archivos/manejador_archivos_CS/servidor/server.py | import time
import zmq
import hashlib
import os
import json
NAME_DATAFILE = "dataFiles.json" #Json que mapea hash global con lista de hashes
information_dict = {}
NAME_NAMEFILES = "nameFiles.json" #Json que mapea nombre con hash global
names_dict = {}
with open(NAME_DATAFILE, "r") as dataFiles:
information_dic... | 0.029396 | 0.08141 |
import os
COWIN_URL = os.getenv('COWIN_URL')
STATES_URL = f'{COWIN_URL}admin/location/states/'
DISTRICTS_URL = f'{COWIN_URL}admin/location/districts/'
CALENDAR_BY_DISTRICT_PUBLIC_URL = f'{COWIN_URL}appointment/sessions/public/calendarByDistrict/'
CALENDAR_BY_DISTRICT_URL = f'{COWIN_URL}appointment/sessions/calendarByD... | helpers/constants.py | import os
COWIN_URL = os.getenv('COWIN_URL')
STATES_URL = f'{COWIN_URL}admin/location/states/'
DISTRICTS_URL = f'{COWIN_URL}admin/location/districts/'
CALENDAR_BY_DISTRICT_PUBLIC_URL = f'{COWIN_URL}appointment/sessions/public/calendarByDistrict/'
CALENDAR_BY_DISTRICT_URL = f'{COWIN_URL}appointment/sessions/calendarByD... | 0.182025 | 0.056574 |
import os
from engines import peregrinbase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class SeleniumWebForm(peregrinbase.PeregrinBase):
"""This will read an RSS feed and save the data to
Peregrin DB"""
def __init__(self):
super().__init__()
self._title = ... | engines/seleniumwebform.py | import os
from engines import peregrinbase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
class SeleniumWebForm(peregrinbase.PeregrinBase):
"""This will read an RSS feed and save the data to
Peregrin DB"""
def __init__(self):
super().__init__()
self._title = ... | 0.349311 | 0.075961 |
import pprint
import re # noqa: F401
import six
class Member(object):
"""
Attributes:
mx_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in... | atrium/models/member.py | import pprint
import re # noqa: F401
import six
class Member(object):
"""
Attributes:
mx_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in... | 0.543106 | 0.115511 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .resnet import BasicBlock
class ResNet_cifar10_nofc(nn.Module):
def __init__(self, block, num_layers, num_classes=10):
super(ResNet_cifar10_nofc, self).__init__()
self.in_planes = 16
if (num_layers-2) % 6 == 0:
... | models/resnet_cifar10_nofc.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from .resnet import BasicBlock
class ResNet_cifar10_nofc(nn.Module):
def __init__(self, block, num_layers, num_classes=10):
super(ResNet_cifar10_nofc, self).__init__()
self.in_planes = 16
if (num_layers-2) % 6 == 0:
... | 0.911888 | 0.434581 |
import tarfile
from nnabla import random
from nnabla.logger import logger
from nnabla.utils.data_iterator import data_iterator
from nnabla.utils.data_source import DataSource
from nnabla.utils.data_source_loader import download
import numpy as np
from sklearn.model_selection import train_test_split
from .dataloader ... | nnabla_nas/dataset/cifar10.py |
import tarfile
from nnabla import random
from nnabla.logger import logger
from nnabla.utils.data_iterator import data_iterator
from nnabla.utils.data_source import DataSource
from nnabla.utils.data_source_loader import download
import numpy as np
from sklearn.model_selection import train_test_split
from .dataloader ... | 0.81593 | 0.519765 |
import json
import base64
import jwt.exceptions
from django.test import TestCase
from rest_framework_jwt import utils
from rest_framework_jwt.compat import get_user_model
from rest_framework_jwt.settings import api_settings, DEFAULTS
User = get_user_model()
def base64url_decode(input):
rem = len(input) % 4
... | tests/test_utils.py | import json
import base64
import jwt.exceptions
from django.test import TestCase
from rest_framework_jwt import utils
from rest_framework_jwt.compat import get_user_model
from rest_framework_jwt.settings import api_settings, DEFAULTS
User = get_user_model()
def base64url_decode(input):
rem = len(input) % 4
... | 0.427994 | 0.149625 |
"""Registry responsible for built-in keras classes."""
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow_model_optimization.python.core.clustering.keras import clustering_registry
from tensorflow_model_optimization.python.core.quantization.keras import quant_ops
from tensorflow_model_o... | tensorflow_model_optimization/python/core/quantization/keras/collaborative_optimizations/cluster_preserve/cluster_preserve_quantize_registry.py | """Registry responsible for built-in keras classes."""
import tensorflow as tf
from tensorflow.keras import backend as K
from tensorflow_model_optimization.python.core.clustering.keras import clustering_registry
from tensorflow_model_optimization.python.core.quantization.keras import quant_ops
from tensorflow_model_o... | 0.965479 | 0.404008 |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from math import floor, log
import os
output_dir = "output/"
# 处理数据 x
def dataProcess_X(rawData):
#sex 只有两个属性 先drop之后处理
if "income" in rawData.columns:
Data = rawData.drop(["sex", 'income'], axis=1)
else:
Data = rawData... | EX3/lr.py | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from math import floor, log
import os
output_dir = "output/"
# 处理数据 x
def dataProcess_X(rawData):
#sex 只有两个属性 先drop之后处理
if "income" in rawData.columns:
Data = rawData.drop(["sex", 'income'], axis=1)
else:
Data = rawData... | 0.326057 | 0.536677 |
import argparse
import re
import dockerbackuputils
from dockerbackuputils import *
#volumeBackup() function takes arguments and options parsed from cli and executes appropriate volume backup
#(i.e. full, only-running or only for provided list)
def volumeBackup(args):
if args.full:
cList = getContainerList... | apps/docker_backup.py | import argparse
import re
import dockerbackuputils
from dockerbackuputils import *
#volumeBackup() function takes arguments and options parsed from cli and executes appropriate volume backup
#(i.e. full, only-running or only for provided list)
def volumeBackup(args):
if args.full:
cList = getContainerList... | 0.252016 | 0.085595 |
from insights.parsers import qpid_stat
from insights.tests import context_wrap
import doctest
QPID_STAT_Q_DOCS = '''
Queues
queue dur autoDel excl msg msgIn msgOut bytes bytesIn bytesOut cons bind
======================================... | insights/parsers/tests/test_qpid_stat.py | from insights.parsers import qpid_stat
from insights.tests import context_wrap
import doctest
QPID_STAT_Q_DOCS = '''
Queues
queue dur autoDel excl msg msgIn msgOut bytes bytesIn bytesOut cons bind
======================================... | 0.380068 | 0.27594 |
from typing import Any, Dict, List # pylint: disable=unused-import
from gcp_variant_transforms.beam_io import vcfio
from gcp_variant_transforms.libs.annotation import annotation_parser
from gcp_variant_transforms.libs import bigquery_schema_descriptor # pylint: disable=unused-import
from gcp_variant_transforms.libs ... | gcp_variant_transforms/libs/bigquery_vcf_data_converter.py | from typing import Any, Dict, List # pylint: disable=unused-import
from gcp_variant_transforms.beam_io import vcfio
from gcp_variant_transforms.libs.annotation import annotation_parser
from gcp_variant_transforms.libs import bigquery_schema_descriptor # pylint: disable=unused-import
from gcp_variant_transforms.libs ... | 0.911468 | 0.276562 |
import email
import json
import logging
import os
import re
import boto3
from botocore.exceptions import ClientError
# FORWARD_MAPPING = {recipient: os.environ.get('MSG_TO_LIST') for recipient in os.environ.get('MSG_TARGET')}
with open('mapping.json', 'r') as f:
FORWARD_MAPPING = json.load(f)
VERIFIED_FROM_EMAI... | handler.py | import email
import json
import logging
import os
import re
import boto3
from botocore.exceptions import ClientError
# FORWARD_MAPPING = {recipient: os.environ.get('MSG_TO_LIST') for recipient in os.environ.get('MSG_TARGET')}
with open('mapping.json', 'r') as f:
FORWARD_MAPPING = json.load(f)
VERIFIED_FROM_EMAI... | 0.332961 | 0.054879 |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import sys
import seaborn as sns
import pandas as pd
import scipy.stats as ss
import numpy as np
import random
from collections import defaultdict, OrderedDict
from extract_arrays import extract_arrays, get_refseq, create_random_arrays
import argpa... | array_combinations.py | import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import sys
import seaborn as sns
import pandas as pd
import scipy.stats as ss
import numpy as np
import random
from collections import defaultdict, OrderedDict
from extract_arrays import extract_arrays, get_refseq, create_random_arrays
import argpa... | 0.320928 | 0.456289 |
import unittest
from app.main.searcher import Search
from app.main.loc_types import Point, PointWithDistance
class TestSearcher(unittest.TestCase):
def test_on_empty_list_circle(self):
self.assertEqual(Search.search_points(Point("", 46.483264729155586, 30.731506347656254), 3, []), [])
def test_with_... | app/test/test_searcher.py | import unittest
from app.main.searcher import Search
from app.main.loc_types import Point, PointWithDistance
class TestSearcher(unittest.TestCase):
def test_on_empty_list_circle(self):
self.assertEqual(Search.search_points(Point("", 46.483264729155586, 30.731506347656254), 3, []), [])
def test_with_... | 0.566858 | 0.479869 |
import math
import numpy as np
import matplotlib.pyplot as plt
def power(delta_t, sigma, T, xi, eps_s, L_s, output = "all"):
"""
Calculate work, power and current.
- output: defines what is the function output (Power or all)
"""
sigma_o = 100e6
r = 0.00025
d = 2*r
T_o = 200.
... | dynamic_model/power_usage.py | import math
import numpy as np
import matplotlib.pyplot as plt
def power(delta_t, sigma, T, xi, eps_s, L_s, output = "all"):
"""
Calculate work, power and current.
- output: defines what is the function output (Power or all)
"""
sigma_o = 100e6
r = 0.00025
d = 2*r
T_o = 200.
... | 0.439386 | 0.524456 |
import voluptuous as v
from nodepool.driver import ConfigPool
from nodepool.driver import ProviderConfig
from nodepool.config import as_list
class StaticPool(ConfigPool):
def __init__(self):
self.name = None
self.nodes = []
# The StaticProviderConfig that owns this pool.
self.pro... | nodepool/driver/static/config.py |
import voluptuous as v
from nodepool.driver import ConfigPool
from nodepool.driver import ProviderConfig
from nodepool.config import as_list
class StaticPool(ConfigPool):
def __init__(self):
self.name = None
self.nodes = []
# The StaticProviderConfig that owns this pool.
self.pro... | 0.667798 | 0.113924 |
import os
import glob
from datetime import datetime,date
import random
import itertools
import pickle
import time
import requests
from bs4 import BeautifulSoup
import re
import nltk
from nltk.corpus import names
from nltk.tokenize import RegexpTokenizer
from sklearn.feature_extraction.stop_words import ENGLISH_STOP_... | utils.py |
import os
import glob
from datetime import datetime,date
import random
import itertools
import pickle
import time
import requests
from bs4 import BeautifulSoup
import re
import nltk
from nltk.corpus import names
from nltk.tokenize import RegexpTokenizer
from sklearn.feature_extraction.stop_words import ENGLISH_STOP_... | 0.328099 | 0.154089 |
import os
import sys
import html
import logging
import pandas as pd
from json import JSONDecodeError
from pathlib import Path
import streamlit as st
from annotated_text import annotation
from markdown import markdown
from htbuilder import H
# streamlit does not support any states out of the box. On every button click... | ui/webapp.py | import os
import sys
import html
import logging
import pandas as pd
from json import JSONDecodeError
from pathlib import Path
import streamlit as st
from annotated_text import annotation
from markdown import markdown
from htbuilder import H
# streamlit does not support any states out of the box. On every button click... | 0.396419 | 0.194731 |
from asyncio.log import logger
from ticker_scraper.items import CompanyItem
# Python
import json
import logging
# Scrapy
import scrapy
# --------------------------------------------------------------------------------------------------------------
class InfoSpider(scrapy.Spider):
'''
Spider in charge to ... | ticker_scraper/ticker_scraper/spiders/info.py | from asyncio.log import logger
from ticker_scraper.items import CompanyItem
# Python
import json
import logging
# Scrapy
import scrapy
# --------------------------------------------------------------------------------------------------------------
class InfoSpider(scrapy.Spider):
'''
Spider in charge to ... | 0.350866 | 0.202542 |
import plotly
import plotly.graph_objs as pgo
import numpy as np
pl_BrBG = [
[0.0, "rgb(84, 48, 5)"],
[0.1, "rgb(138, 80, 9)"],
[0.2, "rgb(191, 129, 45)"],
[0.3, "rgb(222, 192, 123)"],
[0.4, "rgb(246, 232, 195)"],
[0.5, "rgb(244, 244, 244)"],
[0.6, "rgb(199, 234, 229)"],
[0.7, "rgb(126,... | slice3d.py | import plotly
import plotly.graph_objs as pgo
import numpy as np
pl_BrBG = [
[0.0, "rgb(84, 48, 5)"],
[0.1, "rgb(138, 80, 9)"],
[0.2, "rgb(191, 129, 45)"],
[0.3, "rgb(222, 192, 123)"],
[0.4, "rgb(246, 232, 195)"],
[0.5, "rgb(244, 244, 244)"],
[0.6, "rgb(199, 234, 229)"],
[0.7, "rgb(126,... | 0.771069 | 0.518485 |
__author__ = '<NAME>'
__version__ = '2.1.8'
__date__ = 'May 17 2010'
import threading
from ctypes import *
from Phidgets.PhidgetLibrary import PhidgetLibrary
from Phidgets.Phidget import Phidget
from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException
from Phidgets.Events.Events import Curren... | contrib/Phidgets/Devices/AdvancedServo.py | __author__ = '<NAME>'
__version__ = '2.1.8'
__date__ = 'May 17 2010'
import threading
from ctypes import *
from Phidgets.PhidgetLibrary import PhidgetLibrary
from Phidgets.Phidget import Phidget
from Phidgets.PhidgetException import PhidgetErrorCodes, PhidgetException
from Phidgets.Events.Events import Curren... | 0.536799 | 0.110904 |
import os
import json
from tkinter import *
import numpy as np
import cv2
from PIL import Image
from PIL import ImageTk
__author__ = "SumiGovindaraju"
__copyright__ = "Copyright 2018, SumiGovindaraju"
__credits__ = ["SumiGovindaraju"]
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "SumiGovindaraju"
__statu... | tuner.py | import os
import json
from tkinter import *
import numpy as np
import cv2
from PIL import Image
from PIL import ImageTk
__author__ = "SumiGovindaraju"
__copyright__ = "Copyright 2018, SumiGovindaraju"
__credits__ = ["SumiGovindaraju"]
__license__ = "MIT"
__version__ = "1.0.0"
__maintainer__ = "SumiGovindaraju"
__statu... | 0.401805 | 0.12544 |
import numpy as np
from glob import glob
from mpi4py import MPI
from nematic_sma_OP import PO
rank = MPI.COMM_WORLD.Get_rank()
nprocs = MPI.COMM_WORLD.Get_size()
first_frame = -2500
last_frame = -1
def open_trajectory(nprocs, rank, first_frame, last_frame, wrap=False, visualize=False, ini_layer_spacing=27.,
... | dataAnalysis/op_traj_mpi.py | import numpy as np
from glob import glob
from mpi4py import MPI
from nematic_sma_OP import PO
rank = MPI.COMM_WORLD.Get_rank()
nprocs = MPI.COMM_WORLD.Get_size()
first_frame = -2500
last_frame = -1
def open_trajectory(nprocs, rank, first_frame, last_frame, wrap=False, visualize=False, ini_layer_spacing=27.,
... | 0.788909 | 0.468851 |
import copy
class WeightedUndirectedGraph(object):
'''
An object that records a weighted undirected graph
Members
-------
WeightedUndirectedGraph._graph: dict of dict, the graph;
WeightedUndirectedGraph._degree: the precomputed weighted degree of each node in the graph;
WeightedUndire... | Labs/Lab3/community/graphx.py | import copy
class WeightedUndirectedGraph(object):
'''
An object that records a weighted undirected graph
Members
-------
WeightedUndirectedGraph._graph: dict of dict, the graph;
WeightedUndirectedGraph._degree: the precomputed weighted degree of each node in the graph;
WeightedUndire... | 0.931711 | 0.703906 |
import arcpy
import sys
from os.path import join
arcpy.env.geographicTransformations = 'NAD_1983_to_WGS_1984_5'
try:
base_folder = sys.argv[1]
except:
base_folder = raw_input('base folder: ')
print('creating new database')
new_db = base_folder + 'QueryLayers_NEW.gdb'
old_db = base_folder + 'QueryLayers.gdb'
... | scripts/reprojectDB.py | import arcpy
import sys
from os.path import join
arcpy.env.geographicTransformations = 'NAD_1983_to_WGS_1984_5'
try:
base_folder = sys.argv[1]
except:
base_folder = raw_input('base folder: ')
print('creating new database')
new_db = base_folder + 'QueryLayers_NEW.gdb'
old_db = base_folder + 'QueryLayers.gdb'
... | 0.155046 | 0.082438 |
example_grid = [
[5,0,0,0,0,7,0,0,0]
,[9,2,6,5,0,0,0,0,0]
,[3,0,0,8,0,9,0,2,0]
,[4,0,0,0,2,0,0,3,5]
,[0,3,5,1,0,4,9,7,0]
,[8,6,0,0,5,0,0,0,4]
,[0,4,0,3,0,8,0,0,2]
,[0,0,0,0,0,5,6,9,3]
,[0,0,0,6,0,0,0,0,7]]
def print_grid(grid):
for row in gri... | sudoku/solver/pencil_marks.py | example_grid = [
[5,0,0,0,0,7,0,0,0]
,[9,2,6,5,0,0,0,0,0]
,[3,0,0,8,0,9,0,2,0]
,[4,0,0,0,2,0,0,3,5]
,[0,3,5,1,0,4,9,7,0]
,[8,6,0,0,5,0,0,0,4]
,[0,4,0,3,0,8,0,0,2]
,[0,0,0,0,0,5,6,9,3]
,[0,0,0,6,0,0,0,0,7]]
def print_grid(grid):
for row in gri... | 0.284974 | 0.278187 |
import collections
import os
import attrdict
import jax
import jax.numpy as jnp
import jax.scipy as jsp
import numpy as np
import scipy.io
import scipy.linalg
from scipy import optimize
import riccati
jax.config.update("jax_enable_x64", True)
class Decision:
"""Decision variable specification."""
def __i... | attas_sp.py | import collections
import os
import attrdict
import jax
import jax.numpy as jnp
import jax.scipy as jsp
import numpy as np
import scipy.io
import scipy.linalg
from scipy import optimize
import riccati
jax.config.update("jax_enable_x64", True)
class Decision:
"""Decision variable specification."""
def __i... | 0.7413 | 0.398289 |
import sys
import pandas as pd
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
"""Loads the messages and categories data sets and merges them based
on the id.
Args:
messages_filepath (str): file path of messages csv file
categories_... | data/process_data.py | import sys
import pandas as pd
from sqlalchemy import create_engine
def load_data(messages_filepath, categories_filepath):
"""Loads the messages and categories data sets and merges them based
on the id.
Args:
messages_filepath (str): file path of messages csv file
categories_... | 0.630912 | 0.553867 |
import sys
import os
import re
import numpy as np
import tensorflow as tf
def print_(str, colour='', bold=False):
if colour == 'w': # yellow warning
sys.stdout.write('\033[93m')
elif colour == "e": # red error
sys.stdout.write('\033[91m')
elif colour == "m": # magenta info
sys.stdo... | Models/classTemplateTF/util/util.py | import sys
import os
import re
import numpy as np
import tensorflow as tf
def print_(str, colour='', bold=False):
if colour == 'w': # yellow warning
sys.stdout.write('\033[93m')
elif colour == "e": # red error
sys.stdout.write('\033[91m')
elif colour == "m": # magenta info
sys.stdo... | 0.355216 | 0.154089 |
from oslo_config import cfg
from oslo_log import log
from oslo_serialization import jsonutils
from watcher.common import exception
from watcher.decision_engine.datasources.grafana_translator.base import \
BaseGrafanaTranslator
CONF = cfg.CONF
LOG = log.getLogger(__name__)
class InfluxDBGrafanaTranslator(BaseGr... | watcher/decision_engine/datasources/grafana_translator/influxdb.py |
from oslo_config import cfg
from oslo_log import log
from oslo_serialization import jsonutils
from watcher.common import exception
from watcher.decision_engine.datasources.grafana_translator.base import \
BaseGrafanaTranslator
CONF = cfg.CONF
LOG = log.getLogger(__name__)
class InfluxDBGrafanaTranslator(BaseGr... | 0.503418 | 0.252908 |
import logging
import os
from django.core.files.base import ContentFile
from django.utils.timezone import now
from django.utils.translation import gettext as _
from django_scopes import scopes_disabled
from pretix.base.i18n import language
from pretix.base.models import (
CachedCombinedTicket, CachedTicket, Event... | src/pretix/base/services/tickets.py | import logging
import os
from django.core.files.base import ContentFile
from django.utils.timezone import now
from django.utils.translation import gettext as _
from django_scopes import scopes_disabled
from pretix.base.i18n import language
from pretix.base.models import (
CachedCombinedTicket, CachedTicket, Event... | 0.375363 | 0.086593 |
from abc import ABC, abstractmethod
from time import time
import numpy as np
from tick.base import Base
class Simu(ABC, Base):
"""
Abstract simulation class. It does nothing besides printing and
verbosing.
Parameters
----------
seed : `int`
The seed of the random number generator
... | tick/base/simulation/simu.py |
from abc import ABC, abstractmethod
from time import time
import numpy as np
from tick.base import Base
class Simu(ABC, Base):
"""
Abstract simulation class. It does nothing besides printing and
verbosing.
Parameters
----------
seed : `int`
The seed of the random number generator
... | 0.848282 | 0.475118 |
from __future__ import absolute_import
import collections
from functools import reduce
import numpy as np
import oneflow as flow
import oneflow_api
from google.protobuf import text_format
from oneflow.python.framework.dtype import convert_proto_dtype_to_oneflow_dtype
from oneflow.python.lib.core.box import Box
clas... | oneflow/python/framework/ofblob.py | from __future__ import absolute_import
import collections
from functools import reduce
import numpy as np
import oneflow as flow
import oneflow_api
from google.protobuf import text_format
from oneflow.python.framework.dtype import convert_proto_dtype_to_oneflow_dtype
from oneflow.python.lib.core.box import Box
clas... | 0.606382 | 0.48438 |
import os
import open3d as o3d
import numpy as np
import copy
import json
from math import *
from PyQt5.QtCore import *
from utils.util_func import transform_coordinates_3d, Scaling
from utils.axis_aligner import AxisAligner
from utils.part_segmentator import PartSegmentator
from utils.joint_annotator import JointAnno... | annotator_window.py | import os
import open3d as o3d
import numpy as np
import copy
import json
from math import *
from PyQt5.QtCore import *
from utils.util_func import transform_coordinates_3d, Scaling
from utils.axis_aligner import AxisAligner
from utils.part_segmentator import PartSegmentator
from utils.joint_annotator import JointAnno... | 0.403097 | 0.118819 |
from django.test import SimpleTestCase
from corehq.apps.app_manager.models import SortElement
from corehq.apps.app_manager.tests.app_factory import AppFactory
from corehq.apps.app_manager.tests.util import TestXmlMixin
class CaseDetailDistance(SimpleTestCase, TestXmlMixin):
def setUp(self):
self.factory... | corehq/apps/app_manager/tests/test_case_detail_distance.py | from django.test import SimpleTestCase
from corehq.apps.app_manager.models import SortElement
from corehq.apps.app_manager.tests.app_factory import AppFactory
from corehq.apps.app_manager.tests.util import TestXmlMixin
class CaseDetailDistance(SimpleTestCase, TestXmlMixin):
def setUp(self):
self.factory... | 0.470007 | 0.227931 |
import numpy as np
import tensorflow as tf
from util.camera import camera_from_blender, quaternion_from_campos
def pool_single_view(cfg, tensor, view_idx):
indices = tf.range(cfg.batch_size) * cfg.step_size + view_idx
indices = tf.expand_dims(indices, axis=-1)
return tf.gather_nd(tensor, indices)
class... | drwr/data_base/data_base.py | import numpy as np
import tensorflow as tf
from util.camera import camera_from_blender, quaternion_from_campos
def pool_single_view(cfg, tensor, view_idx):
indices = tf.range(cfg.batch_size) * cfg.step_size + view_idx
indices = tf.expand_dims(indices, axis=-1)
return tf.gather_nd(tensor, indices)
class... | 0.841956 | 0.323353 |
"""Find the passed in instance id and see if it is a CE migration"""
from __future__ import annotations
import json
import os
from typing import Any, Dict
import boto3
from migrationstate import MigrationStateHandler
print("Loading function find_instance")
ec2_resource = boto3.resource("ec2")
sqs = boto3.client("sq... | step/lambdas/find_instance.py | """Find the passed in instance id and see if it is a CE migration"""
from __future__ import annotations
import json
import os
from typing import Any, Dict
import boto3
from migrationstate import MigrationStateHandler
print("Loading function find_instance")
ec2_resource = boto3.resource("ec2")
sqs = boto3.client("sq... | 0.524151 | 0.290477 |
from rqalpha.api import *
import talib
from rqalpha import run_func
import numpy as np
import datetime
"""
Bar(symbol: u'\u73e0\u6c5f\u94a2\u7434', order_book_id: u'002678.XSHE', datetime: datetime.datetime(2014, 1, 2, 0, 0),
open: 7.08, close: 7.07, high: 7.14, low: 7.03, volume: 3352317.0, total_turnover: 23756852,... | rqalpha/examples/close_price_week.py |
from rqalpha.api import *
import talib
from rqalpha import run_func
import numpy as np
import datetime
"""
Bar(symbol: u'\u73e0\u6c5f\u94a2\u7434', order_book_id: u'002678.XSHE', datetime: datetime.datetime(2014, 1, 2, 0, 0),
open: 7.08, close: 7.07, high: 7.14, low: 7.03, volume: 3352317.0, total_turnover: 23756852,... | 0.2587 | 0.261696 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
from tensorflow_gan.examples.stargan import layers
from tensorflow_gan.examples.stargan import ops
def generator(inputs, targets):
"""Generator module.
Piece everything... | tensorflow_gan/examples/stargan/network.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.compat.v1 as tf
from tensorflow_gan.examples.stargan import layers
from tensorflow_gan.examples.stargan import ops
def generator(inputs, targets):
"""Generator module.
Piece everything... | 0.945343 | 0.441011 |
import tensorflow as tf
from poda.layers.merge import *
from poda.layers.dense import *
from poda.layers.activation import *
from poda.layers.regularizer import *
from poda.layers.convolutional import *
class VGG16(object):
def __init__(self, input_tensor, num_blocks=5, classes=1000, batch_normalizations = True, n... | poda/transfer_learning/Vgg16.py | import tensorflow as tf
from poda.layers.merge import *
from poda.layers.dense import *
from poda.layers.activation import *
from poda.layers.regularizer import *
from poda.layers.convolutional import *
class VGG16(object):
def __init__(self, input_tensor, num_blocks=5, classes=1000, batch_normalizations = True, n... | 0.867934 | 0.52902 |
import logging
import os
import time
import fabric.api
import fabric.operations
import cloudenvy.core
class Provision(cloudenvy.core.Command):
def _build_subparser(self, subparsers):
help_str = 'Upload and execute script(s) in your Envy.'
subparser = subparsers.add_parser('provision', help=help... | cloudenvy/commands/provision.py | import logging
import os
import time
import fabric.api
import fabric.operations
import cloudenvy.core
class Provision(cloudenvy.core.Command):
def _build_subparser(self, subparsers):
help_str = 'Upload and execute script(s) in your Envy.'
subparser = subparsers.add_parser('provision', help=help... | 0.279238 | 0.06148 |
from django.http import HttpRequest, QueryDict
from djtables.table import Table
from djtables.column import Column
DATA = [
{'name': "Leonardo", 'weapon': "Katana" },
{'name': "Michelangelo", 'weapon': "Nunchaku"},
{'name': "Donatello", 'weapon': "Bo Staff"},
{'name': "Raphael", 'weapon... | tests/test_table.py |
from django.http import HttpRequest, QueryDict
from djtables.table import Table
from djtables.column import Column
DATA = [
{'name': "Leonardo", 'weapon': "Katana" },
{'name': "Michelangelo", 'weapon': "Nunchaku"},
{'name': "Donatello", 'weapon': "Bo Staff"},
{'name': "Raphael", 'weapon... | 0.610453 | 0.439928 |
from __future__ import unicode_literals
from django.test import TestCase
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from powerpages.models import Page
from powerpages.sync import PageFileDumper
from powerpages.admin import website_link, s... | powerpages/tests/test_admin.py |
from __future__ import unicode_literals
from django.test import TestCase
from django.conf import settings
from django.core.urlresolvers import reverse
from django.contrib.auth.models import User
from powerpages.models import Page
from powerpages.sync import PageFileDumper
from powerpages.admin import website_link, s... | 0.521227 | 0.306947 |
from typing import List, Set, Dict, Tuple
import csv
import os
import json
import time
import datetime
Table = List[str]
Index = Dict[str, List[int]]
Fuzzy = Dict[str, List[str]]
ROOT_PATH = "C:/Arcology/AeonDB"
TABLE_DIR = "C:/Arcology/AeonDB/%s"
TABLE_PATH = "C:/Arcology/AeonDB/%s/table.txt"
INDEX_PATH = "C:/Arcolo... | PyAeonDB/PyAeonDB.py | from typing import List, Set, Dict, Tuple
import csv
import os
import json
import time
import datetime
Table = List[str]
Index = Dict[str, List[int]]
Fuzzy = Dict[str, List[str]]
ROOT_PATH = "C:/Arcology/AeonDB"
TABLE_DIR = "C:/Arcology/AeonDB/%s"
TABLE_PATH = "C:/Arcology/AeonDB/%s/table.txt"
INDEX_PATH = "C:/Arcolo... | 0.395718 | 0.168344 |
from datetime import datetime
import glob
import logging
import os
from pydoc import locate
import shutil
import sys
import time
from pytz import timezone
from diplomacy_research.models.datasets.base_builder import BaseBuilder
# Constants
LOGGER = logging.getLogger(__name__)
MODEL_PATHS = {'/token_based/v': 'diplomacy... | diplomacy_research/utils/checkpoint.py | from datetime import datetime
import glob
import logging
import os
from pydoc import locate
import shutil
import sys
import time
from pytz import timezone
from diplomacy_research.models.datasets.base_builder import BaseBuilder
# Constants
LOGGER = logging.getLogger(__name__)
MODEL_PATHS = {'/token_based/v': 'diplomacy... | 0.720172 | 0.175432 |
import toppra as ta
import toppra.constraint as constraint
import toppra.algorithm as algo
import numpy as np
import matplotlib.pyplot as plt
import argparse
def main():
parser = argparse.ArgumentParser(description="An example showcasing the usage of robust constraints."
... | examples/robust_kinematics.py | import toppra as ta
import toppra.constraint as constraint
import toppra.algorithm as algo
import numpy as np
import matplotlib.pyplot as plt
import argparse
def main():
parser = argparse.ArgumentParser(description="An example showcasing the usage of robust constraints."
... | 0.738198 | 0.423995 |
import argparse
import pandas as pd
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Check for missing colors & locations",
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('--metadata', type=str, nargs='+', required=True, help="input re... | scripts/check_missing_locations.py | import argparse
import pandas as pd
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description="Check for missing colors & locations",
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('--metadata', type=str, nargs='+', required=True, help="input re... | 0.300951 | 0.21162 |
import dataclasses
import io
import logging
from collections import namedtuple
from decimal import Decimal
from difflib import ndiff
from pathlib import Path
from typing import Any, Callable, DefaultDict, Iterator, List, Optional, Set, Union
import click
import pytest
from rich.console import Console, RenderableType
f... | neuro-cli/tests/unit/conftest.py | import dataclasses
import io
import logging
from collections import namedtuple
from decimal import Decimal
from difflib import ndiff
from pathlib import Path
from typing import Any, Callable, DefaultDict, Iterator, List, Optional, Set, Union
import click
import pytest
from rich.console import Console, RenderableType
f... | 0.610918 | 0.205456 |
import inspect
import io
from abc import ABCMeta, abstractmethod
from PySide.QtGui import QApplication
if __package__:
from . import functions
else:
import functions
class TemplateError(Exception):
pass
class Renderable(metaclass=ABCMeta):
@abstractmethod
def render(self, context):
pas... | qygmy/templates/template.py |
import inspect
import io
from abc import ABCMeta, abstractmethod
from PySide.QtGui import QApplication
if __package__:
from . import functions
else:
import functions
class TemplateError(Exception):
pass
class Renderable(metaclass=ABCMeta):
@abstractmethod
def render(self, context):
pas... | 0.364099 | 0.132936 |
from __future__ import print_function, division, unicode_literals
from deprecated.ncsm_vce_lpt.parser import exp
from deprecated.nushellx_lpt.DataMapNushellxLpt import DataMapNushellxLpt
from constants import FN_PARSE_LPT_RGX_FNAME as _RGX_FNAME
from constants import FN_PARSE_NCSMVCE_LPT_RGX_DNAME as _RGX_DNAME_GGP
f... | src/deprecated/ncsm_vce_lpt/DataMapNcsmVceLpt.py | from __future__ import print_function, division, unicode_literals
from deprecated.ncsm_vce_lpt.parser import exp
from deprecated.nushellx_lpt.DataMapNushellxLpt import DataMapNushellxLpt
from constants import FN_PARSE_LPT_RGX_FNAME as _RGX_FNAME
from constants import FN_PARSE_NCSMVCE_LPT_RGX_DNAME as _RGX_DNAME_GGP
f... | 0.491944 | 0.388821 |
from hexdump import hexdump
from macholib import MachO
def get_macho(fn):
# mod to make the header okay
# MH_CIGAM_64 is good
dat = open(fn, "rb").read()
dat = b"\xcf\xfa\xed\xfe"+dat[4:]
from tempfile import NamedTemporaryFile
with NamedTemporaryFile(delete=False) as f:
f.write(dat)
f.close()
r... | ane/2_compile/hwx_parse.py |
from hexdump import hexdump
from macholib import MachO
def get_macho(fn):
# mod to make the header okay
# MH_CIGAM_64 is good
dat = open(fn, "rb").read()
dat = b"\xcf\xfa\xed\xfe"+dat[4:]
from tempfile import NamedTemporaryFile
with NamedTemporaryFile(delete=False) as f:
f.write(dat)
f.close()
r... | 0.083287 | 0.217379 |
import logging
import os
import sys
import csv
import codecs
from io import BytesIO
from django_extensions.management.signals import post_command, pre_command
def _make_writeable(filename):
"""
Make sure that the file is writeable. Useful if our source is
read-only.
"""
import stat
if sys.p... | desktop/core/ext-py/django-extensions-1.8.0/django_extensions/management/utils.py | import logging
import os
import sys
import csv
import codecs
from io import BytesIO
from django_extensions.management.signals import post_command, pre_command
def _make_writeable(filename):
"""
Make sure that the file is writeable. Useful if our source is
read-only.
"""
import stat
if sys.p... | 0.427277 | 0.078536 |
from flask_restplus import Resource, Namespace
from app.v1.extensions.auth.jwt_auth import auth
from app.v1.extensions.auth import role_required
from flask import request
from app import db
from app.v1.utils.super_user_utils import save_super_user,update_super_user,delete_super_user,new_registors,data_ActivateNewRegist... | app/v1/modules/super_user/resources.py | from flask_restplus import Resource, Namespace
from app.v1.extensions.auth.jwt_auth import auth
from app.v1.extensions.auth import role_required
from flask import request
from app import db
from app.v1.utils.super_user_utils import save_super_user,update_super_user,delete_super_user,new_registors,data_ActivateNewRegist... | 0.318485 | 0.096068 |
from collections import defaultdict
import random
from typing import List, Tuple, Set, DefaultDict
from math import ceil
from instance import Instance
MAX_ITERATIONS = 2000
BEST_POSSIBLE_FITNESS = 1
Solution = DefaultDict[int, Set[Tuple[int, int]]]
EvaluatedSolution = Tuple[Solution, int, float]
Population = List[Sol... | genetic-algorithm/genetic_algorithm.py | from collections import defaultdict
import random
from typing import List, Tuple, Set, DefaultDict
from math import ceil
from instance import Instance
MAX_ITERATIONS = 2000
BEST_POSSIBLE_FITNESS = 1
Solution = DefaultDict[int, Set[Tuple[int, int]]]
EvaluatedSolution = Tuple[Solution, int, float]
Population = List[Sol... | 0.937633 | 0.513242 |
from WMCore.WebTools.RESTModel import RESTModel, restexpose
from cherrypy import HTTPError
import unittest, logging, json
from WMQuality.WebTools.RESTServerSetup import cherrypySetup, DefaultConfig
from WMQuality.WebTools.RESTClientAPI import makeRequest, methodTest
class REST_Exceptions_t(RESTModel):
def __init__... | test/python/WMCore_t/WebTools_t/REST_Exceptions_t.py | from WMCore.WebTools.RESTModel import RESTModel, restexpose
from cherrypy import HTTPError
import unittest, logging, json
from WMQuality.WebTools.RESTServerSetup import cherrypySetup, DefaultConfig
from WMQuality.WebTools.RESTClientAPI import makeRequest, methodTest
class REST_Exceptions_t(RESTModel):
def __init__... | 0.600774 | 0.23375 |
from nose.tools import eq_
from ..apply import apply
from ..tokenizers import text_split
def diff_and_replay(diff):
a = """
This sentence is going to get copied. This sentence is going to go away.
This is a paragraph that is mostly going to change. However, there's going
to be a sentence right in t... | deltas/tests/diff_and_replay.py | from nose.tools import eq_
from ..apply import apply
from ..tokenizers import text_split
def diff_and_replay(diff):
a = """
This sentence is going to get copied. This sentence is going to go away.
This is a paragraph that is mostly going to change. However, there's going
to be a sentence right in t... | 0.467818 | 0.539832 |
import re
import base64
import hashlib
from urllib import unquote,urlencode
from Crypto.Cipher import AES
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class Burpy:
'''
header is list, append as your need
body is string, modify as your need
'''
def __init__(self):
self.key = ""
... | examples/aes_endec[outdated].py | import re
import base64
import hashlib
from urllib import unquote,urlencode
from Crypto.Cipher import AES
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
class Burpy:
'''
header is list, append as your need
body is string, modify as your need
'''
def __init__(self):
self.key = ""
... | 0.246715 | 0.111676 |
from asyncio import gather
from datetime import datetime, timezone
from sanic import Blueprint
from sanic.request import Request
from sanic.response import HTTPResponse, json
from vxwhatsapp import config
from vxwhatsapp.auth import validate_hmac
from vxwhatsapp.claims import store_conversation_claim
from vxwhatsapp.... | vxwhatsapp/whatsapp.py | from asyncio import gather
from datetime import datetime, timezone
from sanic import Blueprint
from sanic.request import Request
from sanic.response import HTTPResponse, json
from vxwhatsapp import config
from vxwhatsapp.auth import validate_hmac
from vxwhatsapp.claims import store_conversation_claim
from vxwhatsapp.... | 0.297878 | 0.061312 |
import asyncio
import datetime
import random
import urllib.parse
import discord
import requests
from discord.ext import commands
from romme import RepublicanDate
from modules.utils import lists
class Fun(commands.Cog):
conf = {}
def __init__(self, bot):
self.bot = bot
self.config = bot.con... | modules/fun/fun.py |
import asyncio
import datetime
import random
import urllib.parse
import discord
import requests
from discord.ext import commands
from romme import RepublicanDate
from modules.utils import lists
class Fun(commands.Cog):
conf = {}
def __init__(self, bot):
self.bot = bot
self.config = bot.con... | 0.321141 | 0.100746 |
from abc import ABC
from typing import Any, Dict, List, Optional, Tuple, Type, Union, cast
from dokklib_db_extended.index import GlobalIndex
from dokklib_db_extended.serializer import Serializer
AnySortKey = Union['SortKey', 'PrefixSortKey']
class EntityName(ABC):
"""Abstract base class of entity names.
Ap... | dokklib_db_extended/keys.py | from abc import ABC
from typing import Any, Dict, List, Optional, Tuple, Type, Union, cast
from dokklib_db_extended.index import GlobalIndex
from dokklib_db_extended.serializer import Serializer
AnySortKey = Union['SortKey', 'PrefixSortKey']
class EntityName(ABC):
"""Abstract base class of entity names.
Ap... | 0.952563 | 0.417509 |
from Queue import Queue
from domain import DomainUtils
from domain.ErrorTypes import ErrorTypes
from pipeline_generator.preprocessing.task import SpecialCaseHandler
# No need to keep data/state, so I did not make it a class..
# This will be safe for multi-thread use as well~
# Improve this...
def determine_generation... | arakat-core/pipeline_generator/preprocessing/task/TaskPreprocessor.py | from Queue import Queue
from domain import DomainUtils
from domain.ErrorTypes import ErrorTypes
from pipeline_generator.preprocessing.task import SpecialCaseHandler
# No need to keep data/state, so I did not make it a class..
# This will be safe for multi-thread use as well~
# Improve this...
def determine_generation... | 0.468304 | 0.18743 |
from app import db
from models import Community, Posts, Comments, User
db.create_all()
u = User(username="ben", password="<PASSWORD>")
c = Community(name="powerlifting", password=None, founder=u, FAQ=None, description=None)
post = Posts("How to Hook Grip with <NAME>",
"This is a video on how to hook grip with mark... | db_create.py | from app import db
from models import Community, Posts, Comments, User
db.create_all()
u = User(username="ben", password="<PASSWORD>")
c = Community(name="powerlifting", password=None, founder=u, FAQ=None, description=None)
post = Posts("How to Hook Grip with <NAME>",
"This is a video on how to hook grip with mark... | 0.431464 | 0.118487 |
from tkinter import *
import mysql.connector
class Tinder:
def __init__(self):
()#database connection
self.conn=mysql.connector.connect(host="localhost", user="root", password="", database="tinder")
self.mycursor=self.conn.cursor()
self.root=Tk()
self.root.title("TINDER... | Python3 GUI code.py | from tkinter import *
import mysql.connector
class Tinder:
def __init__(self):
()#database connection
self.conn=mysql.connector.connect(host="localhost", user="root", password="", database="tinder")
self.mycursor=self.conn.cursor()
self.root=Tk()
self.root.title("TINDER... | 0.394667 | 0.117066 |
from unittest import TestCase
from hazelcast import six
from hazelcast.core import Address
from hazelcast.connection import DefaultAddressProvider
class DefaultAddressProviderTest(TestCase):
def test_load_addresses(self):
initial_list = ["192.168.0.1:5701"]
provider = DefaultAddressProvider(initia... | tests/unit/discovery/default_address_provider_test.py | from unittest import TestCase
from hazelcast import six
from hazelcast.core import Address
from hazelcast.connection import DefaultAddressProvider
class DefaultAddressProviderTest(TestCase):
def test_load_addresses(self):
initial_list = ["192.168.0.1:5701"]
provider = DefaultAddressProvider(initia... | 0.807688 | 0.469824 |
import os
from os.path import join as jp
from collections import defaultdict
from tqdm import tqdm
import numpy as np
import pandas as pd
from skimage.measure import label
from dpipe.io import load_json, save_json, load_pred
from dpipe.medim.metrics import dice_score, fraction
from dpipe.commands import load_from_fol... | lowres/metric.py | import os
from os.path import join as jp
from collections import defaultdict
from tqdm import tqdm
import numpy as np
import pandas as pd
from skimage.measure import label
from dpipe.io import load_json, save_json, load_pred
from dpipe.medim.metrics import dice_score, fraction
from dpipe.commands import load_from_fol... | 0.580709 | 0.163579 |
"""Module for personal hamming coder."""
import argparse
import time
import os
import hammcoder
import binpacker
import errormaker
def setup_parser():
'''
Basic parser setup for simple hamming command line input.
'''
parser = argparse.ArgumentParser(description='Command line hamming coder')
parse... | hamming-python/hamming_main.py | """Module for personal hamming coder."""
import argparse
import time
import os
import hammcoder
import binpacker
import errormaker
def setup_parser():
'''
Basic parser setup for simple hamming command line input.
'''
parser = argparse.ArgumentParser(description='Command line hamming coder')
parse... | 0.531209 | 0.152316 |
import cv2
import onnx
import torch
from albumentations import (Compose,Resize,)
from albumentations.augmentations.transforms import Normalize
from albumentations.pytorch.transforms import ToTensor
from torchvision import models
import os
def preprocess_image(img_path):
# transformations for the input data
tr... | samples/PyTorch-ONNX-TensorRT/pytorch_model.py | import cv2
import onnx
import torch
from albumentations import (Compose,Resize,)
from albumentations.augmentations.transforms import Normalize
from albumentations.pytorch.transforms import ToTensor
from torchvision import models
import os
def preprocess_image(img_path):
# transformations for the input data
tr... | 0.463201 | 0.375163 |
import os
import fire
import numpy as np
import torch
from torch import optim
from torch.utils.tensorboard import SummaryWriter
from torchvision import datasets, transforms
from libs.Visualize import Visualize
from models.VAE import VAE
class Main():
def __init__(self, z_dim):
"""Constructor
Ar... | main.py | import os
import fire
import numpy as np
import torch
from torch import optim
from torch.utils.tensorboard import SummaryWriter
from torchvision import datasets, transforms
from libs.Visualize import Visualize
from models.VAE import VAE
class Main():
def __init__(self, z_dim):
"""Constructor
Ar... | 0.881207 | 0.416915 |
import subprocess
import httplib
import envoy
import socket
import time
import os
class App(object):
def __init__(self, host, port, root="~/.bam"):
self.host = host
self.port = port
self.root = root
self.proc = None
@property
def cmd(self):
"""Return the command to start this app, excluding... | bam/app.py |
import subprocess
import httplib
import envoy
import socket
import time
import os
class App(object):
def __init__(self, host, port, root="~/.bam"):
self.host = host
self.port = port
self.root = root
self.proc = None
@property
def cmd(self):
"""Return the command to start this app, excluding... | 0.740456 | 0.145905 |
import copy
import platform
from ctypes import *
import pkg_resources
system = platform.system()
if system == 'Linux':
lib_file = "../weld-latest/target/release/libweld.so"
elif system == 'Windows':
lib_file = "libweld.dll"
elif system == 'Darwin':
lib_file = "libweld.dylib"
else:
raise OSError("Unsu... | python/benchmarks/weld-python/bindings_latest.py |
import copy
import platform
from ctypes import *
import pkg_resources
system = platform.system()
if system == 'Linux':
lib_file = "../weld-latest/target/release/libweld.so"
elif system == 'Windows':
lib_file = "libweld.dll"
elif system == 'Darwin':
lib_file = "libweld.dylib"
else:
raise OSError("Unsu... | 0.428592 | 0.087019 |
from threading import Thread
from conpaas.core.expose import expose
from conpaas.core.manager import BaseManager
from conpaas.core.https.server import HttpJsonResponse, HttpErrorResponse
from conpaas.services.htcondor.agent import client
import node_info
class HTCondorManager(BaseManager):
"""Manager class with... | conpaas-services/src/conpaas/services/htcondor/manager/manager.py | from threading import Thread
from conpaas.core.expose import expose
from conpaas.core.manager import BaseManager
from conpaas.core.https.server import HttpJsonResponse, HttpErrorResponse
from conpaas.services.htcondor.agent import client
import node_info
class HTCondorManager(BaseManager):
"""Manager class with... | 0.603348 | 0.145874 |
import os
import json
import time
import math
import matplotlib.pyplot as plt
from core.data_processor import DataLoader
from core.model import Model
def plot_results(predicted_data, true_data):
fig = plt.figure(facecolor='white')
ax = fig.add_subplot(111)
ax.plot(true_data, label='True Data')
plt.plo... | Finance/LSTM-Neural-Network-for-Time-Series-Prediction-master/run.py | import os
import json
import time
import math
import matplotlib.pyplot as plt
from core.data_processor import DataLoader
from core.model import Model
def plot_results(predicted_data, true_data):
fig = plt.figure(facecolor='white')
ax = fig.add_subplot(111)
ax.plot(true_data, label='True Data')
plt.plo... | 0.389082 | 0.449997 |
from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
import enum
import uuid
class EventAction(enum.Enum):
CREATED = "Created"
GENERIC_UPDATE = "Generic Update"
AT... | backend/src/events/models.py | from django.db import models
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import User
import enum
import uuid
class EventAction(enum.Enum):
CREATED = "Created"
GENERIC_UPDATE = "Generic Update"
AT... | 0.548674 | 0.097133 |
import logging
import datetime
import tornado.escape
from config import BaseController
from config.dmls_api import USERS
class UserRankController(BaseController):
"""/v1/user_rank"""
def get(self):
limit = self.get_argument("limit")
rank_list = self.select_all(USERS["USER_RANK"], {"limit": l... | apis/user.py | import logging
import datetime
import tornado.escape
from config import BaseController
from config.dmls_api import USERS
class UserRankController(BaseController):
"""/v1/user_rank"""
def get(self):
limit = self.get_argument("limit")
rank_list = self.select_all(USERS["USER_RANK"], {"limit": l... | 0.256925 | 0.070464 |
import unittest
from .util import StateTestCase
class TestTaskState(StateTestCase):
"""Tests for the Task state"""
SUCCESSFUL_CASES = [
(
"Should include a basic task",
"""
class Action(Task):
async def run(event, context):
return
def main(data):
Action()
"""... | tests/test_task.py | import unittest
from .util import StateTestCase
class TestTaskState(StateTestCase):
"""Tests for the Task state"""
SUCCESSFUL_CASES = [
(
"Should include a basic task",
"""
class Action(Task):
async def run(event, context):
return
def main(data):
Action()
"""... | 0.465387 | 0.362489 |
from pathlib import Path
from typing import Optional
import qrcode
from qrcode.image.svg import SvgPathImage
import xml.etree.ElementTree as ET
from jinja2 import Environment, FileSystemLoader
ROOT_DIR = Path(__file__).resolve().parent
def get_eprel_link(eprel_id: int) -> str:
return 'https://eprel.ec.europa.e... | tyre_label/label.py | from pathlib import Path
from typing import Optional
import qrcode
from qrcode.image.svg import SvgPathImage
import xml.etree.ElementTree as ET
from jinja2 import Environment, FileSystemLoader
ROOT_DIR = Path(__file__).resolve().parent
def get_eprel_link(eprel_id: int) -> str:
return 'https://eprel.ec.europa.e... | 0.876138 | 0.341953 |
"""This module defines the utilities required for wxcode plugin """
from collections import OrderedDict
from improver.wxcode.wxcode_decision_tree import wxcode_decision_tree
from improver.wxcode.wxcode_decision_tree_global import wxcode_decision_tree_global
_WX_DICT_IN = {
0: "Clear_Night",
1: "Sunny_Day",
... | improver/wxcode/utilities.py | """This module defines the utilities required for wxcode plugin """
from collections import OrderedDict
from improver.wxcode.wxcode_decision_tree import wxcode_decision_tree
from improver.wxcode.wxcode_decision_tree_global import wxcode_decision_tree_global
_WX_DICT_IN = {
0: "Clear_Night",
1: "Sunny_Day",
... | 0.908618 | 0.431944 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from ._enums import *
__all__ = [
'CacheExpirationActionParametersArgs',
'DeepCreatedOriginArgs',
'DeliveryRuleCacheExpirationActionArgs',
'DeliveryRuleUr... | sdk/python/pulumi_azure_native/cdn/v20171012/_inputs.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from ._enums import *
__all__ = [
'CacheExpirationActionParametersArgs',
'DeepCreatedOriginArgs',
'DeliveryRuleCacheExpirationActionArgs',
'DeliveryRuleUr... | 0.868213 | 0.07703 |