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 migen import *
from litex.build.sim import SimPlatform
from litex.build.sim.config import SimConfig
from litex.build.generic_platform import Pins, Subsignal
from litex.soc.interconnect.csr import CSRStorage, AutoCSR
from litedram.common import Settings, tXXDController
from litedram.phy.utils import Serializer, ... | litedram/phy/sim_utils.py |
from migen import *
from litex.build.sim import SimPlatform
from litex.build.sim.config import SimConfig
from litex.build.generic_platform import Pins, Subsignal
from litex.soc.interconnect.csr import CSRStorage, AutoCSR
from litedram.common import Settings, tXXDController
from litedram.phy.utils import Serializer, ... | 0.729809 | 0.258127 |
from src.utils.bbox import BBox
import numpy as np
"""
Pose configuration
"""
class PoseConfig:
# The joint order defined by the system
NAMES = ["head", "leftShoulder", "rightShoulder", "leftElbow", "rightElbow", "leftWrist", "rightWrist", "leftHip",
"rightHip", "leftKnee", "rightKnee", "leftAn... | src/utils/pose.py | from src.utils.bbox import BBox
import numpy as np
"""
Pose configuration
"""
class PoseConfig:
# The joint order defined by the system
NAMES = ["head", "leftShoulder", "rightShoulder", "leftElbow", "rightElbow", "leftWrist", "rightWrist", "leftHip",
"rightHip", "leftKnee", "rightKnee", "leftAn... | 0.811116 | 0.529507 |
from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from rest_framework import routers
from mooring import views, api
from mooring.admin import admin
from ledger.urls import urlpatterns as ledger_patterns
# API patterns
router = routers.DefaultRouter()... | mooring/urls.py | from django.conf import settings
from django.conf.urls import url, include
from django.conf.urls.static import static
from rest_framework import routers
from mooring import views, api
from mooring.admin import admin
from ledger.urls import urlpatterns as ledger_patterns
# API patterns
router = routers.DefaultRouter()... | 0.320715 | 0.066934 |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchtext import data, datasets, vocab
class MultiheadAttention(nn.Module):
"""
Implementation of Multihead Attention Module
Hat tip to Peter Bloem for very well written
http://peterbloem.nl/blog/transformers
"""
def __ini... | transformer-classification/transformer.py | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchtext import data, datasets, vocab
class MultiheadAttention(nn.Module):
"""
Implementation of Multihead Attention Module
Hat tip to Peter Bloem for very well written
http://peterbloem.nl/blog/transformers
"""
def __ini... | 0.93426 | 0.614625 |
from netaddr import IPNetwork
from exceptions import BadNetObjectId, LastSubNetAchieved
from net_object import NetObject
from ext.serialization import JsonSerializableObject
MAX_SUBNET_ID = 254
def _get_free_net_id(net_map):
subnets_id = [subnet.id for subnet in net_map.subnets]
for i in xrange(1, MAX_SUBN... | net_map/subnet.py | from netaddr import IPNetwork
from exceptions import BadNetObjectId, LastSubNetAchieved
from net_object import NetObject
from ext.serialization import JsonSerializableObject
MAX_SUBNET_ID = 254
def _get_free_net_id(net_map):
subnets_id = [subnet.id for subnet in net_map.subnets]
for i in xrange(1, MAX_SUBN... | 0.613815 | 0.058723 |
import os
import json
from files import Files
class Parametres():
def par_defaut(self): #Parametre par défaut
self.defaut = {
"texte_defaut": "Mini éditeur de texte fait par ElBretzel",
"longueur_defaut": "10",
"caractere_defaut": "o",
"mode_dangereux": "False",
"fi... | data/pref.py | import os
import json
from files import Files
class Parametres():
def par_defaut(self): #Parametre par défaut
self.defaut = {
"texte_defaut": "Mini éditeur de texte fait par ElBretzel",
"longueur_defaut": "10",
"caractere_defaut": "o",
"mode_dangereux": "False",
"fi... | 0.200362 | 0.322573 |
from face_detection import FaceDetection
from head_pose_estimation import Head_Pose_estimation
from facial_landmarks_detection import FacialLandmarkDetection
from gaze_estimation import GazeEstimation
from argparse import ArgumentParser
from input_feeder import InputFeeder
from mouse_controller import MouseController
... | src/main.py | from face_detection import FaceDetection
from head_pose_estimation import Head_Pose_estimation
from facial_landmarks_detection import FacialLandmarkDetection
from gaze_estimation import GazeEstimation
from argparse import ArgumentParser
from input_feeder import InputFeeder
from mouse_controller import MouseController
... | 0.550366 | 0.309845 |
import argparse
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
import seaborn as sns
sns.set()
class recurrent_classifier:
def __init__(self, train_path):
self.seq_x, self.seq_y, self.labels, self.noOfLabels = self.get_data(train_path)
self.test_seq_x, self.... | DAgger_imitationLearning/dagger_on_recurrent_classifier.py | import argparse
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm
import seaborn as sns
sns.set()
class recurrent_classifier:
def __init__(self, train_path):
self.seq_x, self.seq_y, self.labels, self.noOfLabels = self.get_data(train_path)
self.test_seq_x, self.... | 0.407923 | 0.339581 |
from io import BytesIO
import bs4
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from PIL import Image
from collect_image.forms import FoodImageForm
from collect_image.models import FoodImage
from collect_image.tests.test_setup import TestSetUp
class TestFoodImageForm(... | collect_image/tests/test_forms.py | from io import BytesIO
import bs4
from django.core.files.uploadedfile import SimpleUploadedFile
from django.urls import reverse
from PIL import Image
from collect_image.forms import FoodImageForm
from collect_image.models import FoodImage
from collect_image.tests.test_setup import TestSetUp
class TestFoodImageForm(... | 0.473901 | 0.400867 |
import smtplib
import sys
# TODO : Eventually find an alternative solution to this
if '/home/git_repos/quasar_source/' not in sys.path:
sys.path.append('/home/git_repos/quasar_source/')
# Useful file + directory operations.
from universal_code import useful_file_operations as ufo
# Contains useful paths needed.
... | libraries/python/universal_utilities/sms_sender.py | import smtplib
import sys
# TODO : Eventually find an alternative solution to this
if '/home/git_repos/quasar_source/' not in sys.path:
sys.path.append('/home/git_repos/quasar_source/')
# Useful file + directory operations.
from universal_code import useful_file_operations as ufo
# Contains useful paths needed.
... | 0.234933 | 0.11204 |
from json import dumps, loads
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
import base64
def get_access_token(url, client_id, client_secret, refresh_token):
secret = bytes(u'%s:%s' % (client_id, client_secret), 'utf-8')
encoded_secret = base... | core/python/utils/osdu_utils.py | from json import dumps, loads
from urllib.error import HTTPError
from urllib.parse import urlencode
from urllib.request import Request, urlopen
import base64
def get_access_token(url, client_id, client_secret, refresh_token):
secret = bytes(u'%s:%s' % (client_id, client_secret), 'utf-8')
encoded_secret = base... | 0.344003 | 0.072374 |
from ..bottoken import getConn
def initDB():
with getConn('dndppbot') as conn:
cur = conn.cursor()
conn.rollback()
cur.execute("CREATE TABLE IF NOT EXISTS Games(Code TEXT PRIMARY KEY NOT NULL, Title TEXT NOT NULL, DM BIGINT NOT NULL, Open BOOLEAN NOT NULL DEFAULT TRUE);")
cur.execute("CREATE TABLE IF... | dbFuncs.py | from ..bottoken import getConn
def initDB():
with getConn('dndppbot') as conn:
cur = conn.cursor()
conn.rollback()
cur.execute("CREATE TABLE IF NOT EXISTS Games(Code TEXT PRIMARY KEY NOT NULL, Title TEXT NOT NULL, DM BIGINT NOT NULL, Open BOOLEAN NOT NULL DEFAULT TRUE);")
cur.execute("CREATE TABLE IF... | 0.231267 | 0.076926 |
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional
from xsdata.models.datatype import XmlDateTime
__NAMESPACE__ = "http://xstest-tns/schema11_F4_3_16_v05"
class ElEnumerationAValue(Enum):
VALUE_1999_01_01_T01_01_00_Z = XmlDateTime(1999, 1, 1, 1, 1, 0, 0, 0)
VALUE... | output/models/ibm_data/valid/d4_3_16/d4_3_16v05_xsd/d4_3_16v05.py | from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional
from xsdata.models.datatype import XmlDateTime
__NAMESPACE__ = "http://xstest-tns/schema11_F4_3_16_v05"
class ElEnumerationAValue(Enum):
VALUE_1999_01_01_T01_01_00_Z = XmlDateTime(1999, 1, 1, 1, 1, 0, 0, 0)
VALUE... | 0.822332 | 0.276271 |
import torch
import numpy as np
import sys
import copy
import torch.nn as nn
from common_utils import TestCase, run_tests
from common_device_type import dtypes, instantiate_device_type_tests
from util_test import create_common_tensor
class TestRandom(TestCase):
@dtypes(torch.int32, torch.int64, torch.float, torch... | test/test_npu/test_network_ops/test_random.py |
import torch
import numpy as np
import sys
import copy
import torch.nn as nn
from common_utils import TestCase, run_tests
from common_device_type import dtypes, instantiate_device_type_tests
from util_test import create_common_tensor
class TestRandom(TestCase):
@dtypes(torch.int32, torch.int64, torch.float, torch... | 0.474631 | 0.611092 |
import unittest
from memo_table import MemoTable
import time
import spar_python.common.default_dict as dd
class MemoTableTest(unittest.TestCase):
def test_values_correct(self):
"""Create a function that computes the square of its argument. Then wrap
a memo-table around that and make sure we get th... | spar_python/common/memo_table_test.py |
import unittest
from memo_table import MemoTable
import time
import spar_python.common.default_dict as dd
class MemoTableTest(unittest.TestCase):
def test_values_correct(self):
"""Create a function that computes the square of its argument. Then wrap
a memo-table around that and make sure we get th... | 0.806624 | 0.670541 |
from unittest.mock import patch
import kaa
import kaa.config
from kaa import screen, document, cursor, context, editmode
from kaa.filetype.default import defaultmode
class _DmyWnd(context.Context):
def __init__(self, scrn):
self.screen = scrn
self.cursor = cursor.Cursor(self)
def set_editmode... | test/kaa_testutils.py | from unittest.mock import patch
import kaa
import kaa.config
from kaa import screen, document, cursor, context, editmode
from kaa.filetype.default import defaultmode
class _DmyWnd(context.Context):
def __init__(self, scrn):
self.screen = scrn
self.cursor = cursor.Cursor(self)
def set_editmode... | 0.541651 | 0.176193 |
import asyncio
from asyncio import queues
from ..core.task import Flow, Task
from ..flowrunner import FlowRunner
from ..utils.log import logger
from concurrent.futures import ThreadPoolExecutor
from functools import partial
class ParadeFlowRunner(FlowRunner):
# the thread pool to convert block execution of task... | src/parade/flowrunner/default.py | import asyncio
from asyncio import queues
from ..core.task import Flow, Task
from ..flowrunner import FlowRunner
from ..utils.log import logger
from concurrent.futures import ThreadPoolExecutor
from functools import partial
class ParadeFlowRunner(FlowRunner):
# the thread pool to convert block execution of task... | 0.40392 | 0.268247 |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
Base = declarative_base()
def convert_to_datetime(epoch, offset):
from datetime import timezone, timedelta, datetime
tz = timezone(timedelta(mi... | json_log_to_db.py |
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
Base = declarative_base()
def convert_to_datetime(epoch, offset):
from datetime import timezone, timedelta, datetime
tz = timezone(timedelta(mi... | 0.52975 | 0.180955 |
import contextlib
import errno
import os
import signal
import socket
import struct
def builtin_base(exc_type):
for cls in exc_type.mro():
if cls.__module__ != 'py3oserror':
return cls
# pytest.raises isn't catching these errors on Python 2.6
# implement a simple version with standard excepti... | test/test_errors.py | import contextlib
import errno
import os
import signal
import socket
import struct
def builtin_base(exc_type):
for cls in exc_type.mro():
if cls.__module__ != 'py3oserror':
return cls
# pytest.raises isn't catching these errors on Python 2.6
# implement a simple version with standard excepti... | 0.248625 | 0.251648 |
try:
from panalyse import *
except ImportError:
print("\033[38;5;196m[!] ImportError : panalyse not found !\033[00m")
banner = '''
\033[38;5;82m
___ ____ ____ _ _ ____ _ _ _ ____ ____ ____
|__] |___ |__| |\ | |__| | \_/ [__ |___ |__/
| |___ | | | \| | | |___ | ___] |___ | \ ... | PeAnalyser/pe_analyser.py |
try:
from panalyse import *
except ImportError:
print("\033[38;5;196m[!] ImportError : panalyse not found !\033[00m")
banner = '''
\033[38;5;82m
___ ____ ____ _ _ ____ _ _ _ ____ ____ ____
|__] |___ |__| |\ | |__| | \_/ [__ |___ |__/
| |___ | | | \| | | |___ | ___] |___ | \ ... | 0.106586 | 0.11928 |
import random
from mtsp.utils import *
from mtsp.route import Route
MUTATE_RATE = 0.02
class GA:
@classmethod
def evolve_population(self, pop):
'''single evolution iteration'''
for idx in range(int(pop.pop_size / 4)):
parent_1 = pop.get_route(2 * idx)
parent_2 = pop.ge... | GA/vns-ga/mtsp/galogic.py | import random
from mtsp.utils import *
from mtsp.route import Route
MUTATE_RATE = 0.02
class GA:
@classmethod
def evolve_population(self, pop):
'''single evolution iteration'''
for idx in range(int(pop.pop_size / 4)):
parent_1 = pop.get_route(2 * idx)
parent_2 = pop.ge... | 0.186762 | 0.320263 |
from __future__ import division
import argparse
import json
import os.path
import sys
import time
import warnings
from six import iteritems
import logic
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=RuntimeWarning)
__author__ = '<NAME>'
__email__ = '<EMAIL>'
... | fuzzy_tracts.py |
from __future__ import division
import argparse
import json
import os.path
import sys
import time
import warnings
from six import iteritems
import logic
warnings.filterwarnings("ignore", category=FutureWarning)
warnings.filterwarnings("ignore", category=RuntimeWarning)
__author__ = '<NAME>'
__email__ = '<EMAIL>'
... | 0.455925 | 0.132739 |
from __future__ import print_function, division
from sharedinfo import exist_file, get_lines
import sharedinfo
import sys
def sum_comma_sep_str(string):
""" return sum value of the comma separated string """
sum = 0
for i in string.split(","):
if not i == "":
#print(i)
sum +... | PGMF/script/focalintersect.py | from __future__ import print_function, division
from sharedinfo import exist_file, get_lines
import sharedinfo
import sys
def sum_comma_sep_str(string):
""" return sum value of the comma separated string """
sum = 0
for i in string.split(","):
if not i == "":
#print(i)
sum +... | 0.296145 | 0.269785 |
import logging
from collections import defaultdict
from psycopg2.extensions import TRANSACTION_STATUS_INTRANS, TRANSACTION_STATUS_INERROR
_log = logging.getLogger(__name__)
_log.setLevel(logging.WARN)
class Transaction(object):
"""
Database transaction manager for psycopg2 database connections with seamless... | nestedtransactions/transaction.py | import logging
from collections import defaultdict
from psycopg2.extensions import TRANSACTION_STATUS_INTRANS, TRANSACTION_STATUS_INERROR
_log = logging.getLogger(__name__)
_log.setLevel(logging.WARN)
class Transaction(object):
"""
Database transaction manager for psycopg2 database connections with seamless... | 0.619241 | 0.111676 |
import numpy as np
import pygame
def get_small_random_value(randomizer):
# generates a small random value between [0, 1/100)
return (1 / 100) * randomizer.rand()
class Ball(pygame.sprite.Sprite):
def __init__(self, randomizer, dims, speed, bounce_randomness=False):
self.surf = pygame.Surface(dim... | pettingzoo/butterfly/cooperative_pong/ball.py | import numpy as np
import pygame
def get_small_random_value(randomizer):
# generates a small random value between [0, 1/100)
return (1 / 100) * randomizer.rand()
class Ball(pygame.sprite.Sprite):
def __init__(self, randomizer, dims, speed, bounce_randomness=False):
self.surf = pygame.Surface(dim... | 0.58948 | 0.342957 |
import pandas as pd
from facebook_data_analysis.global_vars import messages_cols
from facebook_data_analysis.global_vars import OUTPUT_FOLDER
from facebook_data_analysis.tools.helpers import cached
from facebook_data_analysis.tools.helpers import resolve_path
def save_graph(file_name):
def decorator(wrapped):
... | facebook_data_analysis/conversation_analysis/activity_graphs.py | import pandas as pd
from facebook_data_analysis.global_vars import messages_cols
from facebook_data_analysis.global_vars import OUTPUT_FOLDER
from facebook_data_analysis.tools.helpers import cached
from facebook_data_analysis.tools.helpers import resolve_path
def save_graph(file_name):
def decorator(wrapped):
... | 0.58747 | 0.107883 |
import numpy as np
import dataset_creation.NSWPH_load_network_data as lnd
import dataset_creation.NSWPH_load_parameters as lpr
from dataset_creation.NSWPH_models import network_parameters
def nswph_models(n_sc, n_off, n_wf, n_wf_out, Pwf=0.0, Pl1=0.0, onshore=False, nswph=None, test=1):
"""
Construc... | dataset_creation/NSWPH_system_models.py | import numpy as np
import dataset_creation.NSWPH_load_network_data as lnd
import dataset_creation.NSWPH_load_parameters as lpr
from dataset_creation.NSWPH_models import network_parameters
def nswph_models(n_sc, n_off, n_wf, n_wf_out, Pwf=0.0, Pl1=0.0, onshore=False, nswph=None, test=1):
"""
Construc... | 0.457137 | 0.34065 |
from __future__ import division, absolute_import
from . import mp3bits, bitfields
import array
import weakref
### Channel structures
class ChannelBase(object):
__slots__ = ('_side_info', 'granules')
def __init__(self, side_info, granules):
self._side_info = side_info
self.granules = granules
_raw_side_info... | mp3frame/side_info.py |
from __future__ import division, absolute_import
from . import mp3bits, bitfields
import array
import weakref
### Channel structures
class ChannelBase(object):
__slots__ = ('_side_info', 'granules')
def __init__(self, side_info, granules):
self._side_info = side_info
self.granules = granules
_raw_side_info... | 0.453504 | 0.192293 |
import difflib
import json
import os
import re
import sys
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Optional, List
import pendulum
from kernelz.core import run_command
__all__ = ['list_kernels', 'list_kernel_dirs', 'list_kernels_like', 'list_conda_envs',
... | kernelz/jupyter.py | import difflib
import json
import os
import re
import sys
import tempfile
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Optional, List
import pendulum
from kernelz.core import run_command
__all__ = ['list_kernels', 'list_kernel_dirs', 'list_kernels_like', 'list_conda_envs',
... | 0.52829 | 0.120905 |
from __future__ import annotations
from typing import Literal
from prettyqt import constants, gui
from prettyqt.qt import QtCore, QtGui, QtWidgets
from prettyqt.utils import InvalidParamError, bidict
PANEL_MODALITY = bidict(
none=QtWidgets.QGraphicsItem.PanelModality.NonModal,
panel=QtWidgets.QGraphicsItem.... | prettyqt/widgets/graphicsitem.py | from __future__ import annotations
from typing import Literal
from prettyqt import constants, gui
from prettyqt.qt import QtCore, QtGui, QtWidgets
from prettyqt.utils import InvalidParamError, bidict
PANEL_MODALITY = bidict(
none=QtWidgets.QGraphicsItem.PanelModality.NonModal,
panel=QtWidgets.QGraphicsItem.... | 0.868018 | 0.075892 |
import tempfile
from pathlib import Path
import pytest
import os
os.environ['GITLIB_FS_BACKEND'] = 'filesystem-shim'
from gtmcore.gitlib import GitFilesystemShimmed
from gtmcore.gitlib.tests.git_interface_mixin import GitInterfaceMixin, get_backend, write_file
from gtmcore.gitlib.tests.git_interface_mixin import moc... | packages/gtmcore/gtmcore/gitlib/tests/test_git_filesystem_shim.py | import tempfile
from pathlib import Path
import pytest
import os
os.environ['GITLIB_FS_BACKEND'] = 'filesystem-shim'
from gtmcore.gitlib import GitFilesystemShimmed
from gtmcore.gitlib.tests.git_interface_mixin import GitInterfaceMixin, get_backend, write_file
from gtmcore.gitlib.tests.git_interface_mixin import moc... | 0.357119 | 0.150403 |
import django.core.serializers.json
import django.db.models.deletion
from cms.utils.compat import DJANGO_3_1
from django.db import migrations, models
import djangocms_frontend.fields
if DJANGO_3_1:
from django_jsonfield_backport.models import JSONField
else:
JSONField = models.JSONField
class Migration(mig... | djangocms_frontend/migrations/0001_initial.py |
import django.core.serializers.json
import django.db.models.deletion
from cms.utils.compat import DJANGO_3_1
from django.db import migrations, models
import djangocms_frontend.fields
if DJANGO_3_1:
from django_jsonfield_backport.models import JSONField
else:
JSONField = models.JSONField
class Migration(mig... | 0.390127 | 0.136234 |
from typing import Optional
from pydantic import BaseModel
from clai.datasource.server_status_datasource import ServerStatusDatasource
from clai.server.command_message import State, Action, ProcessesValues, FilesChangesValues, NetworkValues
from clai.server.command_runner.command_runner import CommandRunner, PostComm... | clai/server/command_runner/clai_last_info_command_runner.py | from typing import Optional
from pydantic import BaseModel
from clai.datasource.server_status_datasource import ServerStatusDatasource
from clai.server.command_message import State, Action, ProcessesValues, FilesChangesValues, NetworkValues
from clai.server.command_runner.command_runner import CommandRunner, PostComm... | 0.837288 | 0.130285 |
import itertools
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
## Class and function definitions
def distance(pt, center=(0,0)):
"""Measures distance from point 'pt' to (x_c,y_c)
pt: tuple of (x,y)
return: float - distance
"""
dx, dy = np.subtract... | pi_derivation.py | import itertools
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
## Class and function definitions
def distance(pt, center=(0,0)):
"""Measures distance from point 'pt' to (x_c,y_c)
pt: tuple of (x,y)
return: float - distance
"""
dx, dy = np.subtract... | 0.72952 | 0.570212 |
import asyncio.queues
import collections
import heapq
from typing import Generic, TypeVar
import cocotb
from cocotb.triggers import Event, _pointer_str
class QueueFull(asyncio.queues.QueueFull):
"""Raised when the Queue.put_nowait() method is called on a full Queue."""
class QueueEmpty(asyncio.queues.QueueEmpt... | cocotb/queue.py | import asyncio.queues
import collections
import heapq
from typing import Generic, TypeVar
import cocotb
from cocotb.triggers import Event, _pointer_str
class QueueFull(asyncio.queues.QueueFull):
"""Raised when the Queue.put_nowait() method is called on a full Queue."""
class QueueEmpty(asyncio.queues.QueueEmpt... | 0.909988 | 0.264706 |
import click, os, tempfile, unittest
from click.testing import CliRunner
from unittest.mock import MagicMock, patch
from tests.test_cw_base import BaseWithDb
class CwWfTest(BaseWithDb):
def test_wf_cli(self):
runner = CliRunner()
from cw.wf import cli
result = runner.invoke(cli, ["--help"... | tests/test_cw_wf.py | import click, os, tempfile, unittest
from click.testing import CliRunner
from unittest.mock import MagicMock, patch
from tests.test_cw_base import BaseWithDb
class CwWfTest(BaseWithDb):
def test_wf_cli(self):
runner = CliRunner()
from cw.wf import cli
result = runner.invoke(cli, ["--help"... | 0.367951 | 0.285319 |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
__all__ = ['DataFeedArgs', 'DataFeed']
@pulumi.input_type
class DataFeedArgs:
def __init__(__self__, *,
source_id: pulumi.Input[str],
... | sdk/python/pulumi_ns1/data_feed.py |
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import _utilities
__all__ = ['DataFeedArgs', 'DataFeed']
@pulumi.input_type
class DataFeedArgs:
def __init__(__self__, *,
source_id: pulumi.Input[str],
... | 0.838548 | 0.158435 |
array([[3.06957962, 0.70322209],
[3.21487456, 0.6941981 ],
[3.36178869, 0.68840816],
[3.50994615, 0.68517987],
[3.65898274, 0.68379808],
[3.80855501, 0.68351701],
[3.95831501, 0.6835691 ],
[4.10807562, 0.68362114],
[4.25783491, 0.68367411],
[4.40759492, 0.6... | reinvent_base-10000-8-2021-05-07-124639.py | array([[3.06957962, 0.70322209],
[3.21487456, 0.6941981 ],
[3.36178869, 0.68840816],
[3.50994615, 0.68517987],
[3.65898274, 0.68379808],
[3.80855501, 0.68351701],
[3.95831501, 0.6835691 ],
[4.10807562, 0.68362114],
[4.25783491, 0.68367411],
[4.40759492, 0.6... | 0.102985 | 0.589982 |
# -*- coding: utf-8 -*-
from exception.ToolException import FailException
from utils.client import RestfulClient
from utils.client import RedfishClient
from utils.model import BaseModule
from utils.common import Constant
from utils.predo import get_hdm_firmware
STATUS_DICT = {
"0": "OK",
"1": "... | model/get_pcie.py |
# -*- coding: utf-8 -*-
from exception.ToolException import FailException
from utils.client import RestfulClient
from utils.client import RedfishClient
from utils.model import BaseModule
from utils.common import Constant
from utils.predo import get_hdm_firmware
STATUS_DICT = {
"0": "OK",
"1": "... | 0.314682 | 0.080502 |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# read in data
mnist = input_data.read_data_sets("", one_hot=True)
# define number of hidden layers and nodes per hidden layer
# define number of classes and batch size to avoid ram overload
n_classes = 10
batch_size = 128
# x is da... | mnist-example-cnn.py | import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# read in data
mnist = input_data.read_data_sets("", one_hot=True)
# define number of hidden layers and nodes per hidden layer
# define number of classes and batch size to avoid ram overload
n_classes = 10
batch_size = 128
# x is da... | 0.873201 | 0.770335 |
import re, cPickle
from disco.error import DataError
def notifier(urls):
"""
:type urls: url or list of urls
:param urls: a list of urls gives replica locators.
"""
def map(entry, params):
"""
Returns an iterable of (key, value) pairs given an *entry*.
:param entry: entry coming from the... | lib/disco/worker/classic/func.py | import re, cPickle
from disco.error import DataError
def notifier(urls):
"""
:type urls: url or list of urls
:param urls: a list of urls gives replica locators.
"""
def map(entry, params):
"""
Returns an iterable of (key, value) pairs given an *entry*.
:param entry: entry coming from the... | 0.828384 | 0.654777 |
from sims4.math import Vector3, vector3_rotate_axis_angle, TWO_PI
from sims4.tuning.tunable import TunableVariant, TunableAngle, TunableInterval, TunableFactory
from sims4.tuning.geometric import TunableVector3
import random
class TunableOffset(TunableVariant):
def __init__(self, *args, **kwargs):
(super(... | Scripts/simulation/tunable_utils/tunable_offset.py | from sims4.math import Vector3, vector3_rotate_axis_angle, TWO_PI
from sims4.tuning.tunable import TunableVariant, TunableAngle, TunableInterval, TunableFactory
from sims4.tuning.geometric import TunableVector3
import random
class TunableOffset(TunableVariant):
def __init__(self, *args, **kwargs):
(super(... | 0.849675 | 0.520984 |
import os
import sys
from enum import Enum
from os.path import sep
import PySimpleGUI as sg
from multibootusb.grub import init_base_grub, add_grub_menu_entry
from multibootusb.iso import extract_basic_efi_directory, list_iso_files
from multibootusb.drive import list_drives, FsTypes
from multibootusb.misc import get_re... | multibootusb/multi_boot_usb.py | import os
import sys
from enum import Enum
from os.path import sep
import PySimpleGUI as sg
from multibootusb.grub import init_base_grub, add_grub_menu_entry
from multibootusb.iso import extract_basic_efi_directory, list_iso_files
from multibootusb.drive import list_drives, FsTypes
from multibootusb.misc import get_re... | 0.157947 | 0.060169 |
import numpy as np
import pandas as pd
from scipy import stats
def sharpe_ratio(returns, risk_free=0, time_scale=252):
"""
Essa função, a partir da definição do parâmetro de retorno, fornece o sharpe ratio do ativo, com base na média histórica e desvio padrão dos retornos.
O risk free considerado é nulo.
... | turingquant/metrics.py |
import numpy as np
import pandas as pd
from scipy import stats
def sharpe_ratio(returns, risk_free=0, time_scale=252):
"""
Essa função, a partir da definição do parâmetro de retorno, fornece o sharpe ratio do ativo, com base na média histórica e desvio padrão dos retornos.
O risk free considerado é nulo.
... | 0.870267 | 0.659597 |
import cv2, imutils, socket
import numpy as np
import time, os
import base64
import threading, wave, pyaudio, pickle, struct
# For details visit pyshine.com
BUFF_SIZE = 65536
BREAK = False
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, BU... | streaming_side/testing/udp_client.py | import cv2, imutils, socket
import numpy as np
import time, os
import base64
import threading, wave, pyaudio, pickle, struct
# For details visit pyshine.com
BUFF_SIZE = 65536
BREAK = False
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, BU... | 0.133161 | 0.069289 |
import os, sys, re
tags = {}
tag_pos = {}
tags_of_interest = ["FORMAT","INFO"]
for key in tags_of_interest:
tags[key] = {}
def print_tags():
for t in tags.keys():
print t, tags[t]
if len(sys.argv) != 3:
print "<program> <erds vcf output> <formatted results>"
sys.exit(0)
vcf_... | format_erds_results.py |
import os, sys, re
tags = {}
tag_pos = {}
tags_of_interest = ["FORMAT","INFO"]
for key in tags_of_interest:
tags[key] = {}
def print_tags():
for t in tags.keys():
print t, tags[t]
if len(sys.argv) != 3:
print "<program> <erds vcf output> <formatted results>"
sys.exit(0)
vcf_... | 0.052316 | 0.15662 |
import os
from flask import flash, \
redirect, \
render_template, \
url_for, \
request, \
session as login_session, \
send_from_directory, \
jsonify
from werkzeug.utils import secure_filename
... | pemoi/pmoi_item.py | import os
from flask import flash, \
redirect, \
render_template, \
url_for, \
request, \
session as login_session, \
send_from_directory, \
jsonify
from werkzeug.utils import secure_filename
... | 0.463444 | 0.064801 |
import logging
from collections import defaultdict
from typing import Optional
class Entry(object):
"""
An Entry, i.e. a single line of a Desktop Entry file.
Such entries have a key, a value, and an optional locale:
Key[Locale]=Value
"""
def __init__(self, key: str,
value: s... | xdgprefs/core/desktop_entry.py | import logging
from collections import defaultdict
from typing import Optional
class Entry(object):
"""
An Entry, i.e. a single line of a Desktop Entry file.
Such entries have a key, a value, and an optional locale:
Key[Locale]=Value
"""
def __init__(self, key: str,
value: s... | 0.777173 | 0.250024 |
import discord
from discord.ext import commands
import requests
import random, string
import json
from time import sleep
from threading import Thread
from colorama import init, Fore;init()
with open("config.json", "r", encoding="utf-8-sig") as f:
config = json.load(f)
cleanmessage=0
def Flooder(id, mes... | cogs/Tools.py | import discord
from discord.ext import commands
import requests
import random, string
import json
from time import sleep
from threading import Thread
from colorama import init, Fore;init()
with open("config.json", "r", encoding="utf-8-sig") as f:
config = json.load(f)
cleanmessage=0
def Flooder(id, mes... | 0.159119 | 0.050635 |
from security_monkey.auditor import Categories, Auditor
from security_monkey.watchers.custom.password_policy import PasswordPolicy
class PasswordPolicyAuditor(Auditor):
index = PasswordPolicy.index
i_am_singular = PasswordPolicy.i_am_singular
i_am_plural = PasswordPolicy.i_am_plural
def check_1_5_upp... | security_monkey/auditors/custom/cis/password_policy.py | from security_monkey.auditor import Categories, Auditor
from security_monkey.watchers.custom.password_policy import PasswordPolicy
class PasswordPolicyAuditor(Auditor):
index = PasswordPolicy.index
i_am_singular = PasswordPolicy.i_am_singular
i_am_plural = PasswordPolicy.i_am_plural
def check_1_5_upp... | 0.48438 | 0.15034 |
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import parler.fields
import parler.models
class Migration(migrations.Migration):
dependencies = [
('froide_campaign', '0035_auto_20210108_1915'),
]
operations = [
migrat... | froide_campaign/migrations/0036_add_translateable_categories.py |
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
import parler.fields
import parler.models
class Migration(migrations.Migration):
dependencies = [
('froide_campaign', '0035_auto_20210108_1915'),
]
operations = [
migrat... | 0.506347 | 0.12692 |
import requests
import pandas as pd
from datetime import datetime
import ccxt
import sqlite3
import config
import settings
now = datetime.utcnow()
def get_fx(currency_f):
fx = requests.get(
'https://apilayer.net/api/live?access_key=a1d6d82a3df7cf7882c9dd2b35146d6e&source=USD&format=1').json()
return ... | Data_fetcher/fetcher_bal_orderbook.py | import requests
import pandas as pd
from datetime import datetime
import ccxt
import sqlite3
import config
import settings
now = datetime.utcnow()
def get_fx(currency_f):
fx = requests.get(
'https://apilayer.net/api/live?access_key=a1d6d82a3df7cf7882c9dd2b35146d6e&source=USD&format=1').json()
return ... | 0.318167 | 0.150091 |
from django.urls import include, path
# The REST Framework router will make sure our requests end up at the right resource dynamically.
from rest_framework import routers
from . import views
# Register URL
# Using routers from Rest framework allow us to have some URLs solved for example:
# Query all users will be: /us... | api/urls.py | from django.urls import include, path
# The REST Framework router will make sure our requests end up at the right resource dynamically.
from rest_framework import routers
from . import views
# Register URL
# Using routers from Rest framework allow us to have some URLs solved for example:
# Query all users will be: /us... | 0.530723 | 0.10833 |
import scipy.stats as spst
import scipy.special as spsp
import numpy as np
from . import opt_abc as opt
from . import opt_smile_abc as smile
class Cev(opt.OptAnalyticABC, smile.OptSmileABC, smile.MassZeroABC):
"""
Constant Elasticity of Variance (CEV) model.
Underlying price is assumed to follow CEV proc... | py/pyfeng/cev.py | import scipy.stats as spst
import scipy.special as spsp
import numpy as np
from . import opt_abc as opt
from . import opt_smile_abc as smile
class Cev(opt.OptAnalyticABC, smile.OptSmileABC, smile.MassZeroABC):
"""
Constant Elasticity of Variance (CEV) model.
Underlying price is assumed to follow CEV proc... | 0.875608 | 0.481941 |
import torch
import torch.nn.functional as F
from torch.autograd import Variable
def flatten(scores, labels):
"""
Flattens predictions in the batch (binary case)
"""
return scores.view(-1), labels.view(-1)
def lovasz_grad(gt_sorted):
"""
Computes gradient of the Lovasz extension w.r.t sort... | models/4-Deeplive.exe/code/training/lovasz.py |
import torch
import torch.nn.functional as F
from torch.autograd import Variable
def flatten(scores, labels):
"""
Flattens predictions in the batch (binary case)
"""
return scores.view(-1), labels.view(-1)
def lovasz_grad(gt_sorted):
"""
Computes gradient of the Lovasz extension w.r.t sort... | 0.930169 | 0.721988 |
import sys
def err(msg):
print("ERROR:", msg)
exit(1)
def parse_samples(f):
nms = None
samples = []
for l in f:
s = l.rstrip().split()
if not s: continue
if nms:
samples.append([int(l) for l in s])
else:
nms = [int(l) for l in s]
return (n... | tests/chk.py | import sys
def err(msg):
print("ERROR:", msg)
exit(1)
def parse_samples(f):
nms = None
samples = []
for l in f:
s = l.rstrip().split()
if not s: continue
if nms:
samples.append([int(l) for l in s])
else:
nms = [int(l) for l in s]
return (n... | 0.235988 | 0.412294 |
import numpy as np
# Change False to True for each block of code to see what it does
# Arithmetic operations between 2 NumPy arrays
if False:
a = np.array([1, 2, 3, 4])
b = np.array([1, 2, 1, 2])
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a ** b)
# Arithmetic operations be... | L2_numpy_pandas_1D/np_vector_example.py | import numpy as np
# Change False to True for each block of code to see what it does
# Arithmetic operations between 2 NumPy arrays
if False:
a = np.array([1, 2, 3, 4])
b = np.array([1, 2, 1, 2])
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a ** b)
# Arithmetic operations be... | 0.493897 | 0.611324 |
from Motor_Cortex import *
from Hippocampus import *
def new_registration():
clean()
h_line()
space_3()
"""
To check for the no.of entries to be made
"""
loop = int(input("How many entries are to be made : "))
x = 1
while x < loop or x == loop:
... | Hindbrain.py | from Motor_Cortex import *
from Hippocampus import *
def new_registration():
clean()
h_line()
space_3()
"""
To check for the no.of entries to be made
"""
loop = int(input("How many entries are to be made : "))
x = 1
while x < loop or x == loop:
... | 0.212232 | 0.312632 |
import asyncio
from dataclasses import replace as dc_replace
from functools import reduce
from ovld import OvldMC, ovld
from .. import operations, xtype
from ..info import About
from ..ir import Constant, Graph
from ..operations import primitives as P
from ..utils import (
AnnotationMismatchError,
InferenceE... | myia/abstract/infer.py |
import asyncio
from dataclasses import replace as dc_replace
from functools import reduce
from ovld import OvldMC, ovld
from .. import operations, xtype
from ..info import About
from ..ir import Constant, Graph
from ..operations import primitives as P
from ..utils import (
AnnotationMismatchError,
InferenceE... | 0.790773 | 0.162613 |
import re,urllib,urlparse,base64
from liveresolver.modules import client,decryptionUtils
from liveresolver.modules import jsunpack
from liveresolver.modules.log_utils import log
def resolve(url):
try:
page = re.compile('//(.+?)/(?:embed|v)/([0-9a-zA-Z-_]+)').findall(url)[0]
try: refere... | repo/script.module.liveresolver/lib/liveresolver/resolvers/sawlive.py | import re,urllib,urlparse,base64
from liveresolver.modules import client,decryptionUtils
from liveresolver.modules import jsunpack
from liveresolver.modules.log_utils import log
def resolve(url):
try:
page = re.compile('//(.+?)/(?:embed|v)/([0-9a-zA-Z-_]+)').findall(url)[0]
try: refere... | 0.125909 | 0.082254 |
from datetime import timedelta
from datetimerange import DateTimeRange
from timeutils.timeutils import round_minute_range
FERTILE_START = timedelta(minutes=14)
FERTILE_END = timedelta(minutes=40)
FERTILE_END_EVE = timedelta(minutes=26)
UNKNOWN_NAME = '[UNKNOWN]'
class Character:
def __init__(self, kids, name=U... | logreader/character.py | from datetime import timedelta
from datetimerange import DateTimeRange
from timeutils.timeutils import round_minute_range
FERTILE_START = timedelta(minutes=14)
FERTILE_END = timedelta(minutes=40)
FERTILE_END_EVE = timedelta(minutes=26)
UNKNOWN_NAME = '[UNKNOWN]'
class Character:
def __init__(self, kids, name=U... | 0.691602 | 0.204005 |
# 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... | tools/Vitis-AI-Runtime/VART/vart/trace/vaitrace/writer/parser/dpu_mc_parser/dpuv2.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.846403 | 0.326828 |
class MainData:
class Block:
def __init__(self, size):
self.size = size
self.tuples = [None] * size
self.numtuples = 0
def __getitem__(self, idx):
return self.tuples[idx]
def __setitem__(self, idx, t):
self.tuples[idx] = t
... | CS225/myCode/btree.py | class MainData:
class Block:
def __init__(self, size):
self.size = size
self.tuples = [None] * size
self.numtuples = 0
def __getitem__(self, idx):
return self.tuples[idx]
def __setitem__(self, idx, t):
self.tuples[idx] = t
... | 0.463687 | 0.262071 |
import numpy as np
use_numba = True
try:
import numba as nb
except:
use_numba = False
import Reconstruction as recons
import Derivative
import NewtonianEuler1d as ne
def _apply_mask_recons_prim_impl(density, velocity, mask, atmosphere_density):
# Apply atmosphere again but on reconstructed values
f... | pydro/LaneEmden1d.py |
import numpy as np
use_numba = True
try:
import numba as nb
except:
use_numba = False
import Reconstruction as recons
import Derivative
import NewtonianEuler1d as ne
def _apply_mask_recons_prim_impl(density, velocity, mask, atmosphere_density):
# Apply atmosphere again but on reconstructed values
f... | 0.727975 | 0.361052 |
import pandas
import string
import math
import csv
import os
from unicodedata import normalize
def remover_acentos(txt):
return normalize('NFKD', txt).encode('ASCII', 'ignore').decode('ASCII')
def containsNumber(line):
res = False
numero = 0
if any(i.isdigit() for i in str(line)):
... | Read_write_balorc_desp.py | import pandas
import string
import math
import csv
import os
from unicodedata import normalize
def remover_acentos(txt):
return normalize('NFKD', txt).encode('ASCII', 'ignore').decode('ASCII')
def containsNumber(line):
res = False
numero = 0
if any(i.isdigit() for i in str(line)):
... | 0.077024 | 0.255188 |
import spacy
from cdeid.utils.resources import *
def ent_tuple_to_bio(sentences, bio_scheme=BIO_SCHEME_2):
nlp = spacy.load('en_core_web_sm')
tokens_list = []
tokens_bio_list = []
for record_txt, record_entities in sentences:
entities = record_entities.get('entities', '')
entity_strs =... | cdeid/utils/converter.py | import spacy
from cdeid.utils.resources import *
def ent_tuple_to_bio(sentences, bio_scheme=BIO_SCHEME_2):
nlp = spacy.load('en_core_web_sm')
tokens_list = []
tokens_bio_list = []
for record_txt, record_entities in sentences:
entities = record_entities.get('entities', '')
entity_strs =... | 0.145753 | 0.177276 |
import argparse
import re
from . import config
from .parser import parse_pixiv
from .pxelem import PixivUrl
from .login import login
from . import imgfilter
def main():
parser = argparse.ArgumentParser(description="Pixiv downloader")
parser.add_argument(
"url",
type=str,
help="Pixiv U... | pxhelper/main.py | import argparse
import re
from . import config
from .parser import parse_pixiv
from .pxelem import PixivUrl
from .login import login
from . import imgfilter
def main():
parser = argparse.ArgumentParser(description="Pixiv downloader")
parser.add_argument(
"url",
type=str,
help="Pixiv U... | 0.461502 | 0.080683 |
import numpy as np
import math
__author__ = "<NAME>"
__copyright__ = "Copyright 2020"
class Vehicle:
"""Defines a vehicle which can be detected by sensors.
Parameters
----------
name : str
The name of the vehicle.
active : bool
Defines if the vehicle is active on starting the si... | vehicle.py | import numpy as np
import math
__author__ = "<NAME>"
__copyright__ = "Copyright 2020"
class Vehicle:
"""Defines a vehicle which can be detected by sensors.
Parameters
----------
name : str
The name of the vehicle.
active : bool
Defines if the vehicle is active on starting the si... | 0.793226 | 0.565959 |
from importlib.metadata import version as pkg_version
from pathlib import Path
ASSETS_DIR = Path('_static')
# Basic config
project = 'Naturtag'
copyright = '2022, <NAME>'
author = '<NAME>'
html_static_path = ['_static']
templates_path = ['_templates']
version = release = pkg_version('naturtag')
# Sphinx extension mo... | docs/conf.py | from importlib.metadata import version as pkg_version
from pathlib import Path
ASSETS_DIR = Path('_static')
# Basic config
project = 'Naturtag'
copyright = '2022, <NAME>'
author = '<NAME>'
html_static_path = ['_static']
templates_path = ['_templates']
version = release = pkg_version('naturtag')
# Sphinx extension mo... | 0.516108 | 0.103976 |
import gym
import numpy as np
import importlib
from mujoco_py import MjViewer
class HACEnv(gym.Env):
def __init__(self, task_id, eval_mode=False, **kwargs):
module = importlib.import_module(".." + task_id + ".design_agent_and_env", __name__)
self._env = env = module.design_env()
goal_space ... | sl_envs/hac/hac_env.py | import gym
import numpy as np
import importlib
from mujoco_py import MjViewer
class HACEnv(gym.Env):
def __init__(self, task_id, eval_mode=False, **kwargs):
module = importlib.import_module(".." + task_id + ".design_agent_and_env", __name__)
self._env = env = module.design_env()
goal_space ... | 0.520009 | 0.318379 |
import numpy as np
import datetime
import pandas as pd
from operator import itemgetter
from copy import deepcopy
class BotTester(object):
"""The BotTester object is used to evaluate how close a collection of bot's picks match human picks.
This can be used in the following manner:
tester = BotTeste... | bots/draftsimtools/bot_tester.py | import numpy as np
import datetime
import pandas as pd
from operator import itemgetter
from copy import deepcopy
class BotTester(object):
"""The BotTester object is used to evaluate how close a collection of bot's picks match human picks.
This can be used in the following manner:
tester = BotTeste... | 0.609292 | 0.337395 |
import tkinter as tk
import tkinter.ttk as ttk
import src.view.templateWindow as tw
import src.controller.senhasController as sc
class SenhasView(tw.TemplateWindow):
def __init__(
self, fra_top_senha, fra_top_usuario,
fra_bottom_senha, fra_bottom_usuario
):
self.fra_top_senha... | src/view/senhasView.py | import tkinter as tk
import tkinter.ttk as ttk
import src.view.templateWindow as tw
import src.controller.senhasController as sc
class SenhasView(tw.TemplateWindow):
def __init__(
self, fra_top_senha, fra_top_usuario,
fra_bottom_senha, fra_bottom_usuario
):
self.fra_top_senha... | 0.422386 | 0.077378 |
import codecs
from collections import namedtuple
from electrumx.lib.tx import DeserializerSegWit
from electrumx.lib.tx_dash import (
TxOutPoint, DashProRegTx, DashProUpServTx, DashProUpRegTx,
DashProUpRevTx, DashCbTx, DashSubTxRegister,
DashSubTxTopup, DashSubTxResetKey, DashSubTxCloseAccount
)
from electru... | electrumx/lib/tx_bitgreen.py | import codecs
from collections import namedtuple
from electrumx.lib.tx import DeserializerSegWit
from electrumx.lib.tx_dash import (
TxOutPoint, DashProRegTx, DashProUpServTx, DashProUpRegTx,
DashProUpRevTx, DashCbTx, DashSubTxRegister,
DashSubTxTopup, DashSubTxResetKey, DashSubTxCloseAccount
)
from electru... | 0.608478 | 0.138928 |
import theano.tensor as T
def get_activation(activator):
r"""
Call an activation function from an activator object
Parameters
----------
activator : `activator`
an activator is an activation function, a tuple of (activation function, dict of args),
the name of the activati... | yadll/activations.py | import theano.tensor as T
def get_activation(activator):
r"""
Call an activation function from an activator object
Parameters
----------
activator : `activator`
an activator is an activation function, a tuple of (activation function, dict of args),
the name of the activati... | 0.936321 | 0.759448 |
import os
import argparse
from PIL import Image
import numpy as np
import cv2
Image.MAX_IMAGE_PIXELS = 100000000000
def main(args):
# identify test file
origin_files = os.listdir(args.test)
origin_files_id = [e.split('.')[0] for e in origin_files]
for _id in origin_files_id:
origin_img = Im... | scripts/generate_rsv_result.py | import os
import argparse
from PIL import Image
import numpy as np
import cv2
Image.MAX_IMAGE_PIXELS = 100000000000
def main(args):
# identify test file
origin_files = os.listdir(args.test)
origin_files_id = [e.split('.')[0] for e in origin_files]
for _id in origin_files_id:
origin_img = Im... | 0.359926 | 0.22464 |
import functools
class Route:
def __init__(self, board, coord, other_route=None):
self.board = board
self.vowels = int(board.shape[coord[1]][coord[0]] in "AEIOU")
if other_route:
self.vowels += other_route.vowels
self.coord = coord
def is_legal(self):
retur... | interview_challenges/schroders/interview_live_sequences.py | import functools
class Route:
def __init__(self, board, coord, other_route=None):
self.board = board
self.vowels = int(board.shape[coord[1]][coord[0]] in "AEIOU")
if other_route:
self.vowels += other_route.vowels
self.coord = coord
def is_legal(self):
retur... | 0.552298 | 0.337558 |
import tensorflow as tf
import numpy as np
import poisson_problem
import neural_networks
import matplotlib.pyplot as plt
from matplotlib import rc
import matplotlib.ticker as ticker
rc('font', **{'size':12, 'family':'serif', 'serif':['Computer Modern Roman']})
rc('text', usetex=True)
def draw_magnitude_int_loss(x_r... | poisson_problem/plots.py | import tensorflow as tf
import numpy as np
import poisson_problem
import neural_networks
import matplotlib.pyplot as plt
from matplotlib import rc
import matplotlib.ticker as ticker
rc('font', **{'size':12, 'family':'serif', 'serif':['Computer Modern Roman']})
rc('text', usetex=True)
def draw_magnitude_int_loss(x_r... | 0.517815 | 0.68541 |
from opentera.db.Base import db, BaseModel
class TeraServiceProject(db.Model, BaseModel):
__tablename__ = 't_services_projects'
id_service_project = db.Column(db.Integer, db.Sequence('id_service_project_sequence'), primary_key=True,
autoincrement=True)
id_service = db.Co... | teraserver/python/opentera/db/models/TeraServiceProject.py | from opentera.db.Base import db, BaseModel
class TeraServiceProject(db.Model, BaseModel):
__tablename__ = 't_services_projects'
id_service_project = db.Column(db.Integer, db.Sequence('id_service_project_sequence'), primary_key=True,
autoincrement=True)
id_service = db.Co... | 0.502441 | 0.061933 |
from collections import deque
from typing import List
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
"""
Depth first search
r = number of rows
c = number of columns
Time complexity: O(r * c)
Space complexity: O(r * c)
"""
row... | leetcode/Graphs/200. Number of Islands.py |
from collections import deque
from typing import List
class Solution:
def numIslands(self, grid: List[List[str]]) -> int:
"""
Depth first search
r = number of rows
c = number of columns
Time complexity: O(r * c)
Space complexity: O(r * c)
"""
row... | 0.872334 | 0.563228 |
import os
import pickle
import time
from functools import partial
from typing import List, Optional, Dict, Tuple, Any, Callable
import jax
import jax.numpy as jnp
import numpy as np
import wandb
from jax import jit, value_and_grad
from jax.experimental.optimizers import adam, sgd
from jax.tree_util import tree_leaves
... | dgm/main/learn_system.py | import os
import pickle
import time
from functools import partial
from typing import List, Optional, Dict, Tuple, Any, Callable
import jax
import jax.numpy as jnp
import numpy as np
import wandb
from jax import jit, value_and_grad
from jax.experimental.optimizers import adam, sgd
from jax.tree_util import tree_leaves
... | 0.813794 | 0.143278 |
import clr
import sys
sys.path.append('C:\Program Files (x86)\IronPython 2.7\Lib')
import System
from System import Array
from System.Collections.Generic import *
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Ele... | F0-16-UpdateBuildingEnvelopeDescriptions.py | import clr
import sys
sys.path.append('C:\Program Files (x86)\IronPython 2.7\Lib')
import System
from System import Array
from System.Collections.Generic import *
clr.AddReference('ProtoGeometry')
from Autodesk.DesignScript.Geometry import *
clr.AddReference("RevitNodes")
import Revit
clr.ImportExtensions(Revit.Ele... | 0.177597 | 0.094093 |
def first(str_input):
count = 0
for line in str_input.splitlines():
if isNice(line):
count += 1
return count
# A nice string is one with all of the following properties:
# It contains at least three vowels (aeiou only), like aei, xazegov, or aeiouaeiouaeiou.
# It contains at l... | adv_2015/day5_niceornaughty.py | def first(str_input):
count = 0
for line in str_input.splitlines():
if isNice(line):
count += 1
return count
# A nice string is one with all of the following properties:
# It contains at least three vowels (aeiou only), like aei, xazegov, or aeiouaeiouaeiou.
# It contains at l... | 0.322099 | 0.544559 |
import os
class leetsrc():
def get_151_problems_slug(self):
f = open(os.path.dirname(__file__)+"/151problem.txt")
slugs = f.read().splitlines()
f.close()
return slugs
def get_151_problems(self,problems):
ret =[]
slugs = self.get_151_problems_slug()
for pr... | autoload/leet/leetsrc.py | import os
class leetsrc():
def get_151_problems_slug(self):
f = open(os.path.dirname(__file__)+"/151problem.txt")
slugs = f.read().splitlines()
f.close()
return slugs
def get_151_problems(self,problems):
ret =[]
slugs = self.get_151_problems_slug()
for pr... | 0.258326 | 0.127354 |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import money.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('money', '0001_initial'),
]
operations = [
migrations.CreateModel(
... | backend/register/migrations/0001_initial.py | from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import money.models
class Migration(migrations.Migration):
initial = True
dependencies = [
('money', '0001_initial'),
]
operations = [
migrations.CreateModel(
... | 0.646237 | 0.167661 |
import torch
import numpy as np
import random
import hydra
from hydra.core.config_store import ConfigStore
from omegaconf import OmegaConf, DictConfig
from evaluator.evaluator import Evaluator
from model_builder import load_test_model
from data import (
MelSpectrogramConfig,
SpectrogramConfig,
MFCCConfig,... | eval.py |
import torch
import numpy as np
import random
import hydra
from hydra.core.config_store import ConfigStore
from omegaconf import OmegaConf, DictConfig
from evaluator.evaluator import Evaluator
from model_builder import load_test_model
from data import (
MelSpectrogramConfig,
SpectrogramConfig,
MFCCConfig,... | 0.53607 | 0.153581 |
import random
def riffleShuffle(va, flips):
nl = va
for n in range(flips):
#cut the deck at the middle +/- 10%, remove the second line of the formula for perfect cutting
cutPoint = len(nl)/2 + random.choice([-1, 1]) * random.randint(0, len(va)/10)
# split the deck
left = nl[0:c... | Card_shuffles/Python/shuffles.py | import random
def riffleShuffle(va, flips):
nl = va
for n in range(flips):
#cut the deck at the middle +/- 10%, remove the second line of the formula for perfect cutting
cutPoint = len(nl)/2 + random.choice([-1, 1]) * random.randint(0, len(va)/10)
# split the deck
left = nl[0:c... | 0.201263 | 0.461927 |
__author__ = '<NAME>'
__email__ = '<EMAIL>'
__status__ = 'Development'
__license__ = 'Apache 2.0'
from threading import Thread
import wx
from wx.lib.pubsub import pub
from massoc.scripts.main import run_neo4j
import webbrowser
from biom import load_table
import networkx as nx
from copy import deepcopy
from psutil impo... | massoc/GUI/database.py | __author__ = '<NAME>'
__email__ = '<EMAIL>'
__status__ = 'Development'
__license__ = 'Apache 2.0'
from threading import Thread
import wx
from wx.lib.pubsub import pub
from massoc.scripts.main import run_neo4j
import webbrowser
from biom import load_table
import networkx as nx
from copy import deepcopy
from psutil impo... | 0.388734 | 0.062875 |
import re
import urllib
import base64
from xml.etree import ElementTree
try:
import httplib
except ImportError:
import http.client as httplib
PROGRAM_NAME = "atdtool"
PROGRAM_VERSION = "1.3.3"
def checkDocument(cfg, fd):
'''Invoke checkDocument service and return a list of errors.'''
server = re.s... | atdtool/__init__.py |
import re
import urllib
import base64
from xml.etree import ElementTree
try:
import httplib
except ImportError:
import http.client as httplib
PROGRAM_NAME = "atdtool"
PROGRAM_VERSION = "1.3.3"
def checkDocument(cfg, fd):
'''Invoke checkDocument service and return a list of errors.'''
server = re.s... | 0.270191 | 0.097907 |
import datetime
import logging
from app import db, ma
from app.models.blacklist_user_token import BlacklistUserToken
import bcrypt
import jwt
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key = True, autoincrement = True)
email = db.Column(db.String(250), unique = True, n... | app/models/user.py | import datetime
import logging
from app import db, ma
from app.models.blacklist_user_token import BlacklistUserToken
import bcrypt
import jwt
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key = True, autoincrement = True)
email = db.Column(db.String(250), unique = True, n... | 0.568296 | 0.059839 |
from common.rule import Rule
from tree_decomposition import tree_decomposition
class TdRule(Rule):
"""
A hyperedge replacement grammar rule. In addition to storing the necessary
indexing information and graph fragment, computes various useful structures
(like the tree decomposition) which are independe... | parser_td/td_rule.py | from common.rule import Rule
from tree_decomposition import tree_decomposition
class TdRule(Rule):
"""
A hyperedge replacement grammar rule. In addition to storing the necessary
indexing information and graph fragment, computes various useful structures
(like the tree decomposition) which are independe... | 0.860662 | 0.745004 |
import os
import requests
import time
from requests.structures import CaseInsensitiveDict
#CVALUE
blue= '\33[94m'
lightblue = '\033[94m'
red = '\033[91m'
white = '\33[97m'
yellow = '\33[93m'
green = '\033[1;32m'
cyan = "\033[96m"
end = '\033[0m'
line=yellow+"===========================================================... | trbommer2.py | import os
import requests
import time
from requests.structures import CaseInsensitiveDict
#CVALUE
blue= '\33[94m'
lightblue = '\033[94m'
red = '\033[91m'
white = '\33[97m'
yellow = '\33[93m'
green = '\033[1;32m'
cyan = "\033[96m"
end = '\033[0m'
line=yellow+"===========================================================... | 0.024739 | 0.047736 |
import logging
import re
from os.path import join
from typing import List, get_type_hints
from Bio import AlignIO
from Bio.Emboss.Applications import WaterCommandline
from Bio.SeqRecord import SeqRecord
from numpy import array, nan
from pandas import DataFrame
from ..config import Configuration
__all__ = ("emboss_a... | src/sanger_sequencing/analysis/alignment.py | import logging
import re
from os.path import join
from typing import List, get_type_hints
from Bio import AlignIO
from Bio.Emboss.Applications import WaterCommandline
from Bio.SeqRecord import SeqRecord
from numpy import array, nan
from pandas import DataFrame
from ..config import Configuration
__all__ = ("emboss_a... | 0.760384 | 0.424352 |
import sys
import requests
from bs4 import BeautifulSoup
def main(dict):
response = {}
if dict.get('type') == 1:
url = "http://XXXXXXX.eu-gb.mybluemix.net/"
response = price(url)
elif dict.get('type') == 2:
MRP = dict['MRP']
products = dict['products']
Actual_Profit... | pricing-tool.py | import sys
import requests
from bs4 import BeautifulSoup
def main(dict):
response = {}
if dict.get('type') == 1:
url = "http://XXXXXXX.eu-gb.mybluemix.net/"
response = price(url)
elif dict.get('type') == 2:
MRP = dict['MRP']
products = dict['products']
Actual_Profit... | 0.103556 | 0.203292 |
import os
import math
import copy
import pickle
import numpy as np
class FclrLayer(object):
def __init__(self, optimizer, K, N, epsilon=0.2, param_file='work/fclr.pkl'):
'''
参数:
K:本层神经元个数
N: 特征维度(下一层神经元数)
'''
self.epsilon = epsilon
self.name = 'ann.layer.... | app/pytorch/book/chp004/e1/fclr_layer.py | import os
import math
import copy
import pickle
import numpy as np
class FclrLayer(object):
def __init__(self, optimizer, K, N, epsilon=0.2, param_file='work/fclr.pkl'):
'''
参数:
K:本层神经元个数
N: 特征维度(下一层神经元数)
'''
self.epsilon = epsilon
self.name = 'ann.layer.... | 0.387574 | 0.24599 |
from auth.handlers.resource.manager import AuthResourceManager, ResourceFilter
from iam.resource.provider import ListResult, ResourceProvider
class BKDataResourceProvider(ResourceProvider):
resource_type = None
def list_attr(self, **options):
manager = AuthResourceManager.init(self.resource_type)
... | src/api/auth/bkiam/resources.py | from auth.handlers.resource.manager import AuthResourceManager, ResourceFilter
from iam.resource.provider import ListResult, ResourceProvider
class BKDataResourceProvider(ResourceProvider):
resource_type = None
def list_attr(self, **options):
manager = AuthResourceManager.init(self.resource_type)
... | 0.440469 | 0.061424 |
import argparse
import yaml
'''
This was adapted from PonyGE2: https://github.com/PonyGE/PonyGE2
<NAME>., <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>. PonyGE2: Grammatical Evolution in Python. arXiv preprint, arXiv:1703.08535, 2017.
'''
""""Algorithm Parameters"""
params = {'PARAMETERS': None,
'POPSIZE': 1... | sge/sge/parameters.py | import argparse
import yaml
'''
This was adapted from PonyGE2: https://github.com/PonyGE/PonyGE2
<NAME>., <NAME>., <NAME>., <NAME>., <NAME>., and <NAME>. PonyGE2: Grammatical Evolution in Python. arXiv preprint, arXiv:1703.08535, 2017.
'''
""""Algorithm Parameters"""
params = {'PARAMETERS': None,
'POPSIZE': 1... | 0.460532 | 0.228232 |
import numpy as np
from HotPixelFilter import HotPixelFilter
from BackgroundFilter import BackgroundFilter
from maskRegionFilter import maskRegionFilter
import functools
def extract_from_aedat(aedat, events, startTime, stopTime, sx, sy, nbcam, thrEventHotPixel, dt, xmin_mask1, xmax_mask1, ymin_mask1, ymax_mask1, xmin_... | scripts/dhp19/generate_DHP19/Python_Files/extract_from_aedat.py | import numpy as np
from HotPixelFilter import HotPixelFilter
from BackgroundFilter import BackgroundFilter
from maskRegionFilter import maskRegionFilter
import functools
def extract_from_aedat(aedat, events, startTime, stopTime, sx, sy, nbcam, thrEventHotPixel, dt, xmin_mask1, xmax_mask1, ymin_mask1, ymax_mask1, xmin_... | 0.281702 | 0.463141 |
import numpy as np
import cv2
from dd_pose.image_decorator import ImageDecorator
from dd_pose.evaluation_helpers import T_headfrontal_camdriver
import transformations as tr
def get_dashboard(di, stamp):
# canvas to draw stuff onto
canvas = np.zeros((1024, 2048, 3), dtype=np.uint8)
# camdriver>head
... | dd_pose/visualization_helpers.py | import numpy as np
import cv2
from dd_pose.image_decorator import ImageDecorator
from dd_pose.evaluation_helpers import T_headfrontal_camdriver
import transformations as tr
def get_dashboard(di, stamp):
# canvas to draw stuff onto
canvas = np.zeros((1024, 2048, 3), dtype=np.uint8)
# camdriver>head
... | 0.432063 | 0.193642 |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations... | backend/posts/migrations/0001_initial.py |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations... | 0.501465 | 0.097993 |
from __future__ import print_function, division
import copy
import time
import datetime
import random
import os
from tqdm import tqdm
import pandas as pd
import numpy as np
import argparse
import warnings
import logging
from sklearn.model_selection import KFold
from sklearn.model_selection import train_test_split
imp... | CV/img2vec/main.py | from __future__ import print_function, division
import copy
import time
import datetime
import random
import os
from tqdm import tqdm
import pandas as pd
import numpy as np
import argparse
import warnings
import logging
from sklearn.model_selection import KFold
from sklearn.model_selection import train_test_split
imp... | 0.776581 | 0.367015 |