code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
from tkinter import Tk, Canvas, Frame, Label, Button, BOTH,\
TOP, BOTTOM, RIGHT, Radiobutton, StringVar
from main import Full_field, cells_number
MARGIN = 20 # Pixels around the board
SIDE = 30 # Width of every board cell.
# Width and height of the whole board
WIDTH = HEIGHT = MARGIN * 2 + SIDE * cells_nu... | GUI.py | from tkinter import Tk, Canvas, Frame, Label, Button, BOTH,\
TOP, BOTTOM, RIGHT, Radiobutton, StringVar
from main import Full_field, cells_number
MARGIN = 20 # Pixels around the board
SIDE = 30 # Width of every board cell.
# Width and height of the whole board
WIDTH = HEIGHT = MARGIN * 2 + SIDE * cells_nu... | 0.42322 | 0.183356 |
import abc
import numpy as np
class BaseHypervolume(object, metaclass=abc.ABCMeta):
"""Base class for hypervolume calculators.
.. note::
This class is used for computing the hypervolumes of points in multi-objective space.
Each coordinate of each point represents one value of the multi-objec... | optuna/multi_objective/_hypervolume/base.py | import abc
import numpy as np
class BaseHypervolume(object, metaclass=abc.ABCMeta):
"""Base class for hypervolume calculators.
.. note::
This class is used for computing the hypervolumes of points in multi-objective space.
Each coordinate of each point represents one value of the multi-objec... | 0.891563 | 0.648967 |
from math import ceil, sqrt
import numpy as np
from functools import partial
from pyKrig.utilities import pairwise_distance, mmcriterion
def latin_hypercube(nsample, ndv):
"""
create sample points for latin hypercube sampling
:param nsample: number of samples
:param ndv: number of design var... | pyKrig/latinhypercube.py | from math import ceil, sqrt
import numpy as np
from functools import partial
from pyKrig.utilities import pairwise_distance, mmcriterion
def latin_hypercube(nsample, ndv):
"""
create sample points for latin hypercube sampling
:param nsample: number of samples
:param ndv: number of design var... | 0.697918 | 0.528777 |
from matplotlib import pyplot as plt
import numpy as np
results = np.load("feedforwardtimings.npy")
#Raw Timings Plot Feedforward
plt.figure()
plt.suptitle("Feedforward", fontsize=24, y=1.05)
plt.subplot(2,2,1)
plt.title("Timing With Ten by Ten Sized Matrices")
plt.plot(results[:-1,0])
plt.scatter([5],results[-1:,0])... | PlotTestData.py | from matplotlib import pyplot as plt
import numpy as np
results = np.load("feedforwardtimings.npy")
#Raw Timings Plot Feedforward
plt.figure()
plt.suptitle("Feedforward", fontsize=24, y=1.05)
plt.subplot(2,2,1)
plt.title("Timing With Ten by Ten Sized Matrices")
plt.plot(results[:-1,0])
plt.scatter([5],results[-1:,0])... | 0.803444 | 0.567937 |
# Python compatibility:
from __future__ import absolute_import
from six import string_types as six_string_types
from six.moves import map
__author__ = "<NAME> <<EMAIL>>"
VERSION = (0,
6, # aufgeräumt
)
__version__ = '.'.join(map(str, VERSION))
# Standard library:
from collections import defau... | src/visaplan/plone/tools/brains.py | # Python compatibility:
from __future__ import absolute_import
from six import string_types as six_string_types
from six.moves import map
__author__ = "<NAME> <<EMAIL>>"
VERSION = (0,
6, # aufgeräumt
)
__version__ = '.'.join(map(str, VERSION))
# Standard library:
from collections import defau... | 0.449634 | 0.403332 |
import sys
import numpy as np
import pyzed.sl as sl
import cv2
import math
from utils.yolo_classes import get_cls_dict
from utils.visualization import BBoxVisualization
from utils.yolo_with_plugins import TrtYOLO
import os
import pycuda.autoinit
import time
def main() :
# Create a ZED camera object
zed = sl.Ca... | zed_trt.py | import sys
import numpy as np
import pyzed.sl as sl
import cv2
import math
from utils.yolo_classes import get_cls_dict
from utils.visualization import BBoxVisualization
from utils.yolo_with_plugins import TrtYOLO
import os
import pycuda.autoinit
import time
def main() :
# Create a ZED camera object
zed = sl.Ca... | 0.399694 | 0.26245 |
import numpy as np
import matplotlib.pyplot as plt
exact = np.loadtxt(
"examples/planar_hand/analysis/planar_hand_exact.csv",
delimiter=",")
first_order = np.loadtxt(
"examples/planar_hand/analysis/planar_hand_first_order.csv",
delimiter=",")
zero_order_B = np.loadtxt(
"examples/planar_hand/analysi... | examples/planar_hand/analysis/plot_cost.py | import numpy as np
import matplotlib.pyplot as plt
exact = np.loadtxt(
"examples/planar_hand/analysis/planar_hand_exact.csv",
delimiter=",")
first_order = np.loadtxt(
"examples/planar_hand/analysis/planar_hand_first_order.csv",
delimiter=",")
zero_order_B = np.loadtxt(
"examples/planar_hand/analysi... | 0.610337 | 0.571468 |
import itertools
import math
import numpy as np
from scipy.spatial.distance import cosine
avg_m1 = 0
avg_m2 = 0
initialized_avgs = False
def initialize_avgs(m1, m2):
global avg_m1, avg_m2, initialized_avgs
avg_m1 = np.average(m1[m1.wv.vocab], axis=0)
avg_m2 = np.average(m2[m2.wv.vocab], axis=0)
init... | cade/metrics/comparative.py | import itertools
import math
import numpy as np
from scipy.spatial.distance import cosine
avg_m1 = 0
avg_m2 = 0
initialized_avgs = False
def initialize_avgs(m1, m2):
global avg_m1, avg_m2, initialized_avgs
avg_m1 = np.average(m1[m1.wv.vocab], axis=0)
avg_m2 = np.average(m2[m2.wv.vocab], axis=0)
init... | 0.653127 | 0.388908 |
import torch
import numpy as np
from marl_coop.component.replay_buffer import convert_to_agent_tensor
from marl_coop.component import BufferCreator
from marl_coop.test.mock import Mock_buffer_config
def test_group_by_agent_convert_interleaved_agent_experience_into_batch_by_agent():
arg = np.array([[
... | marl_coop/component/tests/replay_buffer_test.py | import torch
import numpy as np
from marl_coop.component.replay_buffer import convert_to_agent_tensor
from marl_coop.component import BufferCreator
from marl_coop.test.mock import Mock_buffer_config
def test_group_by_agent_convert_interleaved_agent_experience_into_batch_by_agent():
arg = np.array([[
... | 0.799716 | 0.612744 |
from fruit.modules.step import Step, STATUS_ERR, STATUS_OK, STATUS_SKIPPED
import fruit.modules.console as console
import tabulate
import fruit.globals as glb
from .event import Event
from typing import Callable
class FruitError(Exception):
"""Error class for aborting the target make"""
pass
class Target(ob... | fruit/modules/target.py | from fruit.modules.step import Step, STATUS_ERR, STATUS_OK, STATUS_SKIPPED
import fruit.modules.console as console
import tabulate
import fruit.globals as glb
from .event import Event
from typing import Callable
class FruitError(Exception):
"""Error class for aborting the target make"""
pass
class Target(ob... | 0.768212 | 0.191517 |
import pytest
from slack_sdk.errors import SlackApiError
from runflow import runflow
pytest.importorskip('slack_sdk')
def test_slack_api_call_invalid_token(mocker, capsys):
async def chat_postMessage(**kwargs):
raise SlackApiError('invalid_auth', {'ok': False, 'error': 'invalid_auth'})
mock_client... | tests/community/test_slack.py | import pytest
from slack_sdk.errors import SlackApiError
from runflow import runflow
pytest.importorskip('slack_sdk')
def test_slack_api_call_invalid_token(mocker, capsys):
async def chat_postMessage(**kwargs):
raise SlackApiError('invalid_auth', {'ok': False, 'error': 'invalid_auth'})
mock_client... | 0.39222 | 0.161585 |
from psychsim.agent import Agent
from psychsim.world import World
from psychsim.pwl import makeTree, setToFeatureMatrix, dynamicsMatrix, rewardKey
from psychsim.reward import achieveFeatureValue, CONSTANT
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__description__ = 'Simple forward planning (discounted) example involv... | psychsim/examples/forward_planning.py | from psychsim.agent import Agent
from psychsim.world import World
from psychsim.pwl import makeTree, setToFeatureMatrix, dynamicsMatrix, rewardKey
from psychsim.reward import achieveFeatureValue, CONSTANT
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__description__ = 'Simple forward planning (discounted) example involv... | 0.714329 | 0.544922 |
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from django.core.exceptions import ValidationError
from django.conf import settings
import uuid
# Create your models here.
class Player(models.Model):
name = models.CharField(max_length=100)
number = models.... | tournament/models.py | from django.db import models
from django.utils import timezone
from django.utils.text import slugify
from django.core.exceptions import ValidationError
from django.conf import settings
import uuid
# Create your models here.
class Player(models.Model):
name = models.CharField(max_length=100)
number = models.... | 0.516352 | 0.111919 |
import os
import pdb
import json
import debug
import debug as Dbg
import config
import kvtable
import misc
import re
import itertools
from datetime import datetime
from datetime import timedelta
import config as Cfg
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all
patch_all()
import... | src/state.py | import os
import pdb
import json
import debug
import debug as Dbg
import config
import kvtable
import misc
import re
import itertools
from datetime import datetime
from datetime import timedelta
import config as Cfg
from aws_xray_sdk.core import xray_recorder
from aws_xray_sdk.core import patch_all
patch_all()
import... | 0.301362 | 0.07658 |
from rx.subjects import Subject
from motey.models.image_state import ImageState
from motey.utils.path_helper import absolute_file_path
class VALManager(object):
"""
Manger for all the virtual abstraction layer plugins.
Loads the plugins and wrapps the commands.
"""
def __init__(self, logger, cap... | motey/val/valmanager.py | from rx.subjects import Subject
from motey.models.image_state import ImageState
from motey.utils.path_helper import absolute_file_path
class VALManager(object):
"""
Manger for all the virtual abstraction layer plugins.
Loads the plugins and wrapps the commands.
"""
def __init__(self, logger, cap... | 0.824956 | 0.219588 |
import functools
import stem
import time
import sys
import stem.response.events
from . import control
from . import rendguard
from . import vanguards
from . import bandguards
from . import cbtverify
from . import config
from .logger import plog
_MIN_TOR_VERSION_FOR_BW = stem.version.Version("0.3.4.4-rc")
def main... | src/vanguards/main.py | import functools
import stem
import time
import sys
import stem.response.events
from . import control
from . import rendguard
from . import vanguards
from . import bandguards
from . import cbtverify
from . import config
from .logger import plog
_MIN_TOR_VERSION_FOR_BW = stem.version.Version("0.3.4.4-rc")
def main... | 0.113187 | 0.074064 |
import os
import sys
import shutil
import time
import random
import argparse
import cv2
import numpy
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
return True
parser = argparse.Arg... | run_dain.py | import os
import sys
import shutil
import time
import random
import argparse
import cv2
import numpy
def str2bool(v):
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v.lower() in ('no', 'false', 'f', 'n', '0'):
return False
else:
return True
parser = argparse.Arg... | 0.346984 | 0.097048 |
__copyright__ = 'Copyright 2021, FCRlab at University of Messina'
__author__ = '<NAME> <<EMAIL>>'
__credits__ = '<NAME> <<EMAIL>>'
__description__ = 'This project aims making easy the delivery of Call For Papers invitations.'
import argparse
import pandas as pd
from api.google.googleapi import GoogleAPI
def main():... | mailsend/main.py | __copyright__ = 'Copyright 2021, FCRlab at University of Messina'
__author__ = '<NAME> <<EMAIL>>'
__credits__ = '<NAME> <<EMAIL>>'
__description__ = 'This project aims making easy the delivery of Call For Papers invitations.'
import argparse
import pandas as pd
from api.google.googleapi import GoogleAPI
def main():... | 0.625095 | 0.062388 |
import os
from os import path
# 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/
# SECURI... | nydkcd11/nydkcd11/settings_production.py | import os
from os import path
# 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/
# SECURI... | 0.304869 | 0.0666 |
import numpy as np
import pandas as pd
def calculate_model_and_data_error(real_data, predictions, **kwargs):
""" This function compares and calculates the error between model prediction
and data.
Parameters
----------
real_data : pd.DataFrame with 2 columns
theta: float. Angle in r... | beamshapes/compare_predictions_to_data.py | import numpy as np
import pandas as pd
def calculate_model_and_data_error(real_data, predictions, **kwargs):
""" This function compares and calculates the error between model prediction
and data.
Parameters
----------
real_data : pd.DataFrame with 2 columns
theta: float. Angle in r... | 0.937569 | 0.730843 |
import logging
from typing import Dict, List, Optional, Tuple
import numpy as np
import reagent.core.types as rlt
import torch
from reagent.core.dataclasses import dataclass, field
from reagent.core.types import (
Dataset,
PreprocessingOptions,
ReaderOptions,
RewardOptions,
TableSpec,
)
from reage... | reagent/model_managers/actor_critic_base.py |
import logging
from typing import Dict, List, Optional, Tuple
import numpy as np
import reagent.core.types as rlt
import torch
from reagent.core.dataclasses import dataclass, field
from reagent.core.types import (
Dataset,
PreprocessingOptions,
ReaderOptions,
RewardOptions,
TableSpec,
)
from reage... | 0.919746 | 0.33444 |
import os
from pydgeot.processors.builtins import register_builtins
available = {}
""":type: dict[str, callable[pydgeot.app.App]"""
class Processor:
"""
Base class for file processors. When generating content, an App will call can_process on each registered Processor,
adding those that return True to a ... | pydgeot/processors/__init__.py | import os
from pydgeot.processors.builtins import register_builtins
available = {}
""":type: dict[str, callable[pydgeot.app.App]"""
class Processor:
"""
Base class for file processors. When generating content, an App will call can_process on each registered Processor,
adding those that return True to a ... | 0.680135 | 0.363562 |
import os
import re
import json
import collections
import logging
from urllib import parse
import distutils.util
from flask import Flask, request, jsonify
from fedora_messaging import message, api
DEFAULT_LOGGER_NAME =__name__
DEFAULT_TOPIC_TEMPLATE = '{web_url.hostname}.{web_url.path}.{object_kind}'
DEFAULT_IS_PROD... | images/gitlab-webhooks/gitlab-webhook/gitlab_webhook.py | import os
import re
import json
import collections
import logging
from urllib import parse
import distutils.util
from flask import Flask, request, jsonify
from fedora_messaging import message, api
DEFAULT_LOGGER_NAME =__name__
DEFAULT_TOPIC_TEMPLATE = '{web_url.hostname}.{web_url.path}.{object_kind}'
DEFAULT_IS_PROD... | 0.26086 | 0.060059 |
import asyncio
import sys
import types
from AsyncioMqttClient import Client
class AuthenticatedMqttClient(Client):
""" mqtt client supporting authentication"""
def __init__(self, hostname, port, username='', password=''):
"""constructor"""
super(AuthenticatedMqttClient, self).__init__(hostname... | hermod-python/src/MqttService.py | import asyncio
import sys
import types
from AsyncioMqttClient import Client
class AuthenticatedMqttClient(Client):
""" mqtt client supporting authentication"""
def __init__(self, hostname, port, username='', password=''):
"""constructor"""
super(AuthenticatedMqttClient, self).__init__(hostname... | 0.33112 | 0.068164 |
import numpy as np
import matplotlib.pyplot as plt
import os
from mpl_toolkits import mplot3d
from matplotlib import cm
import matplotlib as mpl
def norm_colours(values, lims=(-1,1)):
# Normalize colour values to between 0 and 1
maxcol = np.max(np.abs(values))
if type(lims) != tuple:
raise ValueErr... | cl_plot.py | import numpy as np
import matplotlib.pyplot as plt
import os
from mpl_toolkits import mplot3d
from matplotlib import cm
import matplotlib as mpl
def norm_colours(values, lims=(-1,1)):
# Normalize colour values to between 0 and 1
maxcol = np.max(np.abs(values))
if type(lims) != tuple:
raise ValueErr... | 0.393036 | 0.625724 |
import requests
from datetime import date, timedelta
from django.db.models import Q
from django.http import JsonResponse
from rest_framework.views import APIView
from cajas.general_config.models.country import Country
from cajas.office.models import Office, OfficeCountry
from cajas.users.models import Employee
cl... | cajas/reports/api/views/report_employee_salary.py | import requests
from datetime import date, timedelta
from django.db.models import Q
from django.http import JsonResponse
from rest_framework.views import APIView
from cajas.general_config.models.country import Country
from cajas.office.models import Office, OfficeCountry
from cajas.users.models import Employee
cl... | 0.28607 | 0.164181 |
from typing import Iterable, List, Dict
from game.blocks.block import AbstractBlock
from game.blocks.impl.deadly import DeadlyRockBlock
from game.blocks.impl.player import Player
from game.blocks.impl.stack import GameStack
from game.moveables.movable import Movable
from game.utils.game_error import GameError
from gam... | game/gamemap.py | from typing import Iterable, List, Dict
from game.blocks.block import AbstractBlock
from game.blocks.impl.deadly import DeadlyRockBlock
from game.blocks.impl.player import Player
from game.blocks.impl.stack import GameStack
from game.moveables.movable import Movable
from game.utils.game_error import GameError
from gam... | 0.87266 | 0.454956 |
import os
import pandas as pd
import numpy as np
import pydicom
from argparse import ArgumentParser
def get_boxes_per_patient(df, pId):
"""
Given the dataset and one patient ID,
return an array of all the bounding boxes and their labels associated with that patient ID.
Example of return:
array([[x... | data_processing.py | import os
import pandas as pd
import numpy as np
import pydicom
from argparse import ArgumentParser
def get_boxes_per_patient(df, pId):
"""
Given the dataset and one patient ID,
return an array of all the bounding boxes and their labels associated with that patient ID.
Example of return:
array([[x... | 0.705075 | 0.441492 |
import os
import numpy as np
import pandas as pd
from glob import glob
import scipy.constants as const
from astropy.constants import c
PACKAGE_PATH = os.path.dirname(__file__)
FILTER_DIR = os.path.join(PACKAGE_PATH, 'data/filters/')
__all__ = ['zero_point',
'list_available_filter',
'list_availab... | astrotools/filters.py | import os
import numpy as np
import pandas as pd
from glob import glob
import scipy.constants as const
from astropy.constants import c
PACKAGE_PATH = os.path.dirname(__file__)
FILTER_DIR = os.path.join(PACKAGE_PATH, 'data/filters/')
__all__ = ['zero_point',
'list_available_filter',
'list_availab... | 0.654232 | 0.431405 |
from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
from odoo.exceptions import UserError, ValidationError
@tagged('post_install', '-at_install')
class TestAccountAccount(AccountTestInvoicingCommon):
def test_changing_account_company(self):
''' Ensure you... | addons/account/tests/test_account_account.py | from odoo.addons.account.tests.common import AccountTestInvoicingCommon
from odoo.tests import tagged
from odoo.exceptions import UserError, ValidationError
@tagged('post_install', '-at_install')
class TestAccountAccount(AccountTestInvoicingCommon):
def test_changing_account_company(self):
''' Ensure you... | 0.658418 | 0.379091 |
__author__ = "<NAME>"
__version__ = "0.1"
import os, sys
from dataclasses import dataclass
from typing import List
import functools
import operator
import numpy as np
from astropy import units as u
from astropy import constants as const
from astropy.table import QTable, Column
from colorama import Fore
from colorama... | gleam/spectra_operations.py | __author__ = "<NAME>"
__version__ = "0.1"
import os, sys
from dataclasses import dataclass
from typing import List
import functools
import operator
import numpy as np
from astropy import units as u
from astropy import constants as const
from astropy.table import QTable, Column
from colorama import Fore
from colorama... | 0.807878 | 0.725588 |
import csv
from csv import DictReader
import json
import os
from pathlib import Path
import requests
import time
from tkinter import *
from tkinter import filedialog
from tkinter import ttk
import sys
# Create GUI for getting user input
window = Tk()
window.title('Get dataset metadata')
window.geometry('650x600') # ... | other_scripts/get-dataverse-metadata/get_dataset_json_metadata.py |
import csv
from csv import DictReader
import json
import os
from pathlib import Path
import requests
import time
from tkinter import *
from tkinter import filedialog
from tkinter import ttk
import sys
# Create GUI for getting user input
window = Tk()
window.title('Get dataset metadata')
window.geometry('650x600') # ... | 0.371023 | 0.092196 |
import os
import cv2
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
import numpy as np
from scipy.spatial.transform import Rotation as R
import imageio
import json
import h5py
import math
import argparse
from src.utils.RMatrix import RMatrix
parser = argparse.ArgumentParser()
parser.add_a... | data/7scenes_to_hdf5.py | import os
import cv2
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
import numpy as np
from scipy.spatial.transform import Rotation as R
import imageio
import json
import h5py
import math
import argparse
from src.utils.RMatrix import RMatrix
parser = argparse.ArgumentParser()
parser.add_a... | 0.167866 | 0.176281 |
from math import inf
from uuid import uuid4
from typing import Dict, List, Tuple
from polyA.performance import timeit
@timeit()
def get_path(
columns: List[int],
ids: List[str],
subfams_collapse: List[str],
last_column: List[float],
active_cells_collapse: Dict[int, List[int]],
origin_matrix: ... | polyA/get_path.py | from math import inf
from uuid import uuid4
from typing import Dict, List, Tuple
from polyA.performance import timeit
@timeit()
def get_path(
columns: List[int],
ids: List[str],
subfams_collapse: List[str],
last_column: List[float],
active_cells_collapse: Dict[int, List[int]],
origin_matrix: ... | 0.782538 | 0.740491 |
from collections.abc import MutableMapping, Sequence
from functools import lru_cache
from urllib.parse import urljoin, urlsplit, urlunsplit, unquote
class _Resolver(object):
def __init__(self, base_uri, referrer):
self._scopes_stack = [base_uri]
self._store = _URIDict()
self._store[base_ur... | pyramid_oas3/jsonschema/_resolvers.py | from collections.abc import MutableMapping, Sequence
from functools import lru_cache
from urllib.parse import urljoin, urlsplit, urlunsplit, unquote
class _Resolver(object):
def __init__(self, base_uri, referrer):
self._scopes_stack = [base_uri]
self._store = _URIDict()
self._store[base_ur... | 0.717507 | 0.095307 |
import tensorflow as tf
import os
import sys
import numpy as np
from numpy import *
import scipy.io
import multiprocessing
import datum_pb2
import lmdb
import timeit
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
return tf.train.Featu... | tfrecord-utils/make_tfrecord.py | import tensorflow as tf
import os
import sys
import numpy as np
from numpy import *
import scipy.io
import multiprocessing
import datum_pb2
import lmdb
import timeit
def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))
def _bytes_feature(value):
return tf.train.Featu... | 0.348313 | 0.304752 |
import datetime
import flask
import hashlib
import itertools
import requests
from urlparse import urlparse, parse_qsl
from xml.dom import minidom
import foauth.providers
class Shutterfly(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'http://www.shutterfly.com/'
docs_url = 'ht... | services/shutterfly.py | import datetime
import flask
import hashlib
import itertools
import requests
from urlparse import urlparse, parse_qsl
from xml.dom import minidom
import foauth.providers
class Shutterfly(foauth.providers.OAuth2):
# General info about the provider
provider_url = 'http://www.shutterfly.com/'
docs_url = 'ht... | 0.52829 | 0.13201 |
import pytest
import codecs
import os
import sys
from pytest_localserver.http import ContentServer, Request, Response
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from urllib.parse import urlsplit
from widgetastic.browser import Browser
selenium_brows... | testing/conftest.py | import pytest
import codecs
import os
import sys
from pytest_localserver.http import ContentServer, Request, Response
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from urllib.parse import urlsplit
from widgetastic.browser import Browser
selenium_brows... | 0.324342 | 0.10904 |
write_single_value_template = ''' subroutine hdf_write_dataset_{ftype_name}_0(loc_id, dset_name, array, chunks, filter, processor, axis)
integer(HID_T), intent(in) :: loc_id ! local id in file
character(len=*), intent(in) :: dset_name ! name of dataset
{declaration}
integer, optional,... | core/template.py | write_single_value_template = ''' subroutine hdf_write_dataset_{ftype_name}_0(loc_id, dset_name, array, chunks, filter, processor, axis)
integer(HID_T), intent(in) :: loc_id ! local id in file
character(len=*), intent(in) :: dset_name ! name of dataset
{declaration}
integer, optional,... | 0.453746 | 0.181481 |
from __future__ import annotations
from itertools import repeat
from typing import Optional, Union, Tuple, Sequence, Iterable, List, cast, TYPE_CHECKING
from ..constants import FeatureType
if TYPE_CHECKING:
from ..eodata import EOPatch
class FeatureParser:
"""Class for parsing a variety of feature specifi... | core/eolearn/core/utils/parsing.py | from __future__ import annotations
from itertools import repeat
from typing import Optional, Union, Tuple, Sequence, Iterable, List, cast, TYPE_CHECKING
from ..constants import FeatureType
if TYPE_CHECKING:
from ..eodata import EOPatch
class FeatureParser:
"""Class for parsing a variety of feature specifi... | 0.944267 | 0.574484 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('clients', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('locations', '00... | app/clients/migrations/0002_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 = [
('clients', '0001_initial'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('locations', '00... | 0.479504 | 0.10004 |
import logging
from os import minor
import random
import numpy as np
from fastapi import APIRouter
import pandas as pd
from pydantic import BaseModel, Field, validator
log = logging.getLogger(__name__)
router = APIRouter()
user = pd.read_csv('app/spokane_zipcodes.csv', header='infer')
class Item(BaseModel):
""... | app/predict.py |
import logging
from os import minor
import random
import numpy as np
from fastapi import APIRouter
import pandas as pd
from pydantic import BaseModel, Field, validator
log = logging.getLogger(__name__)
router = APIRouter()
user = pd.read_csv('app/spokane_zipcodes.csv', header='infer')
class Item(BaseModel):
""... | 0.399694 | 0.253399 |
import io
import os
import random
import sys
from configparser import ConfigParser
from datetime import datetime
from itertools import islice
from pathlib import Path
from statistics import mean, stdev
from time import strftime
from typing import Union, Any, Dict, List
import torch
from torch.utils.data import Dataset... | src/deepproblog/utils/__init__.py | import io
import os
import random
import sys
from configparser import ConfigParser
from datetime import datetime
from itertools import islice
from pathlib import Path
from statistics import mean, stdev
from time import strftime
from typing import Union, Any, Dict, List
import torch
from torch.utils.data import Dataset... | 0.577734 | 0.269999 |
import copy
import csv
import numpy as np
import traceback
import requests
import json
import time
import boto
import alog
import logging
from boto.s3.key import Key
from StringIO import StringIO
from datetime import datetime
from django.db.utils import IntegrityError
from firecares.utils.arcgis2geojson import arcgis2g... | firecares/tasks/update.py | import copy
import csv
import numpy as np
import traceback
import requests
import json
import time
import boto
import alog
import logging
from boto.s3.key import Key
from StringIO import StringIO
from datetime import datetime
from django.db.utils import IntegrityError
from firecares.utils.arcgis2geojson import arcgis2g... | 0.383641 | 0.180431 |
from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
register = template.Library()
### Show an update instance ###
@register.inclusion_tag("feeds/update.html", takes_context=True)
def show_update(context, update):
feed_object = update.feed.feed_object
... | colab/apps/object_feeds/templatetags/object_feeds_tags.py | from django import template
from django.conf import settings
from django.core.urlresolvers import reverse
register = template.Library()
### Show an update instance ###
@register.inclusion_tag("feeds/update.html", takes_context=True)
def show_update(context, update):
feed_object = update.feed.feed_object
... | 0.368178 | 0.044514 |
import numpy
import math
import cv2
import random
import matplotlib
from scipy.special import gamma
import matplotlib.pyplot as plt
from functions import *
matplotlib.use("TkAgg")
def inverse_gamma(data, alpha=0.1, beta=0.1):
"""
Inverse gamma distributions
:param data: Data value
:param alpha: alpha ... | main.py | import numpy
import math
import cv2
import random
import matplotlib
from scipy.special import gamma
import matplotlib.pyplot as plt
from functions import *
matplotlib.use("TkAgg")
def inverse_gamma(data, alpha=0.1, beta=0.1):
"""
Inverse gamma distributions
:param data: Data value
:param alpha: alpha ... | 0.642545 | 0.739293 |
from mock import call, Mock
from pytest import fixture
from mailthon.enclosure import PlainText
from mailthon.postman import Session, Postman
from mailthon.response import SendmailResponse
from .utils import mocked_smtp, unicode
class FakeSession(Session):
def __init__(self, **kwargs):
self.opts = kwargs
... | tests/test_postman.py | from mock import call, Mock
from pytest import fixture
from mailthon.enclosure import PlainText
from mailthon.postman import Session, Postman
from mailthon.response import SendmailResponse
from .utils import mocked_smtp, unicode
class FakeSession(Session):
def __init__(self, **kwargs):
self.opts = kwargs
... | 0.567218 | 0.204938 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from third_party.nucleus.io import genomics_reader
from third_party.nucleus.io.python import reference_fai
from third_party.nucleus.protos import reference_pb2
# redacted
RefFastaHeader = ... | third_party/nucleus/io/fasta.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
from third_party.nucleus.io import genomics_reader
from third_party.nucleus.io.python import reference_fai
from third_party.nucleus.protos import reference_pb2
# redacted
RefFastaHeader = ... | 0.89664 | 0.327104 |
from typing import List
class Graph:
def __init__(self):
self.nodes = {}
def addNode(self, s: str):
self.nodes[s] = Node(s)
def addEdge(self, s1: str, s2: str):
self.nodes[s1].edges.append(self.nodes[s2])
self.nodes[s2].edges.append(self.nodes[s1])
def isNode(self, s... | hard/127-word-ladder.py | from typing import List
class Graph:
def __init__(self):
self.nodes = {}
def addNode(self, s: str):
self.nodes[s] = Node(s)
def addEdge(self, s1: str, s2: str):
self.nodes[s1].edges.append(self.nodes[s2])
self.nodes[s2].edges.append(self.nodes[s1])
def isNode(self, s... | 0.580828 | 0.41739 |
from __future__ import division
"""
If you want to divide floating point numbers, have this at the start of your file
"""
x= 5.2/2
print x
"""
This is just a list of a number of built in functions that Python uses.
"""
l1='abcd'
l2=['a', 'X', 'm', 'd']
l3=''
"""
Check if a string is empty. If it is, it'll return FA... | 8.py | from __future__ import division
"""
If you want to divide floating point numbers, have this at the start of your file
"""
x= 5.2/2
print x
"""
This is just a list of a number of built in functions that Python uses.
"""
l1='abcd'
l2=['a', 'X', 'm', 'd']
l3=''
"""
Check if a string is empty. If it is, it'll return FA... | 0.682256 | 0.429609 |
from configparser import ConfigParser
from enum import Enum
from functools import lru_cache
from pathlib import Path
from typing import IO, Any, Dict
import boto3
from smart_open import open
from ..exceptions import ArchiveUnavailable, FileExists
from .base import Storage
# Number of days to restore a file from Gla... | serac/storage/s3.py | from configparser import ConfigParser
from enum import Enum
from functools import lru_cache
from pathlib import Path
from typing import IO, Any, Dict
import boto3
from smart_open import open
from ..exceptions import ArchiveUnavailable, FileExists
from .base import Storage
# Number of days to restore a file from Gla... | 0.687525 | 0.106226 |
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# ... | pygrooveshark/examples/webapp/server.py |
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# ... | 0.437824 | 0.080973 |
import pytest
from scraper import nyc
PARSE_TRIP_ID_ARGNAMES = [
"trip_id",
"sub_division",
"effective_date",
"service_day",
"origin_time",
"trip_path",
"route_id",
"direction",
"path_identifier",
]
PARSE_TRIP_ID_PARAMS = [
(
"AFA19GEN-1037-Sunday-00_010600_1..S03R",
... | transit-time/scraper/tests/test_nyc.py | import pytest
from scraper import nyc
PARSE_TRIP_ID_ARGNAMES = [
"trip_id",
"sub_division",
"effective_date",
"service_day",
"origin_time",
"trip_path",
"route_id",
"direction",
"path_identifier",
]
PARSE_TRIP_ID_PARAMS = [
(
"AFA19GEN-1037-Sunday-00_010600_1..S03R",
... | 0.404272 | 0.397646 |
import sys
try:
from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *
except:
raise ImportError('PyOpenGL not installed properly.')
__timerN = 0
__timers = {}
def addTimer( callback, delay ):
global __timerN, __timers
__timerN += 1
__timers[ __timerN ] = (ca... | ExtractVideoFrameConvexHull/GLUTWindow.py |
import sys
try:
from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *
except:
raise ImportError('PyOpenGL not installed properly.')
__timerN = 0
__timers = {}
def addTimer( callback, delay ):
global __timerN, __timers
__timerN += 1
__timers[ __timerN ] = (ca... | 0.219923 | 0.081301 |
from manim import *
import numpy as np
import random
class Tute1(Scene):
def construct(self):
plane = NumberPlane(x_range=[-7,7,1], y_range=[-4,4,1]).add_coordinates()
box = Rectangle(stroke_color = GREEN_C, stroke_opacity=0.7, fill_color = RED_B, fill_opacity = 0.5, height=1, width=1)
... | BrianAmedee/repo/1Tutorial_Intro.py | from manim import *
import numpy as np
import random
class Tute1(Scene):
def construct(self):
plane = NumberPlane(x_range=[-7,7,1], y_range=[-4,4,1]).add_coordinates()
box = Rectangle(stroke_color = GREEN_C, stroke_opacity=0.7, fill_color = RED_B, fill_opacity = 0.5, height=1, width=1)
... | 0.390825 | 0.258186 |
import os, logging, types
import registry
from alchemy.unit import FunctionUnit, DerivedUnit, UNIT_TYPE_META, UNIT_TYPE_SIMPLE, UNIT_TYPE_SIMPLE_WRAP
log = logging.getLogger(__name__)
class Context:
def __init__(self):
self.registry = None
self.values = {}
self.flow = None
self.cu... | alchemy/engine.py | import os, logging, types
import registry
from alchemy.unit import FunctionUnit, DerivedUnit, UNIT_TYPE_META, UNIT_TYPE_SIMPLE, UNIT_TYPE_SIMPLE_WRAP
log = logging.getLogger(__name__)
class Context:
def __init__(self):
self.registry = None
self.values = {}
self.flow = None
self.cu... | 0.385259 | 0.146453 |
from tests.BaseCase import BaseCase
from unittest import mock
import requests
class TodayTest(BaseCase):
@mock.patch('requests.get')
def test_get_today_success(self, mocked_get):
# Arrange
mocked_get.return_value.json.return_value = {
'Global Quote': {
'01. symbol'... | src/backend/services/stock-service/tests/test_today.py | from tests.BaseCase import BaseCase
from unittest import mock
import requests
class TodayTest(BaseCase):
@mock.patch('requests.get')
def test_get_today_success(self, mocked_get):
# Arrange
mocked_get.return_value.json.return_value = {
'Global Quote': {
'01. symbol'... | 0.827724 | 0.271578 |
# piTempTemperature Temperature
import os
import hashlib
import struct
import socket
import syslog
import json
import sys
import threading
import time
import re
from pitmCfg import pitmCfg
class pitmTemperature:
def __init__(self):
self.logging = 2 # 1 = syslog, 2 = stderr
self.cfg = pitmCfg()
... | brewerslab-orig-slave/pitmTemperature.py |
# piTempTemperature Temperature
import os
import hashlib
import struct
import socket
import syslog
import json
import sys
import threading
import time
import re
from pitmCfg import pitmCfg
class pitmTemperature:
def __init__(self):
self.logging = 2 # 1 = syslog, 2 = stderr
self.cfg = pitmCfg()
... | 0.366363 | 0.117978 |
import higra as hg
import numpy as np
def dendrogram_purity(tree, leaf_labels):
"""
Weighted average of the purity of each node of the tree with respect to a ground truth
labelization of the tree leaves.
Let :math:`T` be a tree with leaves :math:`V=\{1, \ldots, n\}`.
Let :math:`C=\{C_1, \ldo... | higra/assessment/hierarchical_cost.py |
import higra as hg
import numpy as np
def dendrogram_purity(tree, leaf_labels):
"""
Weighted average of the purity of each node of the tree with respect to a ground truth
labelization of the tree leaves.
Let :math:`T` be a tree with leaves :math:`V=\{1, \ldots, n\}`.
Let :math:`C=\{C_1, \ldo... | 0.919188 | 0.880077 |
from abc import ABCMeta
class ServerPluginBase(object):
"""
server plugin base class. Methods are not declared abstract because the plugins should not
be forced to reimplement all of them.
"""
"""
The server plugin base must be abstract. It should not be instantiated.
"""
__metaclass_... | jsonrpc2_base/plugins/server/server_plugin_base.py | from abc import ABCMeta
class ServerPluginBase(object):
"""
server plugin base class. Methods are not declared abstract because the plugins should not
be forced to reimplement all of them.
"""
"""
The server plugin base must be abstract. It should not be instantiated.
"""
__metaclass_... | 0.793986 | 0.14777 |
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.9/howto/deployment/checklist/
# SECURITY WARNING: keep th... | symkala/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.9/howto/deployment/checklist/
# SECURITY WARNING: keep th... | 0.384565 | 0.069195 |
import torch
from torch.autograd import Variable
from scipy.misc import imresize
import numpy as np
from path import Path
import argparse
from tqdm import tqdm
from models import PoseExpNet
from inverse_warp import pose_vec2mat
import torch.nn.functional as F
parser = argparse.ArgumentParser(description='Script for P... | test_pose.py | import torch
from torch.autograd import Variable
from scipy.misc import imresize
import numpy as np
from path import Path
import argparse
from tqdm import tqdm
from models import PoseExpNet
from inverse_warp import pose_vec2mat
import torch.nn.functional as F
parser = argparse.ArgumentParser(description='Script for P... | 0.547948 | 0.235317 |
import math
from typing import List, Tuple, Union
import requests
import slack
import woodchips
from github import Issue, NamedUser, PaginatedList, PullRequest
LOGGER_NAME = 'pullbug'
DESCRIPTION_CONTINUATION = '...'
DESCRIPTION_MAX_LENGTH = 120
class Message:
@staticmethod
def send_discord_message(message... | pullbug/messages.py | import math
from typing import List, Tuple, Union
import requests
import slack
import woodchips
from github import Issue, NamedUser, PaginatedList, PullRequest
LOGGER_NAME = 'pullbug'
DESCRIPTION_CONTINUATION = '...'
DESCRIPTION_MAX_LENGTH = 120
class Message:
@staticmethod
def send_discord_message(message... | 0.563258 | 0.111531 |
import datetime
from influxdb_client.client.flux_table import FluxTable, FluxColumn, FluxRecord
from tests.base_test import BaseTest
class FluxObjectTest(BaseTest):
def test_create_structure(self):
_time = datetime.datetime(1970, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)
table = FluxTable()
... | tests/test_FluxObject.py | import datetime
from influxdb_client.client.flux_table import FluxTable, FluxColumn, FluxRecord
from tests.base_test import BaseTest
class FluxObjectTest(BaseTest):
def test_create_structure(self):
_time = datetime.datetime(1970, 1, 1, 0, 0, tzinfo=datetime.timezone.utc)
table = FluxTable()
... | 0.392337 | 0.396594 |
import unittest
import apache_beam as beam
from apache_beam.testing import test_pipeline
from apache_beam.testing import util
from dataflow import cq_attempts as sanitize_cq_attempts
from dataflow import new_cq_attempts
def _beam_equals(expected, actual):
if expected != actual:
raise util.BeamAssertExceptio... | packages/dataflow/test/new_cq_attempts_test.py |
import unittest
import apache_beam as beam
from apache_beam.testing import test_pipeline
from apache_beam.testing import util
from dataflow import cq_attempts as sanitize_cq_attempts
from dataflow import new_cq_attempts
def _beam_equals(expected, actual):
if expected != actual:
raise util.BeamAssertExceptio... | 0.598077 | 0.413063 |
from flask import Flask, jsonify, url_for, request
from flask_httpauth import HTTPBasicAuth
import sys, flask
import model
app = Flask(__name__)
auth = HTTPBasicAuth()
def spcall(qry, param, commit=False):
try:
dbo = model.DBconn()
cursor = dbo.getcursor()
cursor.callproc(qry, ... | main.py | from flask import Flask, jsonify, url_for, request
from flask_httpauth import HTTPBasicAuth
import sys, flask
import model
app = Flask(__name__)
auth = HTTPBasicAuth()
def spcall(qry, param, commit=False):
try:
dbo = model.DBconn()
cursor = dbo.getcursor()
cursor.callproc(qry, ... | 0.192501 | 0.040961 |
import pytest
from thenewboston_node.business_logic.models.block import Block
from thenewboston_node.business_logic.models.blockchain_state import BlockchainState
from thenewboston_node.business_logic.tests import factories
@pytest.mark.parametrize(
'long_name,short_name', (
('signer', 's'),
('me... | thenewboston_node/business_logic/tests/test_models/test_field_compaction.py | import pytest
from thenewboston_node.business_logic.models.block import Block
from thenewboston_node.business_logic.models.blockchain_state import BlockchainState
from thenewboston_node.business_logic.tests import factories
@pytest.mark.parametrize(
'long_name,short_name', (
('signer', 's'),
('me... | 0.640748 | 0.543711 |
import pytest
from pyDEA.core.gui_modules.navigation_frame_gui import NavigationForTableFrame
class TableFrameMock(object):
def __init__(self):
self.nb_rows = 100
self.display_data_called = False
def display_data(self, row_index):
self.display_data_called = True
@pytest.fixture
de... | tests/test_gui_navigation_frame.py | import pytest
from pyDEA.core.gui_modules.navigation_frame_gui import NavigationForTableFrame
class TableFrameMock(object):
def __init__(self):
self.nb_rows = 100
self.display_data_called = False
def display_data(self, row_index):
self.display_data_called = True
@pytest.fixture
de... | 0.580828 | 0.370795 |
from Table import Table
from Server import get_server
from PageCleaner import Uniq_Block
from Server import publish, post, cfg, cfg_reply_ajax_ok
HEADER = [
'<script type="text/javascript" src="/CTK/js/jquery.tablednd_0_5.js"></script>'
]
JS_INIT = """
$("#%(id)s").tableDnD({
onDrop: function (table, row) {
... | CTK/SortableList.py |
from Table import Table
from Server import get_server
from PageCleaner import Uniq_Block
from Server import publish, post, cfg, cfg_reply_ajax_ok
HEADER = [
'<script type="text/javascript" src="/CTK/js/jquery.tablednd_0_5.js"></script>'
]
JS_INIT = """
$("#%(id)s").tableDnD({
onDrop: function (table, row) {
... | 0.378574 | 0.083441 |
import sqlite3
conn0 = sqlite3.connect('northwind_small.sqlite3')
curs0 = conn0.cursor()
# What are the ten most expensive items (per unit price) in the database?
quer = '''
SELECT ProductName, UnitPrice
FROM Product
ORDER BY UnitPrice DESC
LIMIT 10;
'''
pricey = curs0.execute(quer).fetchall()
print('\n', 'What are... | DAVID_DODDS_Unit3_Sprint2_challenge/northwind_DDODDS.py | import sqlite3
conn0 = sqlite3.connect('northwind_small.sqlite3')
curs0 = conn0.cursor()
# What are the ten most expensive items (per unit price) in the database?
quer = '''
SELECT ProductName, UnitPrice
FROM Product
ORDER BY UnitPrice DESC
LIMIT 10;
'''
pricey = curs0.execute(quer).fetchall()
print('\n', 'What are... | 0.233794 | 0.53048 |
import json
import os, configparser
import requests
from django.core.mail import send_mail
from rest_framework.permissions import AllowAny
from rest_framework.viewsets import GenericViewSet
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from . import serializers
from dj... | wedding_api/mailjet/views.py | import json
import os, configparser
import requests
from django.core.mail import send_mail
from rest_framework.permissions import AllowAny
from rest_framework.viewsets import GenericViewSet
from rest_framework.generics import CreateAPIView
from rest_framework.response import Response
from . import serializers
from dj... | 0.328314 | 0.040961 |
# These are the key vertices of "The Cuttle"
VERTICES = [
# T
[
(15, 1),
(15, 51)
],
[
( 4, 51),
(30, 51)
],
# h
[
(35, 54),
(35, 2)
],
[
(35, 23),
(40, 32),
(49, 33),
(49, 2)
],
# e
[
... | BoldportClub/TheCuttle/ScopeTag/make_data.py |
# These are the key vertices of "The Cuttle"
VERTICES = [
# T
[
(15, 1),
(15, 51)
],
[
( 4, 51),
(30, 51)
],
# h
[
(35, 54),
(35, 2)
],
[
(35, 23),
(40, 32),
(49, 33),
(49, 2)
],
# e
[
... | 0.328099 | 0.55266 |
import json
from flask_jwt_extended import create_access_token
from app import app
from src.models.permission import PermissionModel
from src.models.role import RoleModel
from src.models.user import UserModel
from tests.test_base import TestBase
user_dict = {"username": "testusername", 'password': '<PASSWORD>'}
_rol... | tests/system/test_role_permission_system.py | import json
from flask_jwt_extended import create_access_token
from app import app
from src.models.permission import PermissionModel
from src.models.role import RoleModel
from src.models.user import UserModel
from tests.test_base import TestBase
user_dict = {"username": "testusername", 'password': '<PASSWORD>'}
_rol... | 0.358016 | 0.110184 |
import torch
from gpytorch.kernels import Kernel, ProductKernel
from edge.model.inference.tensorwrap import ensure_tensor
from edge.utils import device
def get_index_and_name(name):
split_name = name.split('.')
index = int(split_name[0])
pname = '.'.join(split_name[1:])
return index, pname
# TODO is... | edge/model/inference/kernels/custom_kernels.py | import torch
from gpytorch.kernels import Kernel, ProductKernel
from edge.model.inference.tensorwrap import ensure_tensor
from edge.utils import device
def get_index_and_name(name):
split_name = name.split('.')
index = int(split_name[0])
pname = '.'.join(split_name[1:])
return index, pname
# TODO is... | 0.520984 | 0.449755 |
import torch
import torch.nn as nn
class Residual(nn.Module):
def __init__(self, fn):
super().__init__()
self.fn = fn
def forward(self, x):
return self.fn(x) + x
class ConvMixer(nn.Module):
def __init__(self, dim, depth,
kernel_size = 9, patch_size = 7, num_classes = 1000... | model.py | import torch
import torch.nn as nn
class Residual(nn.Module):
def __init__(self, fn):
super().__init__()
self.fn = fn
def forward(self, x):
return self.fn(x) + x
class ConvMixer(nn.Module):
def __init__(self, dim, depth,
kernel_size = 9, patch_size = 7, num_classes = 1000... | 0.940626 | 0.437824 |
import warnings
from collections import Counter
from time import time
import numpy as np
from frozendict import frozendict
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.exceptions import ConvergenceWarning
from sklearn.linear_model import LogisticRegression, ElasticNet
from sklearn.model_select... | autoflow/feature_engineer/scale/adaptive.py | import warnings
from collections import Counter
from time import time
import numpy as np
from frozendict import frozendict
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.exceptions import ConvergenceWarning
from sklearn.linear_model import LogisticRegression, ElasticNet
from sklearn.model_select... | 0.580233 | 0.208743 |
# 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... | tests/test_decorator.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... | 0.923087 | 0.514827 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import csv
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
_URL = "http://spiechallenges.cloudapp.net/competitions/14#participate"
# BibTeX citation
_CITATION = """\
... | tensorflow_datasets/image/breastpathq.py |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import csv
import numpy as np
import tensorflow as tf
import tensorflow_datasets as tfds
_URL = "http://spiechallenges.cloudapp.net/competitions/14#participate"
# BibTeX citation
_CITATION = """\
... | 0.786991 | 0.327816 |
from django.contrib.auth.models import User as DjangoUser
from django.db import connection
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from djaveAPI.models.pretend_publishable import PretendPublishable
from djaveAPI.models.user_api_key import UserAPIKey
from djaveAPI.s... | djaveAPI/models/user.py | from django.contrib.auth.models import User as DjangoUser
from django.db import connection
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from djaveAPI.models.pretend_publishable import PretendPublishable
from djaveAPI.models.user_api_key import UserAPIKey
from djaveAPI.s... | 0.594198 | 0.084795 |
import scrapy
from scrapy import Request
import json
from ..items import AcordaoItem
import re
import json
from datetime import datetime
import sqlite3 as sql
class ApiSpider(scrapy.Spider):
name = "api"
def __init__(self, **kwargs):
self.year = kwargs.get('year', None)
self.conn = sql.connect... | crawlers/projects/api_acordaos/apiacordao/apiacordao/spiders/api.py | import scrapy
from scrapy import Request
import json
from ..items import AcordaoItem
import re
import json
from datetime import datetime
import sqlite3 as sql
class ApiSpider(scrapy.Spider):
name = "api"
def __init__(self, **kwargs):
self.year = kwargs.get('year', None)
self.conn = sql.connect... | 0.237841 | 0.057812 |
import numpy as np
import os
import sys
from astropy.io import ascii
# list of targets
names = ['CZTau', 'DPTau', 'FQTau', 'FSTau', 'FVTau', 'FXTau', 'GGTau',
'GHTau', 'GNTau', 'HLTau', 'Haro6-28', 'IRAS04260', 'IRAS04263',
'IRAS04301', 'ITG40', 'J04202144', 'J04210795', 'J04231822',
'J043... | avg_plx.py | import numpy as np
import os
import sys
from astropy.io import ascii
# list of targets
names = ['CZTau', 'DPTau', 'FQTau', 'FSTau', 'FVTau', 'FXTau', 'GGTau',
'GHTau', 'GNTau', 'HLTau', 'Haro6-28', 'IRAS04260', 'IRAS04263',
'IRAS04301', 'ITG40', 'J04202144', 'J04210795', 'J04231822',
'J043... | 0.067064 | 0.195498 |
import diggrtoolbox as dt
from copy import deepcopy
TESTDICT = {'key0': 'value0',
'key1': 'value2',
'key2': 'value2',
'key3': 'value3',
'key4': {'subkey0': 'subvalue0',
'subkey1': 'subvalue1', },
'key5': ['sublistelement0',
... | tests/test_treeexplore.py |
import diggrtoolbox as dt
from copy import deepcopy
TESTDICT = {'key0': 'value0',
'key1': 'value2',
'key2': 'value2',
'key3': 'value3',
'key4': {'subkey0': 'subvalue0',
'subkey1': 'subvalue1', },
'key5': ['sublistelement0',
... | 0.331769 | 0.435721 |
from matplotlib import pyplot as pp
import numpy as np
import DNA_manipulations as DNAm
#Places labels on top of bars within bar graph
def autolabel(bins, plotType, integer = True):
# attach some text labels
offSet = max([b.get_height() for b in bins])
for bins in bins:
height = bins.get_height()
... | Neural_network/GC Analysis.py | from matplotlib import pyplot as pp
import numpy as np
import DNA_manipulations as DNAm
#Places labels on top of bars within bar graph
def autolabel(bins, plotType, integer = True):
# attach some text labels
offSet = max([b.get_height() for b in bins])
for bins in bins:
height = bins.get_height()
... | 0.483892 | 0.476519 |
import sys
import numpy as np
import matplotlib
import matplotlib.pyplot
if __name__ == '__main__':
filename = 'aoc_day13_input.txt'
if len(sys.argv) > 1:
filename = sys.argv[1]
pre = 'fold along '
pre_len = len(pre)
with open(filename) as f:
points = []
folds = []
... | 2021/aoc_day13.py |
import sys
import numpy as np
import matplotlib
import matplotlib.pyplot
if __name__ == '__main__':
filename = 'aoc_day13_input.txt'
if len(sys.argv) > 1:
filename = sys.argv[1]
pre = 'fold along '
pre_len = len(pre)
with open(filename) as f:
points = []
folds = []
... | 0.211987 | 0.2667 |
import time
import threading
import configparser
HAS_281x_LIB = True
try:
from rpi_ws281x import *
except ImportError:
HAS_281x_LIB = False
class SingletonType(type):
_instance_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with Single... | led_display_config.py | import time
import threading
import configparser
HAS_281x_LIB = True
try:
from rpi_ws281x import *
except ImportError:
HAS_281x_LIB = False
class SingletonType(type):
_instance_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with Single... | 0.611498 | 0.059102 |
from sixtypical.model import (
RoutineType, ConstantRef, LocationRef, IndirectRef, IndexedRef,
)
class AnalysisContext(object):
"""
A location is touched if it was changed (or even potentially
changed) during this routine, or some routine called by this routine.
A location is meaningful if it wa... | src/sixtypical/context.py |
from sixtypical.model import (
RoutineType, ConstantRef, LocationRef, IndirectRef, IndexedRef,
)
class AnalysisContext(object):
"""
A location is touched if it was changed (or even potentially
changed) during this routine, or some routine called by this routine.
A location is meaningful if it wa... | 0.774882 | 0.313972 |
import json
from alipay.aop.api.constant.ParamConstants import *
class SpecifiedAsset(object):
def __init__(self):
self._bank_card_no = None
self._inst_id = None
self._pay_tool_type = None
self._specified_reason_code = None
@property
def bank_card_no(self):
retur... | alipay/aop/api/domain/SpecifiedAsset.py | import json
from alipay.aop.api.constant.ParamConstants import *
class SpecifiedAsset(object):
def __init__(self):
self._bank_card_no = None
self._inst_id = None
self._pay_tool_type = None
self._specified_reason_code = None
@property
def bank_card_no(self):
retur... | 0.625667 | 0.061396 |
import numpy as np
import pandas as pd
import sys
sys.path.append('../dsbase/src/main')
from sklearn.model_selection import train_test_split
from ModelDSBase import ModelDSBaseWrapper
from AdaBoostClassificationDSBase import AdaBoostClassificationDSBaseModelParamsToMap
from AdaBoostClassificationDSBase import AdaBoost... | utils/trainFold.py | import numpy as np
import pandas as pd
import sys
sys.path.append('../dsbase/src/main')
from sklearn.model_selection import train_test_split
from ModelDSBase import ModelDSBaseWrapper
from AdaBoostClassificationDSBase import AdaBoostClassificationDSBaseModelParamsToMap
from AdaBoostClassificationDSBase import AdaBoost... | 0.264074 | 0.241668 |
import json
from dataclasses import dataclass
from py2neo import Graph, Node, Relationship
from typing import List
from src.exception import IdNotFound, NoStartNodeFound
from src.model.exe_status import StatusInfo, Status, AdditionalInfo
from src.model.node_data import NodeData, RelationshipData, Identifier, Relation,... | src/storage/ongdb/db.py | import json
from dataclasses import dataclass
from py2neo import Graph, Node, Relationship
from typing import List
from src.exception import IdNotFound, NoStartNodeFound
from src.model.exe_status import StatusInfo, Status, AdditionalInfo
from src.model.node_data import NodeData, RelationshipData, Identifier, Relation,... | 0.625095 | 0.219526 |
import functools
import os
from PyInquirer import prompt, style_from_dict, Token
from typing import List, TYPE_CHECKING
from . import server
from ..common import chdir
from ..process_assignment import import_supporting, remove_supporting
from ..process_file import process_file
from ..process_file.file_result import Fi... | stograde/webapp/web_cli.py | import functools
import os
from PyInquirer import prompt, style_from_dict, Token
from typing import List, TYPE_CHECKING
from . import server
from ..common import chdir
from ..process_assignment import import_supporting, remove_supporting
from ..process_file import process_file
from ..process_file.file_result import Fi... | 0.341034 | 0.128908 |
import pytest
def test_app(app, client):
response = client.get('/')
assert response.data == b'OK'
def test_simple_view(app, api, client):
@api.route('/simple', methods=['GET', 'POST'])
def view(*args, **kwargs):
return {'ok': True}
assert view.methods == {'GET', 'POST'}
response =... | tests/test_base.py | import pytest
def test_app(app, client):
response = client.get('/')
assert response.data == b'OK'
def test_simple_view(app, api, client):
@api.route('/simple', methods=['GET', 'POST'])
def view(*args, **kwargs):
return {'ok': True}
assert view.methods == {'GET', 'POST'}
response =... | 0.558086 | 0.352536 |
import phydra
from .main import FirstInit, SecondInit
import xsimlab as xs
@phydra.comp(init_stage=2)
class SV:
"""represents a state variable in the model"""
var = phydra.variable(description='basic state variable')
@phydra.comp(init_stage=2)
class SVArray:
"""represents a state variable in the model... | phydra/components/variables.py | import phydra
from .main import FirstInit, SecondInit
import xsimlab as xs
@phydra.comp(init_stage=2)
class SV:
"""represents a state variable in the model"""
var = phydra.variable(description='basic state variable')
@phydra.comp(init_stage=2)
class SVArray:
"""represents a state variable in the model... | 0.662469 | 0.42674 |
from PySide.QtCore import *
from PySide.QtGui import *
class RichTextDelegate(QStyledItemDelegate):
def _make_document(self, text):
doc = QTextDocument()
doc.setHtml(text)
doc.setDocumentMargin(3)
return doc
def paint(self, painter, option, index):
option = QStyleOptio... | qygmy/uiutils.py | from PySide.QtCore import *
from PySide.QtGui import *
class RichTextDelegate(QStyledItemDelegate):
def _make_document(self, text):
doc = QTextDocument()
doc.setHtml(text)
doc.setDocumentMargin(3)
return doc
def paint(self, painter, option, index):
option = QStyleOptio... | 0.683208 | 0.129046 |
import struct
import ctypes
import capstone as cp
from typing import (
List,
Set,
Dict,
Tuple,
Generator
)
from ..extraction_context import ExtractionContext
from ..macho.macho_context import MachOContext
from ..converter import (
slide_info,
stub_fixer
)
from ..objc.objc_structs import (
objc_category_t,
o... | DyldExtractor/converter/objc_fixer.py | import struct
import ctypes
import capstone as cp
from typing import (
List,
Set,
Dict,
Tuple,
Generator
)
from ..extraction_context import ExtractionContext
from ..macho.macho_context import MachOContext
from ..converter import (
slide_info,
stub_fixer
)
from ..objc.objc_structs import (
objc_category_t,
o... | 0.455925 | 0.09314 |
from configparser import ConfigParser
from flask import Flask, jsonify, request
import logging.handlers
import logging
from bin.ram import RAM
from bin.cpu import CPU
from bin.network import Network
from bin.load_avg import LoadAvg
from bin.boot_time import BootTime
from bin.disk import Disk
# convert human sizes to... | agent/app.py | from configparser import ConfigParser
from flask import Flask, jsonify, request
import logging.handlers
import logging
from bin.ram import RAM
from bin.cpu import CPU
from bin.network import Network
from bin.load_avg import LoadAvg
from bin.boot_time import BootTime
from bin.disk import Disk
# convert human sizes to... | 0.226955 | 0.067424 |
import csv
from datetime import datetime
from collections import defaultdict
import dateutil.relativedelta
import json
import re
import utils
USAGECOST_DIR='in/usagecost'
METADATA_DIR='out/instance-metadata'
OUT_PATH_EBS = 'out/last-month/ebs.csv'
OUT_PATH_SNAPSHOTS = 'out/last-month/snapshots.csv'
BEGIN_LAST_MONTH... | src/get_last_month_ebs_cost.py |
import csv
from datetime import datetime
from collections import defaultdict
import dateutil.relativedelta
import json
import re
import utils
USAGECOST_DIR='in/usagecost'
METADATA_DIR='out/instance-metadata'
OUT_PATH_EBS = 'out/last-month/ebs.csv'
OUT_PATH_SNAPSHOTS = 'out/last-month/snapshots.csv'
BEGIN_LAST_MONTH... | 0.273477 | 0.099602 |
from collections import OrderedDict
from ektelo import workload
from ektelo.data import Relation
from ektelo.data import RelationHelper
import numpy as np
import os
from ektelo.plans import standalone
from ektelo.private import transformation
import unittest
import yaml
class TestPlans(unittest.TestCase):
seed =... | test/system/test_plans.py | from collections import OrderedDict
from ektelo import workload
from ektelo.data import Relation
from ektelo.data import RelationHelper
import numpy as np
import os
from ektelo.plans import standalone
from ektelo.private import transformation
import unittest
import yaml
class TestPlans(unittest.TestCase):
seed =... | 0.660939 | 0.375191 |
"""Tests for data_loader.py"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import pytest
from caliban_toolbox.pre_annotation import data_loader
def _get_dummy_inputs(object):
possible_data_type = random.choice([['2d', 'static'],
... | caliban_toolbox/pre_annotation/data_loader_test.py | """Tests for data_loader.py"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import random
import pytest
from caliban_toolbox.pre_annotation import data_loader
def _get_dummy_inputs(object):
possible_data_type = random.choice([['2d', 'static'],
... | 0.678859 | 0.331431 |
from datetime import date as dt_date
from typing import Tuple
BOTTOM_ROW_COUNT = 6
class Address(object):
__slots__ = ('name', 'street', 'postcode', 'city')
def __init__(self, name, street, postcode, city):
self.name = name
self.street = street
self.postcode = postcode
self.... | invoice_generator/models.py | from datetime import date as dt_date
from typing import Tuple
BOTTOM_ROW_COUNT = 6
class Address(object):
__slots__ = ('name', 'street', 'postcode', 'city')
def __init__(self, name, street, postcode, city):
self.name = name
self.street = street
self.postcode = postcode
self.... | 0.878679 | 0.098296 |
import os
import sys
import subprocess
import geopandas as gpd
import time
import yaml
import igraph as ig
import pandas as pd
from sklearn.neighbors import KDTree
from tqdm import tqdm
import numpy as np
def get_repo_root():
"""Get the root directory of the repo."""
dir_in_repo = os.path.dirname(os.path.absp... | src/py/multi-region-distance-error-computation.py | import os
import sys
import subprocess
import geopandas as gpd
import time
import yaml
import igraph as ig
import pandas as pd
from sklearn.neighbors import KDTree
from tqdm import tqdm
import numpy as np
def get_repo_root():
"""Get the root directory of the repo."""
dir_in_repo = os.path.dirname(os.path.absp... | 0.532668 | 0.234779 |