code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import os
import unittest
import tensorflow as tf
import mvg_distributions.covariance_representations as cov_rep
from mvg_distributions.covariance_representations.tests.test_covariance_matrix import CovarianceTest, \
declare_inv_method_test_classes
class CovarianceCholTest(CovarianceTest):
def setUp(self):
... | mvg_distributions/covariance_representations/tests/test_covariance_chol.py | import os
import unittest
import tensorflow as tf
import mvg_distributions.covariance_representations as cov_rep
from mvg_distributions.covariance_representations.tests.test_covariance_matrix import CovarianceTest, \
declare_inv_method_test_classes
class CovarianceCholTest(CovarianceTest):
def setUp(self):
... | 0.576423 | 0.529446 |
from data import Amazon, Ebay, Mercado_Libre, Best_Buy, headers
from scrape_funcs import extract_soup, search_boxes
from page_getters import get_names, get_images, get_products_urls, get_price
# Clasification info
from clasificator import add_clasification_info
# Corpus and Params
from statistics import min_w... | scraper/main.py | from data import Amazon, Ebay, Mercado_Libre, Best_Buy, headers
from scrape_funcs import extract_soup, search_boxes
from page_getters import get_names, get_images, get_products_urls, get_price
# Clasification info
from clasificator import add_clasification_info
# Corpus and Params
from statistics import min_w... | 0.256646 | 0.16238 |
from typing import Hashable
import dask.array as da
import numpy as np
from xarray import Dataset
from sgkit import variables
from sgkit.stats.aggregation import call_allele_frequencies
from sgkit.utils import (
conditional_merge_datasets,
create_dataset,
define_variable_if_absent,
)
def identity_by_sta... | sgkit/stats/ibs.py | from typing import Hashable
import dask.array as da
import numpy as np
from xarray import Dataset
from sgkit import variables
from sgkit.stats.aggregation import call_allele_frequencies
from sgkit.utils import (
conditional_merge_datasets,
create_dataset,
define_variable_if_absent,
)
def identity_by_sta... | 0.938969 | 0.553445 |
import numpy as np
from typing import List
class Tuple(object):
__slots__ = ["val", "g", "delta"]
def __init__(self, val, g, delta):
self.val = val
self.g = g
self.delta = delta
def __repr__(self):
return '{}[{},{}]'.format(self.val, self.g, self.delta)
class GKArray(obj... | python/sketch/greenwaldkhanna_py.py | import numpy as np
from typing import List
class Tuple(object):
__slots__ = ["val", "g", "delta"]
def __init__(self, val, g, delta):
self.val = val
self.g = g
self.delta = delta
def __repr__(self):
return '{}[{},{}]'.format(self.val, self.g, self.delta)
class GKArray(obj... | 0.535098 | 0.23612 |
from datetime import datetime
from typing import Any, Optional, Union, AnyStr, Iterable, IO, Dict
from azure.storage.blob import ContentSettings, StorageStreamDownloader
from azure.storage.blob.aio import StorageStreamDownloader as StorageStreamDownloaderAsync
from azure.storage.filedatalake.aio import DataLakeFileCli... | src/osiris/core/io.py | from datetime import datetime
from typing import Any, Optional, Union, AnyStr, Iterable, IO, Dict
from azure.storage.blob import ContentSettings, StorageStreamDownloader
from azure.storage.blob.aio import StorageStreamDownloader as StorageStreamDownloaderAsync
from azure.storage.filedatalake.aio import DataLakeFileCli... | 0.902138 | 0.236175 |
import pytest
import ruleset
import util
import os
def get_rulesets(ruledir, recurse):
"""
List of ruleset objects extracted from the yaml directory
"""
if os.path.isdir(ruledir) and recurse:
yaml_files = []
for root, dirs, files in os.walk(ruledir):
for name in files:
... | ftw/pytest_plugin.py | import pytest
import ruleset
import util
import os
def get_rulesets(ruledir, recurse):
"""
List of ruleset objects extracted from the yaml directory
"""
if os.path.isdir(ruledir) and recurse:
yaml_files = []
for root, dirs, files in os.walk(ruledir):
for name in files:
... | 0.411939 | 0.257444 |
import sys
#dictionary of ambiguity codes
ambig = {"Y":["C", "T"], "R":["A", "G"], "W":["A", "T"], "S":["C", "G"],
"K":["G","T"], "M":["A", "C"]}
def duplicate(file):
"""duplicate all individuals so they are diploid"""
with open(file, 'r') as Infile:
d = []
for line in Infile... | SNPtoAFSready.py | import sys
#dictionary of ambiguity codes
ambig = {"Y":["C", "T"], "R":["A", "G"], "W":["A", "T"], "S":["C", "G"],
"K":["G","T"], "M":["A", "C"]}
def duplicate(file):
"""duplicate all individuals so they are diploid"""
with open(file, 'r') as Infile:
d = []
for line in Infile... | 0.092955 | 0.280038 |
import requests
import json
import time
import re
from bs4 import BeautifulSoup
import MySQLdb
import random
# 获取当前知乎热榜
# 获取当前知乎热榜
def get_hot_zhihu(url, headers, proxy_ip):
res = requests.get(url, headers=headers, proxies=proxy_ip)
content = BeautifulSoup(res.text, "html.parser")
hot_data = content.fin... | zhihu crawler/getHotBoard.py | import requests
import json
import time
import re
from bs4 import BeautifulSoup
import MySQLdb
import random
# 获取当前知乎热榜
# 获取当前知乎热榜
def get_hot_zhihu(url, headers, proxy_ip):
res = requests.get(url, headers=headers, proxies=proxy_ip)
content = BeautifulSoup(res.text, "html.parser")
hot_data = content.fin... | 0.129293 | 0.077239 |
# Simple demo of super-basic neural-network weather prediction
# <NAME>
# Created: 2/1/15
# Updated: 3/23/17
import random
class Seer:
# [Temp, Pressure (hPa), Wind Speed, Temp Multiplier, Precip Multiplier, Clouds Multiplier]
rawlins = [65, .5, .75, .3, .3, .3]
laramie = [75, .2, .5, .3, .3, ... | seer.py |
# Simple demo of super-basic neural-network weather prediction
# <NAME>
# Created: 2/1/15
# Updated: 3/23/17
import random
class Seer:
# [Temp, Pressure (hPa), Wind Speed, Temp Multiplier, Precip Multiplier, Clouds Multiplier]
rawlins = [65, .5, .75, .3, .3, .3]
laramie = [75, .2, .5, .3, .3, ... | 0.267887 | 0.478712 |
from __future__ import division
from sympy.matrices import Matrix
from sympy import Rational
# TODO: determine this from mpmath, currently assumes float precision
eps = 2**(-52) # = B/2*B**(-m)
def norm_p(x):
"""
Return the p-norm of a vector.
"""
return sum([abs(i)**p for i in x])**(1./p)
def maxn... | sympy/solvers/numeric.py |
from __future__ import division
from sympy.matrices import Matrix
from sympy import Rational
# TODO: determine this from mpmath, currently assumes float precision
eps = 2**(-52) # = B/2*B**(-m)
def norm_p(x):
"""
Return the p-norm of a vector.
"""
return sum([abs(i)**p for i in x])**(1./p)
def maxn... | 0.544801 | 0.581036 |
from django import forms
from .models import (InputResult,
RowToColumn,
ColumnToRow,
DeleteDuplicates,
NumbersInWords,
ListSorting,
ChangeCase,
Autofill,
... | tools/forms.py | from django import forms
from .models import (InputResult,
RowToColumn,
ColumnToRow,
DeleteDuplicates,
NumbersInWords,
ListSorting,
ChangeCase,
Autofill,
... | 0.384334 | 0.159643 |
import open3d
import rospy
from pc_utility import convert
from sensor_msgs.msg import PointCloud2
from coro_eyes_ros.srv import *
def ask_for_command():
display = '**********************\n'
display += '* Available commands *\n'
display += '**********************\n'
display += 's: Single scan\n'
d... | scripts/coro_eyes.py | import open3d
import rospy
from pc_utility import convert
from sensor_msgs.msg import PointCloud2
from coro_eyes_ros.srv import *
def ask_for_command():
display = '**********************\n'
display += '* Available commands *\n'
display += '**********************\n'
display += 's: Single scan\n'
d... | 0.516352 | 0.133472 |
import time
import logging
from optparse import make_option
from django.db import connection, transaction
from django.utils.timezone import now
from utils.management.commands.base.time_args_command import TimeArgsCommand
from utils.pid import Pid
log = logging.getLogger(__name__)
class DBProcedureCommand(TimeArgsC... | app/utils/management/commands/base/db_procedure_command.py | import time
import logging
from optparse import make_option
from django.db import connection, transaction
from django.utils.timezone import now
from utils.management.commands.base.time_args_command import TimeArgsCommand
from utils.pid import Pid
log = logging.getLogger(__name__)
class DBProcedureCommand(TimeArgsC... | 0.540681 | 0.092811 |
from data_access_layer.mongo_db.mongo_db_atlas import MongoDBOperation
from exception_layer.generic_exception.generic_exception import GenericException as RegistrationException
from entity_layer.encryption.encrypt_confidential_data import EncryptData
from project_library_layer.datetime_libray.date_time import get_time,... | entity_layer/registration/registration.py | from data_access_layer.mongo_db.mongo_db_atlas import MongoDBOperation
from exception_layer.generic_exception.generic_exception import GenericException as RegistrationException
from entity_layer.encryption.encrypt_confidential_data import EncryptData
from project_library_layer.datetime_libray.date_time import get_time,... | 0.254787 | 0.076442 |
from http import HTTPStatus
from typing import Union, Tuple
from uuid import UUID
from flask import Blueprint, Response, jsonify, request, current_app
from liquidity import create_liquidity_provider
from liquidity.types.currency import Currency, CurrencyPair
from liquidity.types.errors import AlreadySettled
from liq... | webapp/api.py |
from http import HTTPStatus
from typing import Union, Tuple
from uuid import UUID
from flask import Blueprint, Response, jsonify, request, current_app
from liquidity import create_liquidity_provider
from liquidity.types.currency import Currency, CurrencyPair
from liquidity.types.errors import AlreadySettled
from liq... | 0.762336 | 0.092647 |
import argparse
import itertools
import os
import re
import requests as rq
import collections
from datetime import datetime
import pandas as pd
import Levenshtein
"""
Map between Data Tracking sheet headers and the desired input.
Every value gets passed to eval_value(), which will return the desired formatted outpu... | src/compare_tracker_with_nxn_sheet.py | import argparse
import itertools
import os
import re
import requests as rq
import collections
from datetime import datetime
import pandas as pd
import Levenshtein
"""
Map between Data Tracking sheet headers and the desired input.
Every value gets passed to eval_value(), which will return the desired formatted outpu... | 0.456652 | 0.470372 |
from telegram_envelope import utils
def test_parse_command():
assert utils.parse_command("") == ('', '')
assert utils.parse_command("/hello") == ('hello', '')
assert utils.parse_command("/command text") == ('command', 'text')
assert utils.parse_command("/command and more text") == ('command', 'and mor... | tests/telegram_envelope/test_utils.py | from telegram_envelope import utils
def test_parse_command():
assert utils.parse_command("") == ('', '')
assert utils.parse_command("/hello") == ('hello', '')
assert utils.parse_command("/command text") == ('command', 'text')
assert utils.parse_command("/command and more text") == ('command', 'and mor... | 0.749637 | 0.371479 |
import numpy as np
from PIL import Image
from habitat_sim.utils.common import d3_40_colors_rgb
from habitat.config import Config
from typing import Any, Dict, Iterator, List, Optional, Tuple, Type, Union
from habitat.core.dataset import Dataset, Episode, EpisodeIterator
import os
import magnum as mn
import habitat
impo... | spring_simulation/spring_simulation/envs/spring_env.py | import numpy as np
from PIL import Image
from habitat_sim.utils.common import d3_40_colors_rgb
from habitat.config import Config
from typing import Any, Dict, Iterator, List, Optional, Tuple, Type, Union
from habitat.core.dataset import Dataset, Episode, EpisodeIterator
import os
import magnum as mn
import habitat
impo... | 0.855202 | 0.265845 |
import logging
from typing import Union
from UQpy.inference.information_criteria import AIC
from UQpy.inference.information_criteria.baseclass.InformationCriterion import InformationCriterion
from beartype import beartype
from UQpy.inference.MLE import MLE
import numpy as np
class InformationModelSelection:
# A... | src/UQpy/inference/InformationModelSelection.py | import logging
from typing import Union
from UQpy.inference.information_criteria import AIC
from UQpy.inference.information_criteria.baseclass.InformationCriterion import InformationCriterion
from beartype import beartype
from UQpy.inference.MLE import MLE
import numpy as np
class InformationModelSelection:
# A... | 0.908274 | 0.470068 |
import os
from cStringIO import StringIO
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import override_settings
from dju_image.tools import (get_relative_path_from_img_id, clear_profile_configs_cache,
ERROR_MESSAGES as TOOLS_ERRORS)
from dju_... | tests/tests/test_views.py | import os
from cStringIO import StringIO
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test import override_settings
from dju_image.tools import (get_relative_path_from_img_id, clear_profile_configs_cache,
ERROR_MESSAGES as TOOLS_ERRORS)
from dju_... | 0.347648 | 0.272987 |
import locale
import logging
import time
from modules import button, flowmeter, lv_sensor, ph_meter, relais
from server import app_server
locale.setlocale(locale.LC_TIME, "")
FORMATTER = logging.Formatter(
"%(asctime)s [%(levelname)s] <%(name)s> - %(message)s", "%x %X"
)
LOGGER = logging.getLogger("Bio-Urée")
L... | main.py | import locale
import logging
import time
from modules import button, flowmeter, lv_sensor, ph_meter, relais
from server import app_server
locale.setlocale(locale.LC_TIME, "")
FORMATTER = logging.Formatter(
"%(asctime)s [%(levelname)s] <%(name)s> - %(message)s", "%x %X"
)
LOGGER = logging.getLogger("Bio-Urée")
L... | 0.18691 | 0.104798 |
from __future__ import annotations
import asyncio
import logging
from typing import Optional, TYPE_CHECKING
from steam import utils
from steam.models import EventParser, register
from steam.state import ConnectionState
from steam.protobufs import GCMsg, GCMsgProto, MsgProto, EMsg
from .channel import Channel
from .e... | steam/ext/dota2/state.py | from __future__ import annotations
import asyncio
import logging
from typing import Optional, TYPE_CHECKING
from steam import utils
from steam.models import EventParser, register
from steam.state import ConnectionState
from steam.protobufs import GCMsg, GCMsgProto, MsgProto, EMsg
from .channel import Channel
from .e... | 0.740737 | 0.043916 |
from django.contrib.gis import admin
from django.http import HttpResponseRedirect
from .models import Project, Emprise, Plan, PlanEmprise
from .tasks import process_new_project, process_new_plan
@admin.register(Project)
class ProjectAdmin(admin.GeoModelAdmin):
model = Project
list_display = (
"name",... | project/admin.py | from django.contrib.gis import admin
from django.http import HttpResponseRedirect
from .models import Project, Emprise, Plan, PlanEmprise
from .tasks import process_new_project, process_new_plan
@admin.register(Project)
class ProjectAdmin(admin.GeoModelAdmin):
model = Project
list_display = (
"name",... | 0.346099 | 0.081374 |
from __future__ import annotations
__VERSION__ = '0.6.2'
import re
from typing import Type, Union
from . import utils
from .exceptions import TakiyashaException
from .ncm import NCM
from .ncmcache import NCMCache
from .qmc import QMCv1, QMCv2
from .sniff import sniff_audio_file
SupportsCrypter = Union[NCM, NCMCache... | src/libtakiyasha/__init__.py | from __future__ import annotations
__VERSION__ = '0.6.2'
import re
from typing import Type, Union
from . import utils
from .exceptions import TakiyashaException
from .ncm import NCM
from .ncmcache import NCMCache
from .qmc import QMCv1, QMCv2
from .sniff import sniff_audio_file
SupportsCrypter = Union[NCM, NCMCache... | 0.596786 | 0.129706 |
import numpy as np
import tensorflow as tf
import pytest
from src.channelcoding.dataclasses import StateTransitionGraph, Trellis
from src.channelcoding.encoders import AffineConvolutionalCode, GeneralizedConvolutionalCode, TrellisCode
from commpy import channelcoding as cc
from src.channelcoding.interleavers import ... | turbo-codes/tests/channelcoding/test_encoders.py | import numpy as np
import tensorflow as tf
import pytest
from src.channelcoding.dataclasses import StateTransitionGraph, Trellis
from src.channelcoding.encoders import AffineConvolutionalCode, GeneralizedConvolutionalCode, TrellisCode
from commpy import channelcoding as cc
from src.channelcoding.interleavers import ... | 0.715424 | 0.438004 |
import streamlit as st
import pandas as pd
import shap
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.ensemble import RandomForestRegressor
st.write("""
# Boston House Price Prediction App
App for predicting **Boston House Prices**
""")
st.write('---')
# Loads the Boston House ... | Boston_House_Price_Predictor/app.py | import streamlit as st
import pandas as pd
import shap
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn.ensemble import RandomForestRegressor
st.write("""
# Boston House Price Prediction App
App for predicting **Boston House Prices**
""")
st.write('---')
# Loads the Boston House ... | 0.699254 | 0.324904 |
from flask import g
from flask.ext.restful import fields, marshal_with, reqparse, abort
from ..core.setup import Resource, auth, config
from ..models import User
from ..core.validators import validate_email
user_fields = {
'id': fields.Integer,
'username': fields.String,
'per_page': fields.Integer,
'e... | api/views/profile.py |
from flask import g
from flask.ext.restful import fields, marshal_with, reqparse, abort
from ..core.setup import Resource, auth, config
from ..models import User
from ..core.validators import validate_email
user_fields = {
'id': fields.Integer,
'username': fields.String,
'per_page': fields.Integer,
'e... | 0.427158 | 0.07072 |
from maya import cmds as MayaCmds
import os
import unittest
import util
class LoadWorldSpaceTranslateJobTest(unittest.TestCase):
def setUp(self):
MayaCmds.file(new=True, force=True)
self.__files = []
def tearDown(self):
for f in self.__files :
os.remove(f)
def testSt... | maya/Tests/loadWorldSpaceTranslateJob_test.py |
from maya import cmds as MayaCmds
import os
import unittest
import util
class LoadWorldSpaceTranslateJobTest(unittest.TestCase):
def setUp(self):
MayaCmds.file(new=True, force=True)
self.__files = []
def tearDown(self):
for f in self.__files :
os.remove(f)
def testSt... | 0.377196 | 0.226484 |
import json
import time
from mqalib import call_rest_api
from prometheus_client.core import CounterMetricFamily, GaugeMetricFamily, InfoMetricFamily
class MQAMQSystemResourcesMetrics(object):
"""MQ Appliance MQ system resources metrics collector"""
def __init__(self, appliance, ip, port, session, timeout):
... | code/mqa_mq_system_recources_metrics.py | import json
import time
from mqalib import call_rest_api
from prometheus_client.core import CounterMetricFamily, GaugeMetricFamily, InfoMetricFamily
class MQAMQSystemResourcesMetrics(object):
"""MQ Appliance MQ system resources metrics collector"""
def __init__(self, appliance, ip, port, session, timeout):
... | 0.482185 | 0.093595 |
import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import metrics
from sklearn import svm
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
from sklearn.manifold import Isomap
digits = datasets.load_digits()
X_train, X_test, y_train, y_test, image... | svm.py | import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import metrics
from sklearn import svm
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
from sklearn.manifold import Isomap
digits = datasets.load_digits()
X_train, X_test, y_train, y_test, image... | 0.901293 | 0.774796 |
import sys
sys.path.append('..')
from intcode.intcode import IntCodeComputer
from itertools import product
from tractor_beam import TractorBeam
from math import sqrt
def part1():
# ic.debugging = True
area = []
for y in range(0, 50):
area.append(['?'] * 50)
num_affected = 0
for coord... | day19/day19.py | import sys
sys.path.append('..')
from intcode.intcode import IntCodeComputer
from itertools import product
from tractor_beam import TractorBeam
from math import sqrt
def part1():
# ic.debugging = True
area = []
for y in range(0, 50):
area.append(['?'] * 50)
num_affected = 0
for coord... | 0.416559 | 0.477981 |
def ts_recon(ts, dim, tau):
xlen = len(ts)-(dim-1)*tau
a= np.linspace(0,xlen-1,xlen)
a= np.reshape(a,(xlen,1))
delayVec=np.linspace(0,(dim-1),dim)*tau
delayVec= np.reshape(delayVec,(1,dim))
delayMat=np.tile(delayVec,(xlen,1))
vec=np.tile(a,(1,dim))
indRecon = np.reshape(vec,(xlen,dim)) +... | PE_parameter_functions/FNN_n.py | def ts_recon(ts, dim, tau):
xlen = len(ts)-(dim-1)*tau
a= np.linspace(0,xlen-1,xlen)
a= np.reshape(a,(xlen,1))
delayVec=np.linspace(0,(dim-1),dim)*tau
delayVec= np.reshape(delayVec,(1,dim))
delayMat=np.tile(delayVec,(xlen,1))
vec=np.tile(a,(1,dim))
indRecon = np.reshape(vec,(xlen,dim)) +... | 0.793666 | 0.555315 |
from .common import InfoExtractor
from ..utils import (
determine_ext,
float_or_none,
join_nonempty,
traverse_obj,
url_or_none,
)
class DailyWireBaseIE(InfoExtractor):
_JSON_PATH = {
'episode': ('props', 'pageProps', 'episodeData', 'episode'),
'videos': ('props', 'pageProps', '... | yt_dlp/extractor/dailywire.py | from .common import InfoExtractor
from ..utils import (
determine_ext,
float_or_none,
join_nonempty,
traverse_obj,
url_or_none,
)
class DailyWireBaseIE(InfoExtractor):
_JSON_PATH = {
'episode': ('props', 'pageProps', 'episodeData', 'episode'),
'videos': ('props', 'pageProps', '... | 0.460532 | 0.163179 |
import numpy as np
class KNNClassifier:
def __init__(self, X, y):
self.X = self._check_input(X)
self.y = self._check_input(y)
def _check_input(self, arr):
if list == type(arr):
return np.array(arr)
elif np.ndarray == type(arr):
return arr
... | mlgorithms/knn/knn.py | import numpy as np
class KNNClassifier:
def __init__(self, X, y):
self.X = self._check_input(X)
self.y = self._check_input(y)
def _check_input(self, arr):
if list == type(arr):
return np.array(arr)
elif np.ndarray == type(arr):
return arr
... | 0.408631 | 0.344058 |
import mitsuba
import pytest
import enoki as ek
from enoki.dynamic import Float32 as Float
def test01_create(variant_scalar_rgb):
from mitsuba.core import xml
s = xml.load_dict({"type" : "rectangle"})
assert s is not None
assert s.primitive_count() == 1
assert ek.allclose(s.surface_area(), 4.0)
... | src/shapes/tests/test_rectangle.py | import mitsuba
import pytest
import enoki as ek
from enoki.dynamic import Float32 as Float
def test01_create(variant_scalar_rgb):
from mitsuba.core import xml
s = xml.load_dict({"type" : "rectangle"})
assert s is not None
assert s.primitive_count() == 1
assert ek.allclose(s.surface_area(), 4.0)
... | 0.538741 | 0.683565 |
# <NAME>
# Main for interacting with the ROBDD
# Libraries:
# -pyeda, a python EDA library. It provides a lot of functionality, I am only
# using its expression conversion functionality so that I don't have to roll my
# own using lex, flex, etc.
import argparse
import re
from pyeda.boolalg.expr import expr
fr... | main.py |
# <NAME>
# Main for interacting with the ROBDD
# Libraries:
# -pyeda, a python EDA library. It provides a lot of functionality, I am only
# using its expression conversion functionality so that I don't have to roll my
# own using lex, flex, etc.
import argparse
import re
from pyeda.boolalg.expr import expr
fr... | 0.480479 | 0.311113 |
from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse_lazy
from datetime import datetime
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.views.generic import TemplateView, FormView, UpdateView, DeleteView, DetailView, ListView
from products.models im... | products/views.py | from django.shortcuts import render, redirect, get_object_or_404
from django.urls import reverse_lazy
from datetime import datetime
from django.contrib.auth.mixins import PermissionRequiredMixin
from django.views.generic import TemplateView, FormView, UpdateView, DeleteView, DetailView, ListView
from products.models im... | 0.538983 | 0.072178 |
import random
VOWELS = ('a', 'e', 'i', 'o', 'u',)
CONSONANT_START = {
'b': ('l', 'r',),
'c': ('h', 'l', 'r',),
'd': ('r', 'w',),
'f': ('l', 'r',),
'g': ('l', 'r', 'w',),
'h': (),
'j': (),
'k': ('l', 'r',),
'l': (),
'm': (),
'n': (),
'p': ('l', 'r',),
'qu': (),
'r... | mock_word.py | import random
VOWELS = ('a', 'e', 'i', 'o', 'u',)
CONSONANT_START = {
'b': ('l', 'r',),
'c': ('h', 'l', 'r',),
'd': ('r', 'w',),
'f': ('l', 'r',),
'g': ('l', 'r', 'w',),
'h': (),
'j': (),
'k': ('l', 'r',),
'l': (),
'm': (),
'n': (),
'p': ('l', 'r',),
'qu': (),
'r... | 0.333069 | 0.255664 |
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
import random
from datetime import datetime, timedelta
import cufflinks as cf
from plotly.offline import iplot, init_notebook_mode
import pandas as pd
from datetime import datetime
from ipyleaflet import Map, Marker, MarkerCluster
class Ba... | cerebralcortex/core/plotting/basic_plots.py |
import plotly.plotly as py
import plotly.graph_objs as go
import pandas as pd
import random
from datetime import datetime, timedelta
import cufflinks as cf
from plotly.offline import iplot, init_notebook_mode
import pandas as pd
from datetime import datetime
from ipyleaflet import Map, Marker, MarkerCluster
class Ba... | 0.612541 | 0.25333 |
import json
from django.conf import settings
from rest_framework import serializers
from landscapesim.async.tasks import run_model
from landscapesim.models import Library, Project, Scenario, RunScenarioModel
from landscapesim.serializers import imports
STSIM_MULTIPLIER_DIR = getattr(settings, 'STSIM_MULTIPLIER_DIR')... | landscapesim/async/serializers.py | import json
from django.conf import settings
from rest_framework import serializers
from landscapesim.async.tasks import run_model
from landscapesim.models import Library, Project, Scenario, RunScenarioModel
from landscapesim.serializers import imports
STSIM_MULTIPLIER_DIR = getattr(settings, 'STSIM_MULTIPLIER_DIR')... | 0.602412 | 0.178275 |
from django.contrib.auth import get_user_model, authenticate, password_validation
from django.utils.translation import ugettext_lazy as _
from core.models import Role
from rest_framework import serializers
class RoleSerializer(serializers.ModelSerializer):
"""Serializer for roles"""
class Meta:
model... | app/user/serializers.py | from django.contrib.auth import get_user_model, authenticate, password_validation
from django.utils.translation import ugettext_lazy as _
from core.models import Role
from rest_framework import serializers
class RoleSerializer(serializers.ModelSerializer):
"""Serializer for roles"""
class Meta:
model... | 0.609989 | 0.09947 |
import json
import datetime
from django.http import HttpResponseServerError
from django.core.exceptions import PermissionDenied
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import authenticate
from django.urls import reverse
from django.contrib.auth.decorat... | app/views/User.py | import json
import datetime
from django.http import HttpResponseServerError
from django.core.exceptions import PermissionDenied
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import authenticate
from django.urls import reverse
from django.contrib.auth.decorat... | 0.281702 | 0.054853 |
from ..graph import get_default_graph
from ..tensors import *
from ..ops.array_ops import *
from ..ops.ctrl_ops import *
from ..ops.constant import *
from ..ops.math_ops import *
from ..ops.placeholder import *
from ..ops.variable import *
def constant(name, out_shape, value=None, graph=None):
if graph is None:
... | catamount/api/ops.py | from ..graph import get_default_graph
from ..tensors import *
from ..ops.array_ops import *
from ..ops.ctrl_ops import *
from ..ops.constant import *
from ..ops.math_ops import *
from ..ops.placeholder import *
from ..ops.variable import *
def constant(name, out_shape, value=None, graph=None):
if graph is None:
... | 0.607081 | 0.345947 |
from .derivation import (
normalised_primary_matrix,
chromatically_adapted_primaries,
primaries_whitepoint,
RGB_luminance_equation,
RGB_luminance,
)
from .rgb_colourspace import RGB_Colourspace
from .rgb_colourspace import XYZ_to_RGB, RGB_to_XYZ
from .rgb_colourspace import matrix_RGB_to_RGB, RGB_t... | colour/models/rgb/__init__.py |
from .derivation import (
normalised_primary_matrix,
chromatically_adapted_primaries,
primaries_whitepoint,
RGB_luminance_equation,
RGB_luminance,
)
from .rgb_colourspace import RGB_Colourspace
from .rgb_colourspace import XYZ_to_RGB, RGB_to_XYZ
from .rgb_colourspace import matrix_RGB_to_RGB, RGB_t... | 0.611266 | 0.260295 |
import os
import torch
import argparse
import onnxruntime
import numpy as np
from functools import reduce
from zcls.config import cfg
from zcls.config.key_word import KEY_OUTPUT
from zcls.model.recognizers.build import build_recognizer
from misc import to_numpy, softmax
def parse_args():
parser = argparse.Argu... | py/convert/compare_zcl_pytorch_and_onnx.py | import os
import torch
import argparse
import onnxruntime
import numpy as np
from functools import reduce
from zcls.config import cfg
from zcls.config.key_word import KEY_OUTPUT
from zcls.model.recognizers.build import build_recognizer
from misc import to_numpy, softmax
def parse_args():
parser = argparse.Argu... | 0.463444 | 0.188828 |
import resource
from typing import Optional, Union
from bitmath import MiB
from hbutils.model import get_repr_info
from hbutils.scale import size_to_bytes, time_to_duration, size_to_bytes_str
from ...utils import allow_none
_UNLIMITED = -1
def _rmin(x, y):
if x == _UNLIMITED:
return y
elif y == _UN... | pji/control/model/resource.py | import resource
from typing import Optional, Union
from bitmath import MiB
from hbutils.model import get_repr_info
from hbutils.scale import size_to_bytes, time_to_duration, size_to_bytes_str
from ...utils import allow_none
_UNLIMITED = -1
def _rmin(x, y):
if x == _UNLIMITED:
return y
elif y == _UN... | 0.849332 | 0.239355 |
import numpy as np
from queue import LifoQueue
import math
class SkeletalGraph:
def __init__(self, structure):
self.vertices = structure
self.edges = self.compute_edges()
self.block_size = 1
def compute_edges(self):
# Add edge if blocks are within a certain radius of target blo... | skeletal_graph.py | import numpy as np
from queue import LifoQueue
import math
class SkeletalGraph:
def __init__(self, structure):
self.vertices = structure
self.edges = self.compute_edges()
self.block_size = 1
def compute_edges(self):
# Add edge if blocks are within a certain radius of target blo... | 0.59843 | 0.496033 |
import numpy as np
import warnings
class GradientPolicy2(object):
def __init__(self, train_size=0, valid_size=0, average_win=20, hist_size=20):
self.train_loss = np.array([])
self.valid_loss = np.array([])
self.smoothed_train_loss = np.array([])
self.smoothed_valid_loss = np.array([... | mass/tensorflow_nets/xsleepnet2/gradient_policy2.py | import numpy as np
import warnings
class GradientPolicy2(object):
def __init__(self, train_size=0, valid_size=0, average_win=20, hist_size=20):
self.train_loss = np.array([])
self.valid_loss = np.array([])
self.smoothed_train_loss = np.array([])
self.smoothed_valid_loss = np.array([... | 0.642208 | 0.462048 |
from __future__ import unicode_literals
from __future__ import absolute_import
from checkmate.lib.analysis.base import BaseAnalyzer
import logging
import os
import tempfile
import json
import pprint
import subprocess
logger = logging.getLogger(__name__)
class GosecAnalyzer(BaseAnalyzer):
def __init__(self, *a... | checkmate/contrib/plugins/golang/gosec/analyzer.py |
from __future__ import unicode_literals
from __future__ import absolute_import
from checkmate.lib.analysis.base import BaseAnalyzer
import logging
import os
import tempfile
import json
import pprint
import subprocess
logger = logging.getLogger(__name__)
class GosecAnalyzer(BaseAnalyzer):
def __init__(self, *a... | 0.317215 | 0.048249 |
from oper import Webfinger, AccessToken
from oper import Discovery
from oper import Registration
from oper import Authn
from testfunc import resource, set_jwks_uri, set_op_args
from testfunc import expect_exception
from testfunc import set_request_args
from oic.exception import IssuerMismatch
__author__ = 'roland'
O... | test/oic_rp/rp/cflows.py | from oper import Webfinger, AccessToken
from oper import Discovery
from oper import Registration
from oper import Authn
from testfunc import resource, set_jwks_uri, set_op_args
from testfunc import expect_exception
from testfunc import set_request_args
from oic.exception import IssuerMismatch
__author__ = 'roland'
O... | 0.379838 | 0.203035 |
from model.rental import Rental
from model.client import Client
from model.boat import Boat
from exception.dni_format_exception import DNIFormatException
import test_data
class RentalManagement(object):
"""Clase que encapsula el programa de gestión de alquileres."""
def __init__(self):
"""Inicializa... | app/rental_app.py | from model.rental import Rental
from model.client import Client
from model.boat import Boat
from exception.dni_format_exception import DNIFormatException
import test_data
class RentalManagement(object):
"""Clase que encapsula el programa de gestión de alquileres."""
def __init__(self):
"""Inicializa... | 0.604516 | 0.356951 |
# In[2]:
import time
import copy
import numpy as np
import nibabel as nib
import dipy.reconst.dti as dti
from dipy.viz import window, actor
from dipy.viz.colormap import line_colors
from dipy.core.gradients import gradient_table
# In[3]:
st_all_animals = time.time()
roi_l = 122
roi_r = 1122+166-1000
interactive ... | compute_tensor.py |
# In[2]:
import time
import copy
import numpy as np
import nibabel as nib
import dipy.reconst.dti as dti
from dipy.viz import window, actor
from dipy.viz.colormap import line_colors
from dipy.core.gradients import gradient_table
# In[3]:
st_all_animals = time.time()
roi_l = 122
roi_r = 1122+166-1000
interactive ... | 0.429908 | 0.245187 |
import time
from unittest import TestCase
from anadroid.device.Device import get_first_connected_device
class TestDeviceState(TestCase):
device = get_first_connected_device()
def test_screen_lock(self):
self.__class__.device.unlock_screen()
time.sleep(1)
res = self.__class__.device.d... | anadroid/test/device/test_DeviceState.py | import time
from unittest import TestCase
from anadroid.device.Device import get_first_connected_device
class TestDeviceState(TestCase):
device = get_first_connected_device()
def test_screen_lock(self):
self.__class__.device.unlock_screen()
time.sleep(1)
res = self.__class__.device.d... | 0.430985 | 0.410284 |
import attribute
import pytest
import typing
@pytest.fixture
def default() -> typing.Any:
return 'default'
@pytest.fixture
def default_factory() -> typing.Callable:
return dict
@pytest.fixture
def value() -> typing.Any:
return 'value'
@pytest.fixture
def present(default) -> attribute.Attribute:
retu... | tests/test_attribute.py | import attribute
import pytest
import typing
@pytest.fixture
def default() -> typing.Any:
return 'default'
@pytest.fixture
def default_factory() -> typing.Callable:
return dict
@pytest.fixture
def value() -> typing.Any:
return 'value'
@pytest.fixture
def present(default) -> attribute.Attribute:
retu... | 0.651577 | 0.494751 |
import argparse
import os
import sys
import io
from pathlib import Path
from flask import Flask, render_template, request, send_file
from TTS.utils.synthesizer import Synthesizer
from TTS.utils.manage import ModelManager
from TTS.utils.io import load_config
def create_argparser():
def convert_boolean(x):
... | TTS/server/server.py | import argparse
import os
import sys
import io
from pathlib import Path
from flask import Flask, render_template, request, send_file
from TTS.utils.synthesizer import Synthesizer
from TTS.utils.manage import ModelManager
from TTS.utils.io import load_config
def create_argparser():
def convert_boolean(x):
... | 0.344664 | 0.055005 |
import os
import mmpm.consts
from mmpm.models import MagicMirrorPackage
from typing import List
from socket import gethostname, gethostbyname
MMPM_TEST_ROOT: str = os.path.join("/", "tmp", "MMPM_TEST")
MMPM_CONFIG_DIR: str = os.path.normpath(os.path.join(MMPM_TEST_ROOT, '.config', 'mmpm'))
MAGICMIRROR_ROOT: str = os... | tests/mmpm_test/consts.py | import os
import mmpm.consts
from mmpm.models import MagicMirrorPackage
from typing import List
from socket import gethostname, gethostbyname
MMPM_TEST_ROOT: str = os.path.join("/", "tmp", "MMPM_TEST")
MMPM_CONFIG_DIR: str = os.path.normpath(os.path.join(MMPM_TEST_ROOT, '.config', 'mmpm'))
MAGICMIRROR_ROOT: str = os... | 0.47244 | 0.161883 |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Brand',
fields=[
('id', models.AutoField(auto_created=True... | product/migrations/0001_initial.py |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Brand',
fields=[
('id', models.AutoField(auto_created=True... | 0.584034 | 0.305956 |
import setuptools
import os
import sys
import subprocess
# tags = subprocess.check_output("git tag -l | cat", shell=True).decode("utf-8")
# version = list(filter(None, tags.split("\n")))[-1]
version = "v1.3.1"
if sys.argv[-1] == 'publish':
if os.system("pip freeze | grep twine"):
print("twine not instal... | setup.py |
import setuptools
import os
import sys
import subprocess
# tags = subprocess.check_output("git tag -l | cat", shell=True).decode("utf-8")
# version = list(filter(None, tags.split("\n")))[-1]
version = "v1.3.1"
if sys.argv[-1] == 'publish':
if os.system("pip freeze | grep twine"):
print("twine not instal... | 0.30767 | 0.064831 |
from ..config import get_config, Config # noqa: F401
import json
import os
import requests
__all__ = [
'submit_project_to_runbiosimulations',
'validate_biosimulations_api_response',
]
def submit_project_to_runbiosimulations(name, filename_or_url,
simulator, simulator_... | biosimulators_utils/biosimulations/utils.py | from ..config import get_config, Config # noqa: F401
import json
import os
import requests
__all__ = [
'submit_project_to_runbiosimulations',
'validate_biosimulations_api_response',
]
def submit_project_to_runbiosimulations(name, filename_or_url,
simulator, simulator_... | 0.761804 | 0.219254 |
from torch import Tensor
import torch
import torch.nn as nn
import math
from torch.utils.data import DataLoader
from models import generate_square_subsequent_mask
import time
from data_preprocessing import BOS_WORD, EOS_WORD
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def train_epoch(model:... | NLP/The_Bottom_up_Evolution_of_Representations_in_the_Transformer/LM_helpers.py | from torch import Tensor
import torch
import torch.nn as nn
import math
from torch.utils.data import DataLoader
from models import generate_square_subsequent_mask
import time
from data_preprocessing import BOS_WORD, EOS_WORD
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
def train_epoch(model:... | 0.883557 | 0.515498 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import gin
import tensorflow as tf
from absl import flags
from sprl import env_factory, eval_policy
from sprl.utils import Summary_logger
from third_party.baselines import logger
from third_party.bas... | sprl/train_policy.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import gin
import tensorflow as tf
from absl import flags
from sprl import env_factory, eval_policy
from sprl.utils import Summary_logger
from third_party.baselines import logger
from third_party.bas... | 0.747247 | 0.101322 |
import time
import inspect
class KeepRunningTerminate(Exception):
pass
def keeprunning(
wait_secs=0, exit_on_success=False, on_success=None, on_error=None, on_done=None
):
"""
Example 1: dosomething needs to run until completion condition
without needing to have a loop in its code. Also, when er... | deeputil/keep_running.py | import time
import inspect
class KeepRunningTerminate(Exception):
pass
def keeprunning(
wait_secs=0, exit_on_success=False, on_success=None, on_error=None, on_done=None
):
"""
Example 1: dosomething needs to run until completion condition
without needing to have a loop in its code. Also, when er... | 0.489015 | 0.290761 |
import argparse
import datetime
import collections
import fnmatch
import shlex
import os
import re
import sys
import utils
from itertools import islice
# File extensions to check
VALID_FILE_EXTENSIONS = ('.c', '.conf', '.dts', '.dtsi', '.editorconfig',
'.h', '.i', '.ld', 'Makefile', '.mk', '.m... | script/static-checks/check-copyright.py | import argparse
import datetime
import collections
import fnmatch
import shlex
import os
import re
import sys
import utils
from itertools import islice
# File extensions to check
VALID_FILE_EXTENSIONS = ('.c', '.conf', '.dts', '.dtsi', '.editorconfig',
'.h', '.i', '.ld', 'Makefile', '.mk', '.m... | 0.311846 | 0.100525 |
import pandas as pd
from sklearn.model_selection import train_test_split
from scipy.stats import chi2_contingency as csc
from IPython.display import display
class DataFrameOperator:
"""Perform pandas.DataFrame operations"""
def __init__(self, dataframe):
self.dataframe = dataframe
def decompose_... | jose_lambdata/dftools.py |
import pandas as pd
from sklearn.model_selection import train_test_split
from scipy.stats import chi2_contingency as csc
from IPython.display import display
class DataFrameOperator:
"""Perform pandas.DataFrame operations"""
def __init__(self, dataframe):
self.dataframe = dataframe
def decompose_... | 0.705785 | 0.522019 |
from tiddlyweb.model.bag import Bag
from tiddlyweb import filter as fl
from tiddlyweb.serializer import TiddlerFormatError
from tiddlyweb.store import NoBagError
def get_tiddlers_from_recipe(recipe, environ=None):
"""
Return the list of tiddlers that result
from processing the recipe.
This list of ti... | tiddlyweb/control.py | from tiddlyweb.model.bag import Bag
from tiddlyweb import filter as fl
from tiddlyweb.serializer import TiddlerFormatError
from tiddlyweb.store import NoBagError
def get_tiddlers_from_recipe(recipe, environ=None):
"""
Return the list of tiddlers that result
from processing the recipe.
This list of ti... | 0.650578 | 0.281261 |
import os
import re
from utils.tool import Tools
__author__ = 'deff'
from scanner.base import BaseScanner
import json
from utils.sdkinfo import sdkinfo
from config import config
# api审计
# 0. 隐私信息api :手机号/imei/imsi/mac/android id/gps/通讯录/应用程序列表/网页浏览记录(静态检测,后续动态可以进行hook对应函数检测)
# 0.1 http url链接检测
# 1. 调用非SDK接口,带来兼容性问... | scanner/staticscanner/api.py | import os
import re
from utils.tool import Tools
__author__ = 'deff'
from scanner.base import BaseScanner
import json
from utils.sdkinfo import sdkinfo
from config import config
# api审计
# 0. 隐私信息api :手机号/imei/imsi/mac/android id/gps/通讯录/应用程序列表/网页浏览记录(静态检测,后续动态可以进行hook对应函数检测)
# 0.1 http url链接检测
# 1. 调用非SDK接口,带来兼容性问... | 0.117243 | 0.092647 |
import os
import wget
import math
import numpy as np
import scipy.io as sio
from sklearn.decomposition import PCA
def load_dataset(dataset, split=0.9):
"""Load one of the available hyperspectral datasets (IP, PU, SA, KSC)."""
if not os.path.exists('datasets'):
os.mkdir('datasets')
if dataset ... | multiple/data.py | import os
import wget
import math
import numpy as np
import scipy.io as sio
from sklearn.decomposition import PCA
def load_dataset(dataset, split=0.9):
"""Load one of the available hyperspectral datasets (IP, PU, SA, KSC)."""
if not os.path.exists('datasets'):
os.mkdir('datasets')
if dataset ... | 0.448185 | 0.401688 |
from blueprints.blueprint import bp
from vkbottle.bot import Message
import asyncio
from middlewares.registration import registered_chats
from vkbottle.dispatch.rules.base import PayloadRule
from random import choice, randint
tea_keys = [x.strip() for x in open("teakeys.txt", "r", encoding="utf-8").readlines()]
fortu... | handlers/common.py | from blueprints.blueprint import bp
from vkbottle.bot import Message
import asyncio
from middlewares.registration import registered_chats
from vkbottle.dispatch.rules.base import PayloadRule
from random import choice, randint
tea_keys = [x.strip() for x in open("teakeys.txt", "r", encoding="utf-8").readlines()]
fortu... | 0.310799 | 0.173411 |
import sys
import requests
import socket
import json
if len(sys.argv) < 2:
print("usage: " + sys.argv[0] + "<url>")
sys.exit(1)
print("_____________________________________________________________________________________________________")
print(" |\ \|\ ___ \|\ _____\\ __ \ |\ _... | inforecon.py | import sys
import requests
import socket
import json
if len(sys.argv) < 2:
print("usage: " + sys.argv[0] + "<url>")
sys.exit(1)
print("_____________________________________________________________________________________________________")
print(" |\ \|\ ___ \|\ _____\\ __ \ |\ _... | 0.086867 | 0.058319 |
__all__ = ('run_tests_in', )
from os.path import isfile as is_file, split as split_paths
from sys import path as system_paths, stdout
from .exceptions import TestLoadingError
from .test_file import __file__ as VAMPYTEST_TEST_FILE_PATH
from .test_file_collector import collect_test_files
from scarletio import render_e... | vampytest/core/runner.py | __all__ = ('run_tests_in', )
from os.path import isfile as is_file, split as split_paths
from sys import path as system_paths, stdout
from .exceptions import TestLoadingError
from .test_file import __file__ as VAMPYTEST_TEST_FILE_PATH
from .test_file_collector import collect_test_files
from scarletio import render_e... | 0.494385 | 0.30319 |
# Coded triangle numbers
# Problem 42
# The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# By converting each letter in a word to a number corresponding to its
# alphabetical position and adding these values ... | projecteuler.net/problem_042.py |
# Coded triangle numbers
# Problem 42
# The nth term of the sequence of triangle numbers is given by, tn = ½n(n+1); so the first ten triangle numbers are:
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
# By converting each letter in a word to a number corresponding to its
# alphabetical position and adding these values ... | 0.816991 | 0.637503 |
import os, sys, time, subprocess, fnmatch
import numpy as np
TSLP = 0.1
def execute (jobs, nproc, nt=-1, name="anonymous", sh=False, tsleep=TSLP):
if int(nt) > 0: os.environ['OMP_NUM_THREADS'] = str(nt)
tic = time.time()
procs = list()
while True:
_procs = procs[:]
for p in procs:
if p.poll() is ... | src/gadget/python/script_util.py | import os, sys, time, subprocess, fnmatch
import numpy as np
TSLP = 0.1
def execute (jobs, nproc, nt=-1, name="anonymous", sh=False, tsleep=TSLP):
if int(nt) > 0: os.environ['OMP_NUM_THREADS'] = str(nt)
tic = time.time()
procs = list()
while True:
_procs = procs[:]
for p in procs:
if p.poll() is ... | 0.159217 | 0.173954 |
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING... | turismo/turismo/settings.py | import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING... | 0.290477 | 0.063744 |
import copy
import os
from waflib import Task
from waflib import TaskGen
from waflib.Utils import winreg
class candle(Task.Task):
run_str = ("${CANDLE} -nologo ${CANDLEFLAGS} -out ${TGT} ${SRC[0].abspath()}",)
class light(Task.Task):
run_str = "${LIGHT} -nologo -b ${SRC[0].parent.abspath()} ${LIGHTFLAGS} -... | lectures/extensions/hyperbolic_discounting/replication_code/.mywaflib/waflib/extras/wix.py | import copy
import os
from waflib import Task
from waflib import TaskGen
from waflib.Utils import winreg
class candle(Task.Task):
run_str = ("${CANDLE} -nologo ${CANDLEFLAGS} -out ${TGT} ${SRC[0].abspath()}",)
class light(Task.Task):
run_str = "${LIGHT} -nologo -b ${SRC[0].parent.abspath()} ${LIGHTFLAGS} -... | 0.191706 | 0.060335 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the Licens... | tests/vec3_unit_test.py |
# Licensed under the Apache License, Version 2.0 (the "License"); you may not
# use this file except in compliance with the License. You may obtain a copy of
# the License at http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the Licens... | 0.947478 | 0.819857 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | product/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
... | 0.468791 | 0.126812 |
from os.path import dirname
from os import makedirs
import torch
import torchaudio
import subprocess
from tqdm import tqdm
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib.patches import Rectangle
from vap_turn_taking.plot_utils import plot_vad_oh
mpl.use("ag... | vap_turn_taking/animation.py | from os.path import dirname
from os import makedirs
import torch
import torchaudio
import subprocess
from tqdm import tqdm
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import animation
from matplotlib.patches import Rectangle
from vap_turn_taking.plot_utils import plot_vad_oh
mpl.use("ag... | 0.611266 | 0.224438 |
import sys
import re
def appref(m):
return '@@appendix@@{}@@'.format(m.group(1))
appref.pattern = re.compile(r'\\appref{(.+?)}')
def chapref(m):
return '@@chapter@@{}@@'.format(m.group(1))
chapref.pattern = re.compile(r'\\chapref{(.+?)}')
def cite(m):
return '@@cite@@{}@@'.format(m.group(1))
cite.pat... | bin/tex2md.py |
import sys
import re
def appref(m):
return '@@appendix@@{}@@'.format(m.group(1))
appref.pattern = re.compile(r'\\appref{(.+?)}')
def chapref(m):
return '@@chapter@@{}@@'.format(m.group(1))
chapref.pattern = re.compile(r'\\chapref{(.+?)}')
def cite(m):
return '@@cite@@{}@@'.format(m.group(1))
cite.pat... | 0.304145 | 0.174797 |
from django.urls import reverse
from rest_framework import status
from authors.base_test_config import TestUsingLoggedInUser
from authors.apps.articles.tests.test_config import TestConfig
class TestReadArticle(TestUsingLoggedInUser, TestConfig):
"""
test suite for user read stat
"""
def retrieve_user... | authors/apps/read_stats/tests/test_read_article.py | from django.urls import reverse
from rest_framework import status
from authors.base_test_config import TestUsingLoggedInUser
from authors.apps.articles.tests.test_config import TestConfig
class TestReadArticle(TestUsingLoggedInUser, TestConfig):
"""
test suite for user read stat
"""
def retrieve_user... | 0.478529 | 0.177668 |
import traceback
import sys
import json
from django.shortcuts import render
from django.template import RequestContext
from django.conf import settings
from django.middleware.csrf import get_token
import zerorpc
from geocamPycroraptor2 import status as statuslib
def getPyraptordClient(clientName='pyraptord'):
p... | geocamPycroraptor2/views.py | import traceback
import sys
import json
from django.shortcuts import render
from django.template import RequestContext
from django.conf import settings
from django.middleware.csrf import get_token
import zerorpc
from geocamPycroraptor2 import status as statuslib
def getPyraptordClient(clientName='pyraptord'):
p... | 0.161023 | 0.048586 |
import sys
from os.path import abspath, dirname, isabs, join
from sphinx_base import gen_main
CLASSES = [
"BicopFamily",
"Bicop",
"FitControlsBicop",
"Vinecop",
"FitControlsVinecop",
"CVineStructure",
"DVineStructure",
"RVineStructure"
]
FUNCTIONS = [
"to_pseudo_obs",
"simulat... | docs/gen_sphinx.py | import sys
from os.path import abspath, dirname, isabs, join
from sphinx_base import gen_main
CLASSES = [
"BicopFamily",
"Bicop",
"FitControlsBicop",
"Vinecop",
"FitControlsVinecop",
"CVineStructure",
"DVineStructure",
"RVineStructure"
]
FUNCTIONS = [
"to_pseudo_obs",
"simulat... | 0.240775 | 0.147218 |
import asyncio
import shlex
from typing import Tuple
from git import Repo
from git.exc import GitCommandError, InvalidGitRepositoryError
import config
from ..logging import LOGGER
def install_req(cmd: str) -> Tuple[str, str, int, int]:
async def install_requirements():
args = shlex.split(cmd)
... | YukkiMusic/core/git.py |
import asyncio
import shlex
from typing import Tuple
from git import Repo
from git.exc import GitCommandError, InvalidGitRepositoryError
import config
from ..logging import LOGGER
def install_req(cmd: str) -> Tuple[str, str, int, int]:
async def install_requirements():
args = shlex.split(cmd)
... | 0.376852 | 0.059949 |
import unittest
from user import User,Credentials
class TestUser(unittest.TestCase):
"""
Test class that defines test cases for the user class behaviours
"""
"""
Args:
unittest.TestCase: TestCase class that helps in creating test cases
"""
def setUp(self):
"""
Set up ... | user_test.py | import unittest
from user import User,Credentials
class TestUser(unittest.TestCase):
"""
Test class that defines test cases for the user class behaviours
"""
"""
Args:
unittest.TestCase: TestCase class that helps in creating test cases
"""
def setUp(self):
"""
Set up ... | 0.59408 | 0.478102 |
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
from sklearn import preprocessing
## input here
dataSetName = "breast-cancer" # diabetes breast-cancer australian
numofEXP = 10
scenarioList = ["SynTR_OrgTE"]
metho... | Ch6/PrivSyn_Demo/PythonTesting/Testing_LinearRegression.py | import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
from sklearn import preprocessing
## input here
dataSetName = "breast-cancer" # diabetes breast-cancer australian
numofEXP = 10
scenarioList = ["SynTR_OrgTE"]
metho... | 0.504639 | 0.577138 |
from flask import request
from logger import logger
from resources.tools import *
import datetime, time, pytz, json
class Merchandising():
def __init__(self, app, conn, cur):
self.connector = conn
self.cursor = cur
self.tools = Tools()
def get_all(self):
logger.info('[get_all]... | api/resources/merchandising.py | from flask import request
from logger import logger
from resources.tools import *
import datetime, time, pytz, json
class Merchandising():
def __init__(self, app, conn, cur):
self.connector = conn
self.cursor = cur
self.tools = Tools()
def get_all(self):
logger.info('[get_all]... | 0.470493 | 0.187226 |
import numpy as np
import matplotlib.pyplot as plt
from os import listdir
def extractMeshConv(angles = (0, 6, 15)):
from matplotlib.ticker import MultipleLocator
abspath = "./Panel_code/results/"
folders = listdir(abspath)
#here we parse the folder names
data = {'0deg' : None,'6deg' : None,'15deg' ... | processor.py | import numpy as np
import matplotlib.pyplot as plt
from os import listdir
def extractMeshConv(angles = (0, 6, 15)):
from matplotlib.ticker import MultipleLocator
abspath = "./Panel_code/results/"
folders = listdir(abspath)
#here we parse the folder names
data = {'0deg' : None,'6deg' : None,'15deg' ... | 0.238462 | 0.290264 |
import os
import traceback
import types
import unicodedata
import datetime
import urllib
import time
import re
import platform
import subprocess
from bs4 import UnicodeDammit
import chardet
from babelfish import Language
from subzero.analytics import track_event
# Unicode control characters can appear in ID3v2 tag... | Contents/Code/support/helpers.py | import os
import traceback
import types
import unicodedata
import datetime
import urllib
import time
import re
import platform
import subprocess
from bs4 import UnicodeDammit
import chardet
from babelfish import Language
from subzero.analytics import track_event
# Unicode control characters can appear in ID3v2 tag... | 0.459804 | 0.167355 |
import numpy as np
import onnxruntime
import pandas as pd
import torch
from pathlib import PosixPath
from pickle import load
from sklearn.preprocessing import MinMaxScaler
from make_us_rich.pipelines.preprocessing import extract_features_from_dataset
from make_us_rich.pipelines.converting import to_numpy
class Onnx... | make_us_rich/serving/model.py | import numpy as np
import onnxruntime
import pandas as pd
import torch
from pathlib import PosixPath
from pickle import load
from sklearn.preprocessing import MinMaxScaler
from make_us_rich.pipelines.preprocessing import extract_features_from_dataset
from make_us_rich.pipelines.converting import to_numpy
class Onnx... | 0.900074 | 0.271285 |
import os
from languages.asp.asp_input_program import ASPInputProgram
from src.constants import RESOURCES_PATH
from src.dlvsolution.helpers import chooseDLVSystem, InputNode, Edge, Swap
failureException = ValueError
def assertTrue(expr, msg=None):
"""Check that the expression is true."""
if not expr... | AI/src/dlvsolution/dlvsolution.py | import os
from languages.asp.asp_input_program import ASPInputProgram
from src.constants import RESOURCES_PATH
from src.dlvsolution.helpers import chooseDLVSystem, InputNode, Edge, Swap
failureException = ValueError
def assertTrue(expr, msg=None):
"""Check that the expression is true."""
if not expr... | 0.403684 | 0.227662 |
from django.urls import path
from config import views
urlpatterns_admin = [
path('api/admin/config/shop-info/', views.AdminConfigShopInfoView.as_view()), # 店铺信息获取
path('api/admin/config/print-info/', views.AdminConfigPrintInfoView.as_view()), # 打印信息获取
path('api/admin/config/msg-notify/', views.AdminCon... | wsc_django/wsc_django/apps/config/urls.py | from django.urls import path
from config import views
urlpatterns_admin = [
path('api/admin/config/shop-info/', views.AdminConfigShopInfoView.as_view()), # 店铺信息获取
path('api/admin/config/print-info/', views.AdminConfigPrintInfoView.as_view()), # 打印信息获取
path('api/admin/config/msg-notify/', views.AdminCon... | 0.164014 | 0.028844 |
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
from github.com.metaprov.modelaapi.services.notebook.v1 import notebook_pb2 as github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_notebook_dot_v1_dot_notebook__pb2
class NotebookServiceStub(object):
"""Missing associa... | lang/python/github/com/metaprov/modelaapi/services/notebook/v1/notebook_pb2_grpc.py | """Client and server classes corresponding to protobuf-defined services."""
import grpc
from github.com.metaprov.modelaapi.services.notebook.v1 import notebook_pb2 as github_dot_com_dot_metaprov_dot_modelaapi_dot_services_dot_notebook_dot_v1_dot_notebook__pb2
class NotebookServiceStub(object):
"""Missing associa... | 0.742515 | 0.109064 |
import cv2
import numpy as np
global prevgray
prevgray = cv2.cvtColor(cv2.VideoCapture(0).read()[1], cv2.COLOR_BGR2GRAY)
def draw_flow(img, flow, step=16):
h, w = img.shape[:2]
y, x = np.mgrid[step / 2:h:step, step / 2:w:step].reshape(2, -1).astype(int)
fx, fy = flow[y, x].T
lines = np.vstack([x, y, ... | LCD_RUN.py | import cv2
import numpy as np
global prevgray
prevgray = cv2.cvtColor(cv2.VideoCapture(0).read()[1], cv2.COLOR_BGR2GRAY)
def draw_flow(img, flow, step=16):
h, w = img.shape[:2]
y, x = np.mgrid[step / 2:h:step, step / 2:w:step].reshape(2, -1).astype(int)
fx, fy = flow[y, x].T
lines = np.vstack([x, y, ... | 0.229018 | 0.484807 |
import subprocess
import requests
from tests.endtoend import base
from tests.endtoend.utils import config
class TestIpRestrictions(base.TestBase):
@classmethod
def setUpClass(cls):
super(TestIpRestrictions, cls).setUpClass()
cls.test_config = config.TestConfig()
cls.check_precondi... | tests/endtoend/test_ip_restrictions.py |
import subprocess
import requests
from tests.endtoend import base
from tests.endtoend.utils import config
class TestIpRestrictions(base.TestBase):
@classmethod
def setUpClass(cls):
super(TestIpRestrictions, cls).setUpClass()
cls.test_config = config.TestConfig()
cls.check_precondi... | 0.54359 | 0.292494 |
# the number in the key represents the number to multiply the
# the value by such that it becomes the SI unit
mm = 0.001
cm = 0.01
m = 1
N = 1
kN = 1000
METRIC_UNITS = {
'length': {'mm':mm, 'cm':cm, 'm':m},
'force': {'N':N, 'kN':kN},
'moment': {'N.mm':N*mm, 'kN.mm':kN*mm, 'N.m':N*m, 'kN.m':kN*m},
'distributed': {'N... | indeterminatebeam/units.py |
# the number in the key represents the number to multiply the
# the value by such that it becomes the SI unit
mm = 0.001
cm = 0.01
m = 1
N = 1
kN = 1000
METRIC_UNITS = {
'length': {'mm':mm, 'cm':cm, 'm':m},
'force': {'N':N, 'kN':kN},
'moment': {'N.mm':N*mm, 'kN.mm':kN*mm, 'N.m':N*m, 'kN.m':kN*m},
'distributed': {'N... | 0.379723 | 0.497192 |
import jwt
import json
from typing import List
from functools import wraps
from flask import Blueprint, request, make_response
from flask_restful import Api
from simplexml import dumps
from werkzeug.wrappers import Response
from werkzeug.http import HTTP_STATUS_CODES
from sqlalchemy.ext.declarative import DeclarativeM... | src/utils/http.py | import jwt
import json
from typing import List
from functools import wraps
from flask import Blueprint, request, make_response
from flask_restful import Api
from simplexml import dumps
from werkzeug.wrappers import Response
from werkzeug.http import HTTP_STATUS_CODES
from sqlalchemy.ext.declarative import DeclarativeM... | 0.60054 | 0.103431 |
import sqlite3
import os
import time
from flask import g
from app.myfunctions import get_dblp_url
from app.databases.create_sqlitedb import get_mysql_db
curpath = os.path.dirname(os.path.realpath(__file__))
DATABASE = os.path.join(curpath, 'static', 'pycsrankings.sqlite3')
def mysql_get_db():
db = getattr(g, '_... | app/databases/querydb.py | import sqlite3
import os
import time
from flask import g
from app.myfunctions import get_dblp_url
from app.databases.create_sqlitedb import get_mysql_db
curpath = os.path.dirname(os.path.realpath(__file__))
DATABASE = os.path.join(curpath, 'static', 'pycsrankings.sqlite3')
def mysql_get_db():
db = getattr(g, '_... | 0.331985 | 0.157008 |
import csv
import requests
import polyline
import time
import json
db_points = []
# grab points from csv file - just grab, x, y, and a unique ID
# the headers may be different depending on your data!
with open("db.csv", 'r') as csvfile:
reader = csv.DictReader(csvfile)
n = 0
q = 0
for row in reader:
... | osrm_OD_matrix.py |
import csv
import requests
import polyline
import time
import json
db_points = []
# grab points from csv file - just grab, x, y, and a unique ID
# the headers may be different depending on your data!
with open("db.csv", 'r') as csvfile:
reader = csv.DictReader(csvfile)
n = 0
q = 0
for row in reader:
... | 0.137185 | 0.168754 |
from contextlib import suppress
import json
from io import BytesIO
import re
from sys import argv
import appex
from bs4 import BeautifulSoup
import clipboard
import photos
import PIL.Image
from requests import Session
class Page:
"""An image-containing page of saatchiart.com.
Raises:
ValueError: If ... | saatchi_downloader.py | from contextlib import suppress
import json
from io import BytesIO
import re
from sys import argv
import appex
from bs4 import BeautifulSoup
import clipboard
import photos
import PIL.Image
from requests import Session
class Page:
"""An image-containing page of saatchiart.com.
Raises:
ValueError: If ... | 0.549641 | 0.130202 |
def expect_type_error(fun):
from .parser import TypeError
try:
fun()
except TypeError as e:
print('Traceback (most recent call last):')
print('...')
print('TypeError: {}'.format(e))
class Tests(object):
"""Class containing test cases for Eightebed.
>>> from .parser... | src/eightebed/tests.py | def expect_type_error(fun):
from .parser import TypeError
try:
fun()
except TypeError as e:
print('Traceback (most recent call last):')
print('...')
print('TypeError: {}'.format(e))
class Tests(object):
"""Class containing test cases for Eightebed.
>>> from .parser... | 0.510985 | 0.517144 |
from collections import namedtuple
import fileinput
import sys
import torch
from fairseq import data, options, tasks, tokenizer, utils
from fairseq.sequence_generator import SequenceGenerator
from fairseq.utils import import_user_module
import os
import numpy as np
from collections import defaultdict
from fairseq.lm_... | interactive_spellchecked_rule.py | from collections import namedtuple
import fileinput
import sys
import torch
from fairseq import data, options, tasks, tokenizer, utils
from fairseq.sequence_generator import SequenceGenerator
from fairseq.utils import import_user_module
import os
import numpy as np
from collections import defaultdict
from fairseq.lm_... | 0.323273 | 0.147494 |