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 math
import numpy as np
from scipy import optimize
from range_estimator.hierarchy import Hierarchy
class SmoothHierarchy(Hierarchy):
def __init__(self, users, args):
Hierarchy.__init__(self, users, args)
self.fanout = 16
self.update_fanout()
self.g = self.args.g
... | range_estimator/smooth_hierarchy.py | import math
import numpy as np
from scipy import optimize
from range_estimator.hierarchy import Hierarchy
class SmoothHierarchy(Hierarchy):
def __init__(self, users, args):
Hierarchy.__init__(self, users, args)
self.fanout = 16
self.update_fanout()
self.g = self.args.g
... | 0.601359 | 0.466299 |
import numpy as np
import pytest
from just_bin_it.endpoints.serialisation import (
deserialise_ev42,
deserialise_hs00,
serialise_ev42,
serialise_hs00,
)
from just_bin_it.histograms.histogram1d import Histogram1d
from just_bin_it.histograms.histogram2d import Histogram2d
NUM_BINS = 5
X_RANGE = (0, 5)
Y... | tests/test_serialisation.py | import numpy as np
import pytest
from just_bin_it.endpoints.serialisation import (
deserialise_ev42,
deserialise_hs00,
serialise_ev42,
serialise_hs00,
)
from just_bin_it.histograms.histogram1d import Histogram1d
from just_bin_it.histograms.histogram2d import Histogram2d
NUM_BINS = 5
X_RANGE = (0, 5)
Y... | 0.662578 | 0.588712 |
import os
import sys
import pandas as pd
_thisdir = os.path.realpath(os.path.split(__file__)[0])
__all__=['template_pptx',
'font_path',
'chart_type_list',
'number_format_data',
'number_format_tick',
'font_default_size',
'summary_loc',
'chart_loc']
def _... | reportgen/config.py | import os
import sys
import pandas as pd
_thisdir = os.path.realpath(os.path.split(__file__)[0])
__all__=['template_pptx',
'font_path',
'chart_type_list',
'number_format_data',
'number_format_tick',
'font_default_size',
'summary_loc',
'chart_loc']
def _... | 0.206014 | 0.072308 |
from typing import Any, Dict, Mapping
from eduid_common.api.app import EduIDBaseApp
from eduid_common.api.logging import merge_config
from eduid_common.api.testing import EduidAPITestCase
from eduid_common.config.base import EduIDBaseAppConfig
__author__ = 'lundberg'
from eduid_common.config.parsers import load_con... | src/eduid_common/api/tests/test_logging.py |
from typing import Any, Dict, Mapping
from eduid_common.api.app import EduIDBaseApp
from eduid_common.api.logging import merge_config
from eduid_common.api.testing import EduidAPITestCase
from eduid_common.config.base import EduIDBaseAppConfig
__author__ = 'lundberg'
from eduid_common.config.parsers import load_con... | 0.63273 | 0.164081 |
import datetime as dt
import io
import json
from asyncio.exceptions import TimeoutError
from typing import Optional, Tuple
from aiogram import Bot, Dispatcher, executor, md, types
from aioredis import Redis
from aiotracemoeapi import TraceMoe, exceptions
from aiotracemoeapi.types import AniList, AnimeResponse
API_TO... | examples/redis_telegrambot.py | import datetime as dt
import io
import json
from asyncio.exceptions import TimeoutError
from typing import Optional, Tuple
from aiogram import Bot, Dispatcher, executor, md, types
from aioredis import Redis
from aiotracemoeapi import TraceMoe, exceptions
from aiotracemoeapi.types import AniList, AnimeResponse
API_TO... | 0.640299 | 0.102394 |
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import datetime # For datetime objects
import os.path # To manage paths
import sys # To find out the script name (in argv[0])
import math
import backtrader as bt
import time
import numpy as np
from tabulate ... | mywork/indicator/indicator_rsi.py | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import datetime # For datetime objects
import os.path # To manage paths
import sys # To find out the script name (in argv[0])
import math
import backtrader as bt
import time
import numpy as np
from tabulate ... | 0.21892 | 0.409634 |
from typing import Set
from keycloak_scanner.jwt_attack import change_to_none
from keycloak_scanner.keycloak_api import KeyCloakApi
from keycloak_scanner.logging.vuln_flag import VulnFlag
from keycloak_scanner.scan_base.scanner import Scanner
from keycloak_scanner.scan_base.types import NoneSign, Client, WellKnown, Se... | keycloak_scanner/scanners/none_sign_scanner.py | from typing import Set
from keycloak_scanner.jwt_attack import change_to_none
from keycloak_scanner.keycloak_api import KeyCloakApi
from keycloak_scanner.logging.vuln_flag import VulnFlag
from keycloak_scanner.scan_base.scanner import Scanner
from keycloak_scanner.scan_base.types import NoneSign, Client, WellKnown, Se... | 0.397588 | 0.085404 |
# In[ ]:
import tensorflow as tf
import numpy as np
import SSAE
reload(SSAE)
import matplotlib.pyplot as plt
import glob
import os
import sys
from scipy import signal
from IPython import display
get_ipython().magic(u'matplotlib inline')
# In[ ]:
sys.path.append('../FileOps/')
import FileIO
import PatchSample
# ... | Autoencoders/Train-stack.py |
# In[ ]:
import tensorflow as tf
import numpy as np
import SSAE
reload(SSAE)
import matplotlib.pyplot as plt
import glob
import os
import sys
from scipy import signal
from IPython import display
get_ipython().magic(u'matplotlib inline')
# In[ ]:
sys.path.append('../FileOps/')
import FileIO
import PatchSample
# ... | 0.355439 | 0.229018 |
def matrix_product(p):
"""Return m and s.
m[i][j] is the minimum number of scalar multiplications needed to compute the
product of matrices A(i), A(i + 1), ..., A(j).
s[i][j] is the index of the matrix after which the product is split in an
optimal parenthesization of the matrix product.
p... | interview/matrix_chain_multiplication.py | def matrix_product(p):
"""Return m and s.
m[i][j] is the minimum number of scalar multiplications needed to compute the
product of matrices A(i), A(i + 1), ..., A(j).
s[i][j] is the index of the matrix after which the product is split in an
optimal parenthesization of the matrix product.
p... | 0.677794 | 0.760517 |
import argparse
import collections
import csv
import functools
import logging
import operator
import sys
def process(fh, op, delimiter, join_string=' + '):
'''
apply operation and write to dest
'''
logging.info('reading from stdin...')
out = csv.writer(sys.stdout, delimiter=delimiter)
out = c... | csvtools/csvgroup.py | import argparse
import collections
import csv
import functools
import logging
import operator
import sys
def process(fh, op, delimiter, join_string=' + '):
'''
apply operation and write to dest
'''
logging.info('reading from stdin...')
out = csv.writer(sys.stdout, delimiter=delimiter)
out = c... | 0.127327 | 0.125039 |
import abc
from datetime import datetime
from typing import Optional
from django.utils.crypto import get_random_string
from django.utils.text import slugify
import attr
from werkzeug.urls import url_fix
from url_mangler.apps.url_mapper.models import UrlMapping
@attr.s(auto_attribs=True)
class SlugMapping:
"""U... | url_mangler/apps/url_mapper/uses.py | import abc
from datetime import datetime
from typing import Optional
from django.utils.crypto import get_random_string
from django.utils.text import slugify
import attr
from werkzeug.urls import url_fix
from url_mangler.apps.url_mapper.models import UrlMapping
@attr.s(auto_attribs=True)
class SlugMapping:
"""U... | 0.912486 | 0.189128 |
import sqlite3
def create_database(mops_directory):
"""connects to a database if the database exists. If a database does not exist at that
location then it creates it. Database name is fixed as mops.db
"""
cxn = sqlite3.connect(mops_directory + 'mops.db')
c = cxn.cursor()
#-------... | trunk/MOPS_Database.py | import sqlite3
def create_database(mops_directory):
"""connects to a database if the database exists. If a database does not exist at that
location then it creates it. Database name is fixed as mops.db
"""
cxn = sqlite3.connect(mops_directory + 'mops.db')
c = cxn.cursor()
#-------... | 0.274546 | 0.091585 |
from django.db import models
from django.db.models import OuterRef, Subquery, QuerySet
from django_filters import rest_framework as filters
from .models import Rate
class RateFilter(filters.FilterSet):
"""
Rate object filter
"""
user = filters.BooleanFilter(
label="filter rate associated to c... | src/geocurrency/rates/filters.py | from django.db import models
from django.db.models import OuterRef, Subquery, QuerySet
from django_filters import rest_framework as filters
from .models import Rate
class RateFilter(filters.FilterSet):
"""
Rate object filter
"""
user = filters.BooleanFilter(
label="filter rate associated to c... | 0.832032 | 0.390069 |
import httplib
import urllib
import requests
from urlparse import urlparse
from opensearch import log
from opensearch.exception import HTTPError, ArgumentError
class HttpClient(object):
def request(self, url, method, params):
raise NotImplementedError
@classmethod
def get_httpclient(cls):
... | opensearch/httpclient.py | import httplib
import urllib
import requests
from urlparse import urlparse
from opensearch import log
from opensearch.exception import HTTPError, ArgumentError
class HttpClient(object):
def request(self, url, method, params):
raise NotImplementedError
@classmethod
def get_httpclient(cls):
... | 0.26588 | 0.049797 |
from ..identity import PartitionIdentity
from osgeo import gdal, gdal_array, osr
from osgeo.gdalconst import GDT_Float32, GDT_Byte, GDT_Int16
import numpy as np
class OutOfBounds(Exception): pass
class Kernel(object):
def __init__(self, size, matrix=None):
self.size = size
if size%2 == 0... | ambry/geo/kernel.py | from ..identity import PartitionIdentity
from osgeo import gdal, gdal_array, osr
from osgeo.gdalconst import GDT_Float32, GDT_Byte, GDT_Int16
import numpy as np
class OutOfBounds(Exception): pass
class Kernel(object):
def __init__(self, size, matrix=None):
self.size = size
if size%2 == 0... | 0.660939 | 0.38549 |
from datetime import datetime
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
from monitor import ElementConnected
__author__ = 'slynn'
app = Flask(__name__)... | application.py | from datetime import datetime
from flask_socketio import SocketIO, emit
from flask import Flask, render_template, url_for, copy_current_request_context
from random import random
from time import sleep
from threading import Thread, Event
from monitor import ElementConnected
__author__ = 'slynn'
app = Flask(__name__)... | 0.522689 | 0.09782 |
import bisect
from copy import deepcopy
from Bio.Seq import Seq
from mutalyzer_crossmapper import Coding, Genomic, NonCoding
from mutalyzer_mutator.util import reverse_complement
from ..description_model import (
variant_to_description,
variants_to_description,
yield_sub_model,
)
from ..reference import (... | normalizer/converter/to_rna.py | import bisect
from copy import deepcopy
from Bio.Seq import Seq
from mutalyzer_crossmapper import Coding, Genomic, NonCoding
from mutalyzer_mutator.util import reverse_complement
from ..description_model import (
variant_to_description,
variants_to_description,
yield_sub_model,
)
from ..reference import (... | 0.626696 | 0.540196 |
def parseInput(myinput):
hands = {}
hand_length = 6 #Name plus cards
splitinput = [x for x in myinput.split(' ') if x.strip()!='']
while len(splitinput) > 0:
playerhand = splitinput[0:hand_length]
player = playerhand.pop(0).replace(":", "")
hands[player] = playerhand
splitinput = splitinput[han... | 0311-texas/main.py | def parseInput(myinput):
hands = {}
hand_length = 6 #Name plus cards
splitinput = [x for x in myinput.split(' ') if x.strip()!='']
while len(splitinput) > 0:
playerhand = splitinput[0:hand_length]
player = playerhand.pop(0).replace(":", "")
hands[player] = playerhand
splitinput = splitinput[han... | 0.128854 | 0.395835 |
import cioppy
ciop = cioppy.Cioppy()
import urllib.parse as urlparse
import datetime
import pandas as pd
import gdal
from shapely.geometry import box
def log_input(reference):
"""
Just logs the input reference, using the ciop.log function
"""
ciop.log('INFO', 'processing input: ' + reference)
... | src/main/app-resources/util/util.py |
import cioppy
ciop = cioppy.Cioppy()
import urllib.parse as urlparse
import datetime
import pandas as pd
import gdal
from shapely.geometry import box
def log_input(reference):
"""
Just logs the input reference, using the ciop.log function
"""
ciop.log('INFO', 'processing input: ' + reference)
... | 0.608594 | 0.400398 |
from __future__ import absolute_import
import six
from datetime import timedelta
from django.db.models import Q
from django.utils import timezone
from rest_framework.response import Response
from functools32 import partial
from sentry import options, quotas, tagstore
from sentry.api.base import DocSection, Environm... | src/sentry/api/endpoints/group_events.py | from __future__ import absolute_import
import six
from datetime import timedelta
from django.db.models import Q
from django.utils import timezone
from rest_framework.response import Response
from functools32 import partial
from sentry import options, quotas, tagstore
from sentry.api.base import DocSection, Environm... | 0.529263 | 0.087058 |
import pandas as pd
import numpy as np
from random import choice, randint, uniform, random
import util
from util import Stack, Item, Solution
import time
class GA:
def __init__(self, _instance, _popSize, _mutationRate, _maxIterations,
_widthPlates, _heightPlates,_crossoverAlgorithm,
... | GA_C.py | import pandas as pd
import numpy as np
from random import choice, randint, uniform, random
import util
from util import Stack, Item, Solution
import time
class GA:
def __init__(self, _instance, _popSize, _mutationRate, _maxIterations,
_widthPlates, _heightPlates,_crossoverAlgorithm,
... | 0.441071 | 0.160299 |
u"""
.. module:: test_create_organization
"""
from apps.volontulo.tests.views.test_organizations import TestOrganizations
from apps.volontulo.models import Organization
class TestCreateOrganization(TestOrganizations):
u"""Class responsible for testing editing organization specific views."""
def test__creat... | apps/volontulo/tests/views/test_create_orgranization.py |
u"""
.. module:: test_create_organization
"""
from apps.volontulo.tests.views.test_organizations import TestOrganizations
from apps.volontulo.models import Organization
class TestCreateOrganization(TestOrganizations):
u"""Class responsible for testing editing organization specific views."""
def test__creat... | 0.719482 | 0.306618 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import logging
import warnings
import pymysql
import random
from rasa_core.actions import Action
from rasa_core.agent import Agent
from rasa_core.chann... | bot.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import logging
import warnings
import pymysql
import random
from rasa_core.actions import Action
from rasa_core.agent import Agent
from rasa_core.chann... | 0.253491 | 0.09343 |
import numpy as np
import warnings
class EmptyTriclusterException(Exception):
pass
class DeltaTrimax():
"""
The delta-TRIMAX clustering algorithm.
Attributes
----------
D : ndarray
The data to be clustered
delta : float
The delta parameter of the algorithm. Must be > 0... | mycluster/DeltaTrimax.py |
import numpy as np
import warnings
class EmptyTriclusterException(Exception):
pass
class DeltaTrimax():
"""
The delta-TRIMAX clustering algorithm.
Attributes
----------
D : ndarray
The data to be clustered
delta : float
The delta parameter of the algorithm. Must be > 0... | 0.880181 | 0.739352 |
# Copyright 2018 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
from collections import namedtuple
from ocean_keeper.account import Account
from ocean_keeper.utils import get_account
Balance = namedtuple('Balance', ('eth', 'ocn'))
class OceanAccounts:
"""Ocean accounts class."""
def __i... | squid_py/ocean/ocean_accounts.py | # Copyright 2018 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
from collections import namedtuple
from ocean_keeper.account import Account
from ocean_keeper.utils import get_account
Balance = namedtuple('Balance', ('eth', 'ocn'))
class OceanAccounts:
"""Ocean accounts class."""
def __i... | 0.910137 | 0.232691 |
from PyQt5.QtWidgets import QWidget, QGridLayout, QListView, QPushButton, \
QDialog
from PyQt5.QtCore import QSize, Qt
from app.resources.resources import RESOURCES
from app.editor.data_editor import SingleResourceEditor, MultiResourceEditor
from app.editor.icon_editor import icon_model
class IconTab(QWidget):
... | app/editor/icon_editor/icon_tab.py | from PyQt5.QtWidgets import QWidget, QGridLayout, QListView, QPushButton, \
QDialog
from PyQt5.QtCore import QSize, Qt
from app.resources.resources import RESOURCES
from app.editor.data_editor import SingleResourceEditor, MultiResourceEditor
from app.editor.icon_editor import icon_model
class IconTab(QWidget):
... | 0.529507 | 0.088151 |
import sys
import os
sys.path.append(os.getcwd())
import json
import time
from threading import Thread, Event
from scripts.prettyCode.prettyPrint import PrettyPrint
from scripts.windows.windows import BaseWindowsControl, FindTheFile
from scripts.windows.journalist import BasicLogs
PRETTYPRINT = PrettyPrint()
class ... | scripts/game/gameControl.py | import sys
import os
sys.path.append(os.getcwd())
import json
import time
from threading import Thread, Event
from scripts.prettyCode.prettyPrint import PrettyPrint
from scripts.windows.windows import BaseWindowsControl, FindTheFile
from scripts.windows.journalist import BasicLogs
PRETTYPRINT = PrettyPrint()
class ... | 0.196788 | 0.066873 |
import numpy as np
from cascade.core.form import (
Form,
BoolField,
IntField,
FloatField,
StrField,
StringListField,
ListField,
OptionField,
FormList,
Dummy,
)
from cascade.model import priors
from cascade.core.log import getLoggers
CODELOG, MATHLOG = getLoggers(__name__)
cl... | src/cascade/input_data/configuration/form.py | import numpy as np
from cascade.core.form import (
Form,
BoolField,
IntField,
FloatField,
StrField,
StringListField,
ListField,
OptionField,
FormList,
Dummy,
)
from cascade.model import priors
from cascade.core.log import getLoggers
CODELOG, MATHLOG = getLoggers(__name__)
cl... | 0.61231 | 0.241411 |
from django.db import models
from imagekit.models import ImageSpecField
from pilkit.processors import ResizeToFit
from django.utils.safestring import mark_safe
from django.db.models.signals import post_save, pre_save, pre_delete
from social_network.core.models import (cleaning_files_pre_save, cleaning_files_pre_dele... | posts/models.py |
from django.db import models
from imagekit.models import ImageSpecField
from pilkit.processors import ResizeToFit
from django.utils.safestring import mark_safe
from django.db.models.signals import post_save, pre_save, pre_delete
from social_network.core.models import (cleaning_files_pre_save, cleaning_files_pre_dele... | 0.666931 | 0.128607 |
import deepinterpolation as de
import sys
from shutil import copyfile
import os
from deepinterpolation.generic import JsonSaver, ClassLoader
import datetime
from typing import Any, Dict
from kerastuner.tuners import RandomSearch, BayesianOptimization
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras... | examples/paper_generation_code/2020-08-26-local_fmri_hyper_training.py | import deepinterpolation as de
import sys
from shutil import copyfile
import os
from deepinterpolation.generic import JsonSaver, ClassLoader
import datetime
from typing import Any, Dict
from kerastuner.tuners import RandomSearch, BayesianOptimization
from tensorflow.keras.optimizers import RMSprop
from tensorflow.keras... | 0.461259 | 0.23895 |
import os
from . import __file__
from .data import GHS_HAZARDS
__version__ = [0, 1, 0]
class UnknownHazard(Exception):
"""
Exception raised when no Hazard is found
"""
message = "Unknown hazard"
class Hazard:
"""
Hazard class
"""
code = None
name = None
hazard_type = None
... | ghs_hazard_pictogram/__init__.py | import os
from . import __file__
from .data import GHS_HAZARDS
__version__ = [0, 1, 0]
class UnknownHazard(Exception):
"""
Exception raised when no Hazard is found
"""
message = "Unknown hazard"
class Hazard:
"""
Hazard class
"""
code = None
name = None
hazard_type = None
... | 0.556882 | 0.18508 |
def fibSumThree(n0):
"""
Created on Mon Aug 23 07:40:53 2021
@author: Ezra
fibSumThree(n0) function to find the sum of all the terms in the
Fibonacci sequence divisible by three whih do not exceed n0.
Input: n0 is the largest natural number considered
Output: fibSumThree- the sum of the Fibonac... | Tech lab 1.py | def fibSumThree(n0):
"""
Created on Mon Aug 23 07:40:53 2021
@author: Ezra
fibSumThree(n0) function to find the sum of all the terms in the
Fibonacci sequence divisible by three whih do not exceed n0.
Input: n0 is the largest natural number considered
Output: fibSumThree- the sum of the Fibonac... | 0.529507 | 0.514644 |
import unittest
import sys
import pandas as pd
from CovidVoting.add_data import (add_data_csv)
sys.path.append('..')
# Define all states
all_states = ["Maryland", "Iowa", "Delaware", "Ohio",
"Pennsylvania", "Nebraska", "Washington",
"Alabama", "Arkansas", "New Mexico", "Texas",
... | CovidVoting/test/test_add_data.py | import unittest
import sys
import pandas as pd
from CovidVoting.add_data import (add_data_csv)
sys.path.append('..')
# Define all states
all_states = ["Maryland", "Iowa", "Delaware", "Ohio",
"Pennsylvania", "Nebraska", "Washington",
"Alabama", "Arkansas", "New Mexico", "Texas",
... | 0.347537 | 0.343672 |
from flask import Flask, render_template, url_for, Response, stream_with_context
from datetime import datetime as dt
import threading, cv2, time, imutils, datetime
import numpy as np
from imutils.video import VideoStream
import time
outputFrame = None
lock = threading.Lock()
isCamOn = False
cam = None
class piCam(ob... | Flask_Projects/Bots_Projects/picar_app.py | from flask import Flask, render_template, url_for, Response, stream_with_context
from datetime import datetime as dt
import threading, cv2, time, imutils, datetime
import numpy as np
from imutils.video import VideoStream
import time
outputFrame = None
lock = threading.Lock()
isCamOn = False
cam = None
class piCam(ob... | 0.295332 | 0.167049 |
import urllib.parse
from typing import Any, Dict, List, Optional, Union
from ._http_status_codes import HTTP_STATUS_CODES
from ._model import Model
class HttpResponse(Model):
"""HTTP Error
Properties:
code: (code) OPTIONAL int
content_type: (content_type) OPTIONAL str
content: (... | accelbyte_py_sdk/core/_http_response.py |
import urllib.parse
from typing import Any, Dict, List, Optional, Union
from ._http_status_codes import HTTP_STATUS_CODES
from ._model import Model
class HttpResponse(Model):
"""HTTP Error
Properties:
code: (code) OPTIONAL int
content_type: (content_type) OPTIONAL str
content: (... | 0.8288 | 0.160463 |
import requests
import json
import os
import time
from time import sleep
def dateTime():
return time.strftime("%Y/%m/%d %H:%M:%S")
# Read token and owner id from untracked credentials file.
# We wouldn't want this on Github now, would we?
f = open("creds.txt")
lines = f.readlines()
f.close
token = lines[0].strip... | mensabot.py | import requests
import json
import os
import time
from time import sleep
def dateTime():
return time.strftime("%Y/%m/%d %H:%M:%S")
# Read token and owner id from untracked credentials file.
# We wouldn't want this on Github now, would we?
f = open("creds.txt")
lines = f.readlines()
f.close
token = lines[0].strip... | 0.049854 | 0.062588 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, sys
import random
import re
import threading
import librosa
import pretty_midi
import numpy as np
import tensorflow as tf
sys.path.append(os.path.join(os.getcwd(), os.pardir))
from utils import fin... | readers/wavmid_reader.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os, sys
import random
import re
import threading
import librosa
import pretty_midi
import numpy as np
import tensorflow as tf
sys.path.append(os.path.join(os.getcwd(), os.pardir))
from utils import fin... | 0.525369 | 0.188866 |
import numpy as np
_EXTREMUM_SEARCH_NUM_POINTS = 5
_EXTREMUM_SEARCH_EPSILON = 0.5 / 86400. # A half-second fraction of a Julian day
def find_extremum(t_0, t_1, extremum, function, epsilon=_EXTREMUM_SEARCH_EPSILON,
num=_EXTREMUM_SEARCH_NUM_POINTS):
"""Find a global extremum for a function with ... | extremum.py | import numpy as np
_EXTREMUM_SEARCH_NUM_POINTS = 5
_EXTREMUM_SEARCH_EPSILON = 0.5 / 86400. # A half-second fraction of a Julian day
def find_extremum(t_0, t_1, extremum, function, epsilon=_EXTREMUM_SEARCH_EPSILON,
num=_EXTREMUM_SEARCH_NUM_POINTS):
"""Find a global extremum for a function with ... | 0.92241 | 0.49646 |
from unittest import TestCase
from link_parser import LinkParser
valid_url = LinkParser.valid_url
normalize_url = LinkParser.normalize_url
extract_name = LinkParser.extract_name
class Tests(TestCase):
def test_valid_url(self):
self.assertTrue(valid_url("https://simple.wikipedia.org/wiki/Main_Page"))
... | 06_page_rank/tests.py | from unittest import TestCase
from link_parser import LinkParser
valid_url = LinkParser.valid_url
normalize_url = LinkParser.normalize_url
extract_name = LinkParser.extract_name
class Tests(TestCase):
def test_valid_url(self):
self.assertTrue(valid_url("https://simple.wikipedia.org/wiki/Main_Page"))
... | 0.658966 | 0.737205 |
import json
""" Module for Losant API DataTableRows wrapper class """
# pylint: disable=C0301
class DataTableRows(object):
""" Class containing all the actions for the Data Table Rows Resource """
def __init__(self, client):
self.client = client
def delete(self, **kwargs):
"""
De... | losantrest/data_table_rows.py | import json
""" Module for Losant API DataTableRows wrapper class """
# pylint: disable=C0301
class DataTableRows(object):
""" Class containing all the actions for the Data Table Rows Resource """
def __init__(self, client):
self.client = client
def delete(self, **kwargs):
"""
De... | 0.771456 | 0.285339 |
import os
import yaml
import string
import re
import wx
import wx.adv
from datetime import date, timedelta
from cash_flow.transaction import Transaction
from cash_flow.transaction_store import TransactionStore
from cash_flow.cash_flow import CashFlow
def wxDate2pyDate(wxdate):
return date(wxdate.GetYear(), wxdate... | cash_flow_calculator.py | import os
import yaml
import string
import re
import wx
import wx.adv
from datetime import date, timedelta
from cash_flow.transaction import Transaction
from cash_flow.transaction_store import TransactionStore
from cash_flow.cash_flow import CashFlow
def wxDate2pyDate(wxdate):
return date(wxdate.GetYear(), wxdate... | 0.285472 | 0.0729 |
"""Test utilities."""
from __future__ import (
absolute_import, division, print_function, unicode_literals,
)
import logging
import os
import re
import sys
from threading import RLock
from traitlets.config.application import LevelFormatter
from traitlets.traitlets import default
try:
from notebook.tests.tes... | jupyter_contrib_core/testing_utils/__init__.py | """Test utilities."""
from __future__ import (
absolute_import, division, print_function, unicode_literals,
)
import logging
import os
import re
import sys
from threading import RLock
from traitlets.config.application import LevelFormatter
from traitlets.traitlets import default
try:
from notebook.tests.tes... | 0.654343 | 0.158077 |
from netapp.netapp_object import NetAppObject
class LunStatsInfo(NetAppObject):
"""
Stats for a LUN.
"""
_last_zeroed = None
@property
def last_zeroed(self):
"""
Total number of seconds since the statistics
for this lun were last zeroed.
"""
return s... | generated-libraries/python/netapp/lun/lun_stats_info.py | from netapp.netapp_object import NetAppObject
class LunStatsInfo(NetAppObject):
"""
Stats for a LUN.
"""
_last_zeroed = None
@property
def last_zeroed(self):
"""
Total number of seconds since the statistics
for this lun were last zeroed.
"""
return s... | 0.766468 | 0.196421 |
from unittest import TestCase
import shellmacros
class TestMacroEngine(TestCase):
def setup1(self):
e = shellmacros.MacroEngine()
e.add('zack_dog', 'dolly')
e.add('what','${pet}')
e.add('pet','dog')
e.add('parent', 'duane')
e.add('duane_son', 'zack')
e.add_... | tests/test_engine.py | from unittest import TestCase
import shellmacros
class TestMacroEngine(TestCase):
def setup1(self):
e = shellmacros.MacroEngine()
e.add('zack_dog', 'dolly')
e.add('what','${pet}')
e.add('pet','dog')
e.add('parent', 'duane')
e.add('duane_son', 'zack')
e.add_... | 0.476092 | 0.388502 |
__author__ = "<NAME>"
__copyright__ = "OuroborosCoding"
__version__ = "1.0.0"
__email__ = "<EMAIL>"
__created__ = "2018-11-11"
def crop(w, h, bw, bh):
"""Crop
Makes sure one side fits and crops the other
Arguments:
w (int): The current width
h (int): The current height
bw (int): The boundary width
bh (int... | RestOC/Resize.py | __author__ = "<NAME>"
__copyright__ = "OuroborosCoding"
__version__ = "1.0.0"
__email__ = "<EMAIL>"
__created__ = "2018-11-11"
def crop(w, h, bw, bh):
"""Crop
Makes sure one side fits and crops the other
Arguments:
w (int): The current width
h (int): The current height
bw (int): The boundary width
bh (int... | 0.718199 | 0.180071 |
from interpreter import commands
#----------READER----------
class Reader:
pos = 0
data = ''
def eof(self):
return self.pos >= len(self.data)
def move_cursor(self, offset):
self.pos = self.pos + offset
def load_text(self, text):
self.data = text
self.pos = 0
... | src/interpreters/ysabel/python/ysabel_parser.py | from interpreter import commands
#----------READER----------
class Reader:
pos = 0
data = ''
def eof(self):
return self.pos >= len(self.data)
def move_cursor(self, offset):
self.pos = self.pos + offset
def load_text(self, text):
self.data = text
self.pos = 0
... | 0.417509 | 0.290427 |
import float32_convertors as f32cnv
import unittest
def plot_call_back(string):
pass
class TestFloatConversion(unittest.TestCase):
def setUp(self):
pass
def testInv(self):
""" """
# проверим обр. преобр
doubleOne = 1.0
doubleOneFromMCHIP = f32cnv.hex_mchip_f32_to... | matlab_ext/measurement/mc-assistant/source/py/convertors_simple_data_types/test_float32_convertors.py | import float32_convertors as f32cnv
import unittest
def plot_call_back(string):
pass
class TestFloatConversion(unittest.TestCase):
def setUp(self):
pass
def testInv(self):
""" """
# проверим обр. преобр
doubleOne = 1.0
doubleOneFromMCHIP = f32cnv.hex_mchip_f32_to... | 0.495117 | 0.338268 |
from idds.core import collections
def add_collection(scope, name, coll_type=None, request_id=None, transform_id=None,
relation_type=None, coll_size=0, status=None, total_files=0, retries=0,
expired_at=None, coll_metadata=None):
"""
Add a collection.
:param scope: The... | main/lib/idds/api/collections.py | from idds.core import collections
def add_collection(scope, name, coll_type=None, request_id=None, transform_id=None,
relation_type=None, coll_size=0, status=None, total_files=0, retries=0,
expired_at=None, coll_metadata=None):
"""
Add a collection.
:param scope: The... | 0.795975 | 0.265279 |
import random
import threading
import time
from datetime import datetime
import json
import os
from bson.json_util import dumps
from common.json_encoder import JSONFriendlyEncoder
from common.logger import get_logger
from common.timer import RepeatedTimer
from helpers.file_helper import FileHelper
from helpers.s3_helpe... | cosmos-db-migration-utility/src/migrator-app/helpers/document_batcher.py | import random
import threading
import time
from datetime import datetime
import json
import os
from bson.json_util import dumps
from common.json_encoder import JSONFriendlyEncoder
from common.logger import get_logger
from common.timer import RepeatedTimer
from helpers.file_helper import FileHelper
from helpers.s3_helpe... | 0.191517 | 0.085099 |
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddle import ParamAttr
from ppdet.core.workspace import register, serializable
from ..backbones.darknet import ConvBNLayer
import numpy as np
from ..shape_spec import ShapeSpec
__all__ = ['YOLOv3FPN', 'PPYOLOFPN']
class YoloDetBlock(nn.Lay... | dygraph/ppdet/modeling/necks/yolo_fpn.py |
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddle import ParamAttr
from ppdet.core.workspace import register, serializable
from ..backbones.darknet import ConvBNLayer
import numpy as np
from ..shape_spec import ShapeSpec
__all__ = ['YOLOv3FPN', 'PPYOLOFPN']
class YoloDetBlock(nn.Lay... | 0.849129 | 0.282094 |
import logging
from iptv_proxy.providers.iptv_provider.map import ProviderMap
logger = logging.getLogger(__name__)
class VaderStreamsMap(ProviderMap):
__slots__ = []
_api_class = None
_channel_class = None
_configuration_class = None
_configuration_json_api_class = None
_constants_class = N... | iptv_proxy/providers/vaderstreams/map.py | import logging
from iptv_proxy.providers.iptv_provider.map import ProviderMap
logger = logging.getLogger(__name__)
class VaderStreamsMap(ProviderMap):
__slots__ = []
_api_class = None
_channel_class = None
_configuration_class = None
_configuration_json_api_class = None
_constants_class = N... | 0.452536 | 0.04548 |
# https://docs.opencv.org/3.3.1/d7/d8b/tutorial_py_face_detection.html
# On the Jetson Nano, OpenCV comes preinstalled
# Data files are in /usr/sharc/OpenCV
from __future__ import print_function, division
from PIL import Image
import cv2
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim... | particle_detect.py |
# https://docs.opencv.org/3.3.1/d7/d8b/tutorial_py_face_detection.html
# On the Jetson Nano, OpenCV comes preinstalled
# Data files are in /usr/sharc/OpenCV
from __future__ import print_function, division
from PIL import Image
import cv2
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim... | 0.743261 | 0.493836 |
from twisted.cred.portal import Portal
from twisted.conch.ssh import factory, userauth, connection, keys, session
from twisted.conch.ssh.factory import SSHFactory
from twisted.internet import reactor
from twisted.conch.ssh.keys import Key
from twisted.conch.ssh import session, forwarding, filetransfer
from twisted.conc... | txftp.py | from twisted.cred.portal import Portal
from twisted.conch.ssh import factory, userauth, connection, keys, session
from twisted.conch.ssh.factory import SSHFactory
from twisted.internet import reactor
from twisted.conch.ssh.keys import Key
from twisted.conch.ssh import session, forwarding, filetransfer
from twisted.conc... | 0.376165 | 0.11004 |
import datetime
import random
import string
import typing
import pandas as pd
from audformat.core import define
from audformat.core.common import HeaderBase
class Scheme(HeaderBase):
r"""A scheme defines valid values of an annotation.
Allowed values for ``dtype`` are:
``'bool'``, ``'str'``, ``'int'``, ... | audformat/core/scheme.py | import datetime
import random
import string
import typing
import pandas as pd
from audformat.core import define
from audformat.core.common import HeaderBase
class Scheme(HeaderBase):
r"""A scheme defines valid values of an annotation.
Allowed values for ``dtype`` are:
``'bool'``, ``'str'``, ``'int'``, ... | 0.893716 | 0.517388 |
import csv
from argparse import ArgumentParser
from collections import defaultdict
from itertools import product
from pathlib import Path
from typing import Set, Optional, Sequence
import librosa.display
import matplotlib.ticker as tckr
import matplotlib.pyplot as plt
import mir_eval
import numpy as np
from numpy impo... | analyze_test.py | import csv
from argparse import ArgumentParser
from collections import defaultdict
from itertools import product
from pathlib import Path
from typing import Set, Optional, Sequence
import librosa.display
import matplotlib.ticker as tckr
import matplotlib.pyplot as plt
import mir_eval
import numpy as np
from numpy impo... | 0.817028 | 0.306047 |
import os
BANNED_FILES = set(['.DS_Store'])
OK_CHARS = list(map(ord, list('!@#$%^&*()-_+=`~[]{}|;:\',.<>/? ')))
for i in range(26):
if i < 10: OK_CHARS.append(ord('0') + i)
c = ord('a') + i
OK_CHARS.append(c)
OK_CHARS.append(c - ord('a') + ord('A'))
OK_CHARS = set(OK_CHARS)
escape_lookup = {
... | resourcegen.py | import os
BANNED_FILES = set(['.DS_Store'])
OK_CHARS = list(map(ord, list('!@#$%^&*()-_+=`~[]{}|;:\',.<>/? ')))
for i in range(26):
if i < 10: OK_CHARS.append(ord('0') + i)
c = ord('a') + i
OK_CHARS.append(c)
OK_CHARS.append(c - ord('a') + ord('A'))
OK_CHARS = set(OK_CHARS)
escape_lookup = {
... | 0.052479 | 0.078749 |
from pyb import Pin, SPI
import time
class SX1239():
def __init__(self):
super().__init__()
self.SPI = SPI(1, SPI.MASTER, baudrate=600000, polarity=0, phase=0, crc=None)
self.NRST = Pin('Y6', Pin.OUT_PP)
self.NSS = Pin('X5', Pin.OUT_PP)
self.DIO0 = Pin('Y5', Pin.IN, Pin.PUL... | MAIN/STM32F405/V00/SX1239.py | from pyb import Pin, SPI
import time
class SX1239():
def __init__(self):
super().__init__()
self.SPI = SPI(1, SPI.MASTER, baudrate=600000, polarity=0, phase=0, crc=None)
self.NRST = Pin('Y6', Pin.OUT_PP)
self.NSS = Pin('X5', Pin.OUT_PP)
self.DIO0 = Pin('Y5', Pin.IN, Pin.PUL... | 0.328529 | 0.132767 |
import json
import pytest
from tornado.httpclient import HTTPError, HTTPRequest
from beer_garden.api.http.authentication import issue_token_pair
from beer_garden.db.mongo.models import Garden, Role, RoleAssignment, User
@pytest.fixture(autouse=True)
def garden():
garden = Garden(name="somegarden", connection_ty... | src/app/test/api/http/unit/handlers/v1/forward_test.py | import json
import pytest
from tornado.httpclient import HTTPError, HTTPRequest
from beer_garden.api.http.authentication import issue_token_pair
from beer_garden.db.mongo.models import Garden, Role, RoleAssignment, User
@pytest.fixture(autouse=True)
def garden():
garden = Garden(name="somegarden", connection_ty... | 0.455441 | 0.222658 |
# This script sets up a simple loop for periodical attestation of Pyth data
from pyth_utils import *
from http.client import HTTPConnection
import json
import os
import subprocess
import time
import threading
P2W_ADDRESS = "P2WH424242424242424242424242424242424242424"
P2W_ATTEST_INTERVAL = float(os.environ.get("P2... | third_party/pyth/p2w_autoattest.py |
# This script sets up a simple loop for periodical attestation of Pyth data
from pyth_utils import *
from http.client import HTTPConnection
import json
import os
import subprocess
import time
import threading
P2W_ADDRESS = "P2WH424242424242424242424242424242424242424"
P2W_ATTEST_INTERVAL = float(os.environ.get("P2... | 0.451085 | 0.175962 |
import json
import random
from datetime import datetime, timedelta
from django.db.models import Sum, Avg, Max
from django.shortcuts import render
from rest_framework.authtoken.models import Token
from .models import UserData, Profile
def home_page(request):
return render(request, 'Data/home_page.html', context=... | Data/views.py | import json
import random
from datetime import datetime, timedelta
from django.db.models import Sum, Avg, Max
from django.shortcuts import render
from rest_framework.authtoken.models import Token
from .models import UserData, Profile
def home_page(request):
return render(request, 'Data/home_page.html', context=... | 0.423696 | 0.196498 |
import pytest
from assertpy import assert_that
from pytest_bdd import scenario, given, when, then, parsers
from roguebot.state.entity import Entities, Entity
from roguebot.navigation.path import PathFinder
from roguebot.navigation.path_printer import PathPrinter
from roguebot.state.state import State
from tests.state.d... | tests/bdd/test_path_finder.py | import pytest
from assertpy import assert_that
from pytest_bdd import scenario, given, when, then, parsers
from roguebot.state.entity import Entities, Entity
from roguebot.navigation.path import PathFinder
from roguebot.navigation.path_printer import PathPrinter
from roguebot.state.state import State
from tests.state.d... | 0.648578 | 0.572006 |
import pandas as pd
from .utils import pipeable
@pipeable
def exact_merge(
left: pd.DataFrame,
right: pd.DataFrame,
on: str = None,
left_on: str = None,
right_on: str = None,
how: str = "exact",
suffixes=("_x", "_y"),
):
"""
Merge two dataframes based on two string columns and the ... | schuylkill/exact.py | import pandas as pd
from .utils import pipeable
@pipeable
def exact_merge(
left: pd.DataFrame,
right: pd.DataFrame,
on: str = None,
left_on: str = None,
right_on: str = None,
how: str = "exact",
suffixes=("_x", "_y"),
):
"""
Merge two dataframes based on two string columns and the ... | 0.803097 | 0.688396 |
import os
import shutil
import pytest
from autopylot.cameras import Camera
from autopylot.datasets import preparedata
from autopylot.models import architectures, utils
from autopylot.utils import memory, settings
dirpath = os.path.join(settings.settings.MODELS_PATH, "test", "test")
@pytest.mark.models
def test_crea... | autopylot/tests/test_models.py | import os
import shutil
import pytest
from autopylot.cameras import Camera
from autopylot.datasets import preparedata
from autopylot.models import architectures, utils
from autopylot.utils import memory, settings
dirpath = os.path.join(settings.settings.MODELS_PATH, "test", "test")
@pytest.mark.models
def test_crea... | 0.790934 | 0.652186 |
import numpy as np
import scipy as sp
import pandas as pd
from datetime import datetime
import xgboost as xgb
from sklearn.metrics import log_loss
from utility_common import feature_extraction, data_path
# r087
# 2015/12/16 14h20m
# Ensemble
# XGB
# params: nt (=num_round)
# ncol: 138610
X1, target, v_train, v_test ... | params_tune_xgb.py | import numpy as np
import scipy as sp
import pandas as pd
from datetime import datetime
import xgboost as xgb
from sklearn.metrics import log_loss
from utility_common import feature_extraction, data_path
# r087
# 2015/12/16 14h20m
# Ensemble
# XGB
# params: nt (=num_round)
# ncol: 138610
X1, target, v_train, v_test ... | 0.321353 | 0.180431 |
import tensorflow as tf
import numpy as np
from imgaug import augmenters as iaa
import matplotlib.pyplot as plt
def plot_sample_images(images, labels, num_classes, samples_per_class, mean=None, std=None, dtype='uint8'):
print(images[0].shape)
if mean is not None and std is not None:
images = images * ... | tensorflow_utils/utils/keras_load_data.py | import tensorflow as tf
import numpy as np
from imgaug import augmenters as iaa
import matplotlib.pyplot as plt
def plot_sample_images(images, labels, num_classes, samples_per_class, mean=None, std=None, dtype='uint8'):
print(images[0].shape)
if mean is not None and std is not None:
images = images * ... | 0.776538 | 0.613729 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
country_code = {'US': '082', # United States
'AU': '127', # Australia
'CA': '101', # Canada
'GE': '910', # Germany
'UK': '110', # United Kingdom
'JP': '105', # Ja... | fhnotebooks/Example Strategies/rates_carry_rank.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
country_code = {'US': '082', # United States
'AU': '127', # Australia
'CA': '101', # Canada
'GE': '910', # Germany
'UK': '110', # United Kingdom
'JP': '105', # Ja... | 0.393851 | 0.39065 |
from flask import Flask, render_template, request, redirect, url_for, jsonify,g
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from flask_sqlalchemy import SQLAlchemy
from database_setup import Base, User, Month, Transactions
from flask_bcrypt import Bcrypt
from sqlalchemy.sql import exist... | app.py | from flask import Flask, render_template, request, redirect, url_for, jsonify,g
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from flask_sqlalchemy import SQLAlchemy
from database_setup import Base, User, Month, Transactions
from flask_bcrypt import Bcrypt
from sqlalchemy.sql import exist... | 0.290779 | 0.090013 |
import socket, json, os, re
from pathlib import Path
from http.server import HTTPServer, SimpleHTTPRequestHandler
class MyHandler(SimpleHTTPRequestHandler):
dir = "/etc/nsd/nsd.conf.d/"
print("Loading config")
with open('configs/config.json') as f:
config = json.load(f)
print("Ready")
def ... | api.py | import socket, json, os, re
from pathlib import Path
from http.server import HTTPServer, SimpleHTTPRequestHandler
class MyHandler(SimpleHTTPRequestHandler):
dir = "/etc/nsd/nsd.conf.d/"
print("Loading config")
with open('configs/config.json') as f:
config = json.load(f)
print("Ready")
def ... | 0.081581 | 0.077762 |
r"""
Prototype for object model backend for the libNeuroML project
"""
import numpy as np
import neuroml
class ArrayMorphology(neuroml.Morphology):
"""Core of the array-based object model backend.
Provides the core arrays - vertices,connectivity etc.
node_types.
The connectivity array is a list of ... | neuroml/arraymorph.py | r"""
Prototype for object model backend for the libNeuroML project
"""
import numpy as np
import neuroml
class ArrayMorphology(neuroml.Morphology):
"""Core of the array-based object model backend.
Provides the core arrays - vertices,connectivity etc.
node_types.
The connectivity array is a list of ... | 0.757436 | 0.62088 |
from typing import Optional
import pytest
from chains import tasks
from chains.models import Message
from users.models import User
pytestmark = [
pytest.mark.django_db(transaction=True),
pytest.mark.freeze_time('2032-12-01 15:30'),
]
@pytest.fixture
def owl(mocker):
return mocker.patch('app.tasks.mail.... | src/chains/tests/chain_sender/test_chain_sender_integrational.py | from typing import Optional
import pytest
from chains import tasks
from chains.models import Message
from users.models import User
pytestmark = [
pytest.mark.django_db(transaction=True),
pytest.mark.freeze_time('2032-12-01 15:30'),
]
@pytest.fixture
def owl(mocker):
return mocker.patch('app.tasks.mail.... | 0.876667 | 0.613208 |
class Collection:
"""
A class to abstract the common functionalities of Stack and Queue.
This class should not be initialized directly.
"""
def __init__(self):
""" Constructor. """
self.items = []
self.num_items = 0
def size(self):
""" Get the number... | lab/lab10.py | class Collection:
"""
A class to abstract the common functionalities of Stack and Queue.
This class should not be initialized directly.
"""
def __init__(self):
""" Constructor. """
self.items = []
self.num_items = 0
def size(self):
""" Get the number... | 0.748995 | 0.423041 |
from VyPy.data import HashedDict
import pickle
from copy import deepcopy
from time import time, sleep
import numpy as np
# ----------------------------------------------------------------------
# Main
# ----------------------------------------------------------------------
def main():
#... | tests/data/hashed_dict.py |
from VyPy.data import HashedDict
import pickle
from copy import deepcopy
from time import time, sleep
import numpy as np
# ----------------------------------------------------------------------
# Main
# ----------------------------------------------------------------------
def main():
#... | 0.123855 | 0.156362 |
import time
import tensorflow as tf
from model import CNN_Encoder, RNN_Decoder, FeatureExtraction
from tokenization import load_tokenizer, TOP_K
tf.get_logger().setLevel('INFO')
def load_latest_imgcap(checkpoint_path, ckpt_index=-1):
embedding_dim = 256
units = 512
vocab_size = TOP_K + 1
encoder = C... | inf.py | import time
import tensorflow as tf
from model import CNN_Encoder, RNN_Decoder, FeatureExtraction
from tokenization import load_tokenizer, TOP_K
tf.get_logger().setLevel('INFO')
def load_latest_imgcap(checkpoint_path, ckpt_index=-1):
embedding_dim = 256
units = 512
vocab_size = TOP_K + 1
encoder = C... | 0.743168 | 0.283521 |
import aiosqlite
import discord
from datetime import datetime
import sqlite3
import math
from init import sourceDb, guild_ids
from database import Utilisateur, Quiz, Instance, Reponse, Statistiques
from discord_slash import cog_ext
from discord_slash.utils.manage_commands import create_option
from discord.ext import co... | src/commandsSlash.py | import aiosqlite
import discord
from datetime import datetime
import sqlite3
import math
from init import sourceDb, guild_ids
from database import Utilisateur, Quiz, Instance, Reponse, Statistiques
from discord_slash import cog_ext
from discord_slash.utils.manage_commands import create_option
from discord.ext import co... | 0.378804 | 0.258671 |
import os
import unittest as ut
import numpy as np
from mykit.core.utils import get_matched_files
from mykit.vasp.xml import Vasprunxml, VasprunxmlError
class test_vasprunxml_read(ut.TestCase):
def test_scf_xml(self):
'''Test reading XMLs for SCF calculations (LORBIT not set)
'''
dataD... | test/vasp/xml_test.py |
import os
import unittest as ut
import numpy as np
from mykit.core.utils import get_matched_files
from mykit.vasp.xml import Vasprunxml, VasprunxmlError
class test_vasprunxml_read(ut.TestCase):
def test_scf_xml(self):
'''Test reading XMLs for SCF calculations (LORBIT not set)
'''
dataD... | 0.444565 | 0.368377 |
import numpy as np
import numpy.linalg as linalg
import cv2 as cv
import scipy.optimize as opt
import functools
import json
import math
from .common.camera import Camera, Permutation
from .common.linear import solve_dlt
from .common.math import euclidean, homogeneous
from .common.matrix import matrix_intrinsic, matr... | trio/play_pose.py | import numpy as np
import numpy.linalg as linalg
import cv2 as cv
import scipy.optimize as opt
import functools
import json
import math
from .common.camera import Camera, Permutation
from .common.linear import solve_dlt
from .common.math import euclidean, homogeneous
from .common.matrix import matrix_intrinsic, matr... | 0.627152 | 0.42179 |
import os
import time
import numpy as np
import tensorflow as tf
import core.nn as nn
from config.constants import ACTIVATION, INTERVAL, LOG_PATH
from core.log import get_logger
class DeepHPM:
def __init__(self, idn_lb, idn_ub, t, x, u, tb, x0, u0, X_f, layers,
sol_lb, sol_ub, u_layers, pde_layer... | Mine/core/model.py | import os
import time
import numpy as np
import tensorflow as tf
import core.nn as nn
from config.constants import ACTIVATION, INTERVAL, LOG_PATH
from core.log import get_logger
class DeepHPM:
def __init__(self, idn_lb, idn_ub, t, x, u, tb, x0, u0, X_f, layers,
sol_lb, sol_ub, u_layers, pde_layer... | 0.694613 | 0.149252 |
import backtrader.indicators as btind
from . import compare_price as compare
from .base_indicator import iBaseIndicator
class iZlindCompare(iBaseIndicator):
'''
因子:平均移动线比较数值
传入参数:
rule = {"args": [5,10], # 周期, 增益
"logic":{"compare": "eq","byValue": 1,"byMax": 5,}, # 周期结果比较
}
... | ENIAC/api/loop_stack/loop_indicators/zlind_indicator.py | import backtrader.indicators as btind
from . import compare_price as compare
from .base_indicator import iBaseIndicator
class iZlindCompare(iBaseIndicator):
'''
因子:平均移动线比较数值
传入参数:
rule = {"args": [5,10], # 周期, 增益
"logic":{"compare": "eq","byValue": 1,"byMax": 5,}, # 周期结果比较
}
... | 0.180431 | 0.267024 |
from collections import OrderedDict
_glades = [
("Unusually Sharp Spike", "Twice as deadly as the other spikes."),
("Withered Fruit", "Gazing at it evokes memories of happier times."),
("Fil's Bracelet", "A simple band made of tightly-woven plant fibers."),
("Redcap Mushroom", "Eating these is said to ... | seedbuilder/relics.py | from collections import OrderedDict
_glades = [
("Unusually Sharp Spike", "Twice as deadly as the other spikes."),
("Withered Fruit", "Gazing at it evokes memories of happier times."),
("Fil's Bracelet", "A simple band made of tightly-woven plant fibers."),
("Redcap Mushroom", "Eating these is said to ... | 0.465387 | 0.572753 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django_countries.fields
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('core', '0014_orderitem_total_price'),
... | core/migrations/0015_address_order_payment.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django_countries.fields
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('core', '0014_orderitem_total_price'),
... | 0.522446 | 0.12544 |
from .models import Subscription, SubscriptionPlan, SubscriptionPlanDescription, DiscountCode
from datetime import datetime
from dateutil.relativedelta import relativedelta
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.contr... | proso_subscription/views.py | from .models import Subscription, SubscriptionPlan, SubscriptionPlanDescription, DiscountCode
from datetime import datetime
from dateutil.relativedelta import relativedelta
from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth.decorators import login_required
from django.contr... | 0.532668 | 0.172834 |
import boto3
import botocore
import json
import os
running_locally = True
if os.getenv("RUN_LOCALLY") == "false":
running_locally = False
if running_locally:
lambda_client = boto3.client('lambda',
region_name="us-east-1",
endpoint_url="http://127.0.0.1:3001",
use_ssl=False,
verify=False,
conf... | handler_tests/ou_and_account_tests.py | import boto3
import botocore
import json
import os
running_locally = True
if os.getenv("RUN_LOCALLY") == "false":
running_locally = False
if running_locally:
lambda_client = boto3.client('lambda',
region_name="us-east-1",
endpoint_url="http://127.0.0.1:3001",
use_ssl=False,
verify=False,
conf... | 0.171373 | 0.087252 |
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import numpy as np
import pandas as pd
from ._chartobject import ChartObject
from ..objects import ColumnDataSource, Range1d
#---------------------... | bokeh/charts/scatter.py |
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import numpy as np
import pandas as pd
from ._chartobject import ChartObject
from ..objects import ColumnDataSource, Range1d
#---------------------... | 0.83957 | 0.51501 |
import os
import numpy as np
import pandas as pd
from sklearn.externals import joblib
import AraVib
from AraVib_modules.AraVibS_def import growth_trait_selection, freq_file_selection
from AraVib_modules.AraVibS_def import model_selection, LR_difference
def main():
print("************ Step 1: Plea... | AraVibS.py | import os
import numpy as np
import pandas as pd
from sklearn.externals import joblib
import AraVib
from AraVib_modules.AraVibS_def import growth_trait_selection, freq_file_selection
from AraVib_modules.AraVibS_def import model_selection, LR_difference
def main():
print("************ Step 1: Plea... | 0.149438 | 0.108142 |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def focal_loss(labels, logits, alpha, gamma):
"""Compute the focal loss between `logits` and the ground truth `labels`.
Focal loss = -alpha_t * (1-pt)^gamma * log(pt)
where pt is the probability of being classified to t... | src/loss/cb_loss.py | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def focal_loss(labels, logits, alpha, gamma):
"""Compute the focal loss between `logits` and the ground truth `labels`.
Focal loss = -alpha_t * (1-pt)^gamma * log(pt)
where pt is the probability of being classified to t... | 0.940647 | 0.771219 |
from math import atan, atan2, cos, sin, sqrt
"""Python port of MapBox's cheap-ruler module."""
MATH_PI = 3.14159265359
MATH_E = 2.71828182846
FACTORS = {
"kilometers": 1,
"miles": 1000 / 1609.344,
"nauticalmiles": 1000 / 1852,
"meters": 1000,
"metres": 1000,
"yards": 1000 / 0.9144,
"fee... | cheapruler.py | from math import atan, atan2, cos, sin, sqrt
"""Python port of MapBox's cheap-ruler module."""
MATH_PI = 3.14159265359
MATH_E = 2.71828182846
FACTORS = {
"kilometers": 1,
"miles": 1000 / 1609.344,
"nauticalmiles": 1000 / 1852,
"meters": 1000,
"metres": 1000,
"yards": 1000 / 0.9144,
"fee... | 0.743075 | 0.432123 |
from django import forms
from django.contrib import auth
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Blog
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:... | blog/blogging/forms.py | from django import forms
from django.contrib import auth
from django.forms import ModelForm
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Blog
class RegistrationForm(UserCreationForm):
email = forms.EmailField(required=True)
class Meta:... | 0.446857 | 0.068506 |
import os
import posixpath
import StringIO
import sys
import textwrap
import mozdevice
from optparse import OptionParser
class DMCli(object):
def __init__(self, args=sys.argv[1:]):
self.commands = { 'install': { 'function': self.install,
'min_args': 1,
... | B2G/gecko/testing/mozbase/mozdevice/mozdevice/dmcli.py | import os
import posixpath
import StringIO
import sys
import textwrap
import mozdevice
from optparse import OptionParser
class DMCli(object):
def __init__(self, args=sys.argv[1:]):
self.commands = { 'install': { 'function': self.install,
'min_args': 1,
... | 0.269806 | 0.071364 |
import mock
class SharedMock(mock.MagicMock):
"""
A MagicMock whose children are all itself.
>>> m = SharedMock()
>>> m is m.foo is m.bar is m.foo.bar.baz.qux
True
>>> m.foo.side_effect = ['hello from foo']
>>> m.bar()
'hello from foo'
'Magic' methods are not shared.
>>> m._... | mock_django/shared.py | import mock
class SharedMock(mock.MagicMock):
"""
A MagicMock whose children are all itself.
>>> m = SharedMock()
>>> m is m.foo is m.bar is m.foo.bar.baz.qux
True
>>> m.foo.side_effect = ['hello from foo']
>>> m.bar()
'hello from foo'
'Magic' methods are not shared.
>>> m._... | 0.669745 | 0.291069 |
#LOAD THE DATSET IMAGES
import sys
import subprocess
subprocess.call("apt-get install subversion".split())
subprocess.call("svn export https://github.com/YoniChechik/AI_is_Math/trunk/c_07_camera_calibration/images".split())
#IMPORT ALL THE EQUIRED PACKAGES
import numpy as np
import cv2
from glob... | ImageProcessingScripts/Image Distortion Correction Using OpenCV/image_distortion_correction.py |
#LOAD THE DATSET IMAGES
import sys
import subprocess
subprocess.call("apt-get install subversion".split())
subprocess.call("svn export https://github.com/YoniChechik/AI_is_Math/trunk/c_07_camera_calibration/images".split())
#IMPORT ALL THE EQUIRED PACKAGES
import numpy as np
import cv2
from glob... | 0.277767 | 0.284489 |
from utilities import utils
config = utils.config()
try:
admins = config["admins"]
botlog = config["botlog"]
embed = config["embed"]
github = config["github"]
home = config["home"]
owners = config["owners"]
postgres = config["postgres"]
prefix = config["prefix"]
support = config["su... | settings/constants.py | from utilities import utils
config = utils.config()
try:
admins = config["admins"]
botlog = config["botlog"]
embed = config["embed"]
github = config["github"]
home = config["home"]
owners = config["owners"]
postgres = config["postgres"]
prefix = config["prefix"]
support = config["su... | 0.213869 | 0.162015 |
#Below function is inspired from the REVC-Complementing-a-Strand-of-DNA.py
def take_reverse_complement(string):
#Take the reverse
reversed_string = string[::-1]
#Create a dictionary
complement_dict = {'A':'T','T':'A','G':'C','C':'G'}
#Take the compelement of the reverse
complement_reve... | bioinformatics-stronghold/ORF-Open-Reading-Frames.py | #Below function is inspired from the REVC-Complementing-a-Strand-of-DNA.py
def take_reverse_complement(string):
#Take the reverse
reversed_string = string[::-1]
#Create a dictionary
complement_dict = {'A':'T','T':'A','G':'C','C':'G'}
#Take the compelement of the reverse
complement_reve... | 0.437944 | 0.54819 |
import datetime
from typing import List
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import LoginUser, Base, Content, Client
engine = create_engine('sqlite:///pinet_screens.db?check_same_thread=False')
Base.metadata.bind = engine
DBParent = sessionmaker(bind=engine)
db_ses... | pinet_screens/database.py | import datetime
from typing import List
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import LoginUser, Base, Content, Client
engine = create_engine('sqlite:///pinet_screens.db?check_same_thread=False')
Base.metadata.bind = engine
DBParent = sessionmaker(bind=engine)
db_ses... | 0.282691 | 0.068913 |
from __future__ import annotations # allows using a class as typing inside the same class
from typing import List
def sort_by_name(name: str):
""" function needed to sort signal groups by name """
return len(name), name
class GreenYellowPhase:
def __init__(self, signalgroup_id: str, interval_index: int... | swift_cloud_py/entities/control_output/phase_diagram.py | from __future__ import annotations # allows using a class as typing inside the same class
from typing import List
def sort_by_name(name: str):
""" function needed to sort signal groups by name """
return len(name), name
class GreenYellowPhase:
def __init__(self, signalgroup_id: str, interval_index: int... | 0.948799 | 0.518729 |
# Test whether the broker reduces the message expiry interval when republishing
# a retained message, and eventually removes it.
# MQTT v5
# Helper publishes a message, with a medium length expiry with retained set. It
# publishes a second message with retained set but no expiry.
# Client connects, subscribes, gets m... | eclipse-mosquitto/test/broker/02-subpub-qos1-message-expiry-retain.py |
# Test whether the broker reduces the message expiry interval when republishing
# a retained message, and eventually removes it.
# MQTT v5
# Helper publishes a message, with a medium length expiry with retained set. It
# publishes a second message with retained set but no expiry.
# Client connects, subscribes, gets m... | 0.474875 | 0.364976 |
import blackbook.database
from flask import current_app
from flask.views import MethodView
__all__ = ['basecollection', 'errors']
__author__ = 'ievans3024'
API_URI_PREFIX = current_app.config.get('API_ROOT') or '/api'
class APIType(object):
"""Descriptor for properties that need to a class or a subclass of suc... | blackbook/api/__init__.py | import blackbook.database
from flask import current_app
from flask.views import MethodView
__all__ = ['basecollection', 'errors']
__author__ = 'ievans3024'
API_URI_PREFIX = current_app.config.get('API_ROOT') or '/api'
class APIType(object):
"""Descriptor for properties that need to a class or a subclass of suc... | 0.693369 | 0.067701 |
import datetime
import os
import random
import string
import tempfile
import typing as t
import unittest
from dataclasses import dataclass
from freezegun import freeze_time
from hmalib.common.models.pipeline import HashRecord
from hmalib.common.timebucketizer import CSViable, TimeBucketizer
@dataclass(eq=True)
class... | hasher-matcher-actioner/hmalib/common/tests/test_timebucket.py | import datetime
import os
import random
import string
import tempfile
import typing as t
import unittest
from dataclasses import dataclass
from freezegun import freeze_time
from hmalib.common.models.pipeline import HashRecord
from hmalib.common.timebucketizer import CSViable, TimeBucketizer
@dataclass(eq=True)
class... | 0.629319 | 0.230801 |
import argparse
import os
from pathlib import Path
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
import torch
from torch.utils.data import DataLoader
from package.data.tokenizers import RelationshipTokenizer
from package.data.label_encoders import LabelEncoder
from packa... | sagemaker_notebook_instance/containers/relationship_extraction/package/training.py | import argparse
import os
from pathlib import Path
from pytorch_lightning import Trainer
from pytorch_lightning.callbacks import ModelCheckpoint
import torch
from torch.utils.data import DataLoader
from package.data.tokenizers import RelationshipTokenizer
from package.data.label_encoders import LabelEncoder
from packa... | 0.719778 | 0.230541 |
from __future__ import absolute_import
from datetime import datetime
import json
from pyDataverse.exceptions import ApiAuthorizationError
from pyDataverse.exceptions import ApiResponseError
from pyDataverse.exceptions import ApiUrlError
from pyDataverse.exceptions import DataverseNotFoundError
from pyDataverse.exceptio... | src/pyDataverse/api.py | from __future__ import absolute_import
from datetime import datetime
import json
from pyDataverse.exceptions import ApiAuthorizationError
from pyDataverse.exceptions import ApiResponseError
from pyDataverse.exceptions import ApiUrlError
from pyDataverse.exceptions import DataverseNotFoundError
from pyDataverse.exceptio... | 0.785638 | 0.09739 |
from unittest import mock
import pytest
from submission import helpers
def test_send_email_with_html(mailoutbox, settings):
helpers.send_email(
subject='this thing',
reply_to=['<EMAIL>'],
recipients=['<EMAIL>'],
text_body='Hello',
html_body='<a>Hello</a>',
)
messa... | submission/tests/test_helpers.py | from unittest import mock
import pytest
from submission import helpers
def test_send_email_with_html(mailoutbox, settings):
helpers.send_email(
subject='this thing',
reply_to=['<EMAIL>'],
recipients=['<EMAIL>'],
text_body='Hello',
html_body='<a>Hello</a>',
)
messa... | 0.560974 | 0.376938 |