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 tqdm import tqdm import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torch.autograd as autograd from wrappers import make_atari, wrap_deepmind, wrap_pytorch from replay_memory import ReplayBuffer from QNet import QNet # plot reward...
DQN/train.py
import math import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torch.autograd as autograd from wrappers import make_atari, wrap_deepmind, wrap_pytorch from replay_memory import ReplayBuffer from QNet import QNet # plot reward...
0.696578
0.53206
from deprecation import deprecated from square.api_helper import APIHelper from square.http.api_response import ApiResponse from square.api.base_api import BaseApi class InventoryApi(BaseApi): """A Controller to access Endpoints in the square API.""" def __init__(self, config, auth_managers, call_back=None)...
square/api/inventory_api.py
from deprecation import deprecated from square.api_helper import APIHelper from square.http.api_response import ApiResponse from square.api.base_api import BaseApi class InventoryApi(BaseApi): """A Controller to access Endpoints in the square API.""" def __init__(self, config, auth_managers, call_back=None)...
0.885365
0.20093
from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name="home"), path('top_headlines/', views.top_headlines, name="Top_headlines"), path('search/', views.search_news, name="search"), #countries path('argentina/', views.argentina, name="argentina"), ...
news/urls.py
from django.urls import path, include from . import views urlpatterns = [ path('', views.home, name="home"), path('top_headlines/', views.top_headlines, name="Top_headlines"), path('search/', views.search_news, name="search"), #countries path('argentina/', views.argentina, name="argentina"), ...
0.271638
0.143848
__all__ = ['AsyncGa'] import numpy as np from math import inf from copy import deepcopy from pathlib import Path from random import Random from typing import Dict from typing import Callable from typing import List from asyncevo import Scheduler from asyncevo import Lineage from asyncevo import Member from asyncevo i...
asyncevo/asyncga.py
__all__ = ['AsyncGa'] import numpy as np from math import inf from copy import deepcopy from pathlib import Path from random import Random from typing import Dict from typing import Callable from typing import List from asyncevo import Scheduler from asyncevo import Lineage from asyncevo import Member from asyncevo i...
0.872931
0.324918
import re import unicodedata from datetime import date from decimal import Decimal from django.core.exceptions import ValidationError from django.utils.timezone import now from django.utils.translation import ugettext as _ EMAIL_VALIDATOR = re.compile(r'[a-zA-Z0-9\._-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]+') PHONE_FILTER = re...
jutil/validators.py
import re import unicodedata from datetime import date from decimal import Decimal from django.core.exceptions import ValidationError from django.utils.timezone import now from django.utils.translation import ugettext as _ EMAIL_VALIDATOR = re.compile(r'[a-zA-Z0-9\._-]+@[a-zA-Z0-9\._-]+\.[a-zA-Z]+') PHONE_FILTER = re...
0.464902
0.165222
from functools import reduce def is_trivial(dependency): (x, y) = dependency return y <= x; def is_superkey(key, dependency): (x, y) = dependency return key <= x def is_bcnf(dependency, key): return is_superkey(key, dependency) or is_trivial(dependency) def str_dependency(dependency): (x, y)...
db1/normalizer/normalizer.py
from functools import reduce def is_trivial(dependency): (x, y) = dependency return y <= x; def is_superkey(key, dependency): (x, y) = dependency return key <= x def is_bcnf(dependency, key): return is_superkey(key, dependency) or is_trivial(dependency) def str_dependency(dependency): (x, y)...
0.475849
0.452415
from gensim.models import word2vec, KeyedVectors, Word2Vec import pandas as pd import itertools import os import gc corpus_df = pd.DataFrame() diff_corpus_df = pd.DataFrame() def add_summary_description_message_to_corpus(corpus_df, path, files): x=0 for file in files: if file.split('.')[1] == 'parqu...
baselines/DeepLink/0_word2vec.py
from gensim.models import word2vec, KeyedVectors, Word2Vec import pandas as pd import itertools import os import gc corpus_df = pd.DataFrame() diff_corpus_df = pd.DataFrame() def add_summary_description_message_to_corpus(corpus_df, path, files): x=0 for file in files: if file.split('.')[1] == 'parqu...
0.331444
0.232343
from django import forms from newapp.models import Course, Category, Question from crispy_forms.helper import FormHelper from django.forms import ModelForm from crispy_forms.layout import Layout, Submit class CourseForm(forms.Form): class Meta: model = Course class SearchForm(forms.Form): search = forms....
newapp/forms.py
from django import forms from newapp.models import Course, Category, Question from crispy_forms.helper import FormHelper from django.forms import ModelForm from crispy_forms.layout import Layout, Submit class CourseForm(forms.Form): class Meta: model = Course class SearchForm(forms.Form): search = forms....
0.373533
0.13452
import numpy as np import os.path as osp from init_args_serializer import Serializable import rcsenv from pyrado.environments.rcspysim.base import RcsSim from pyrado.spaces.box import BoxSpace from pyrado.tasks.base import Task from pyrado.tasks.desired_state import RadiallySymmDesStateTask from pyrado.tasks.reward_fu...
Pyrado/pyrado/environments/rcspysim/quanser_qube.py
import numpy as np import os.path as osp from init_args_serializer import Serializable import rcsenv from pyrado.environments.rcspysim.base import RcsSim from pyrado.spaces.box import BoxSpace from pyrado.tasks.base import Task from pyrado.tasks.desired_state import RadiallySymmDesStateTask from pyrado.tasks.reward_fu...
0.802672
0.337777
import odoo from odoo.addons.point_of_sale.tests.common import TestPoSCommon @odoo.tests.tagged('post_install', '-at_install') class TestPoSStock(TestPoSCommon): """ Tests for anglo saxon accounting scenario. """ def setUp(self): super(TestPoSStock, self).setUp() self.config = self.basic_co...
odoo-13.0/addons/point_of_sale/tests/test_pos_stock_account.py
import odoo from odoo.addons.point_of_sale.tests.common import TestPoSCommon @odoo.tests.tagged('post_install', '-at_install') class TestPoSStock(TestPoSCommon): """ Tests for anglo saxon accounting scenario. """ def setUp(self): super(TestPoSStock, self).setUp() self.config = self.basic_co...
0.644225
0.331323
from cinderclient import api_versions from cinderclient.tests.unit import utils from cinderclient.tests.unit.v3 import fakes TRANSFER_URL = 'os-volume-transfer' TRANSFER_355_URL = 'volume-transfers' # Create calls need the right version of faked client v355cs = fakes.FakeClient(api_versions.APIVersion('3.55')) # Oth...
site-packages/cinderclient/tests/unit/v3/test_volume_transfers.py
from cinderclient import api_versions from cinderclient.tests.unit import utils from cinderclient.tests.unit.v3 import fakes TRANSFER_URL = 'os-volume-transfer' TRANSFER_355_URL = 'volume-transfers' # Create calls need the right version of faked client v355cs = fakes.FakeClient(api_versions.APIVersion('3.55')) # Oth...
0.544317
0.229287
from girder.api import access from girder.api.describe import Description, autoDescribeRoute from girder.api.rest import Resource, RestException from girder.constants import AccessType, SortDir from girder.models.folder import Folder from girder.models.user import User from ..constants import WORKSPACE_NAME from ..mode...
server/rest/workspace.py
from girder.api import access from girder.api.describe import Description, autoDescribeRoute from girder.api.rest import Resource, RestException from girder.constants import AccessType, SortDir from girder.models.folder import Folder from girder.models.user import User from ..constants import WORKSPACE_NAME from ..mode...
0.53437
0.13852
import copy import math import json import numpy as np import logging from qcelemental.models import AtomicInput, Result, Molecule from qcelemental.util.serialization import json_dumps from . import history from .exceptions import OptError class ComputeWrapper: """ An implementation of MolSSI's qc schema Pa...
optking/compute_wrappers.py
import copy import math import json import numpy as np import logging from qcelemental.models import AtomicInput, Result, Molecule from qcelemental.util.serialization import json_dumps from . import history from .exceptions import OptError class ComputeWrapper: """ An implementation of MolSSI's qc schema Pa...
0.796886
0.296094
import configparser import abc from collections import defaultdict from enum import Enum from re import match, finditer, Pattern from typing import Iterable, Union, Sequence import numpy as np import scipy.signal as signal from sigpipes.joiner import Merge from sigpipes.sigcontainer import SigContainer, DPath class...
sigpipes/sources.py
import configparser import abc from collections import defaultdict from enum import Enum from re import match, finditer, Pattern from typing import Iterable, Union, Sequence import numpy as np import scipy.signal as signal from sigpipes.joiner import Merge from sigpipes.sigcontainer import SigContainer, DPath class...
0.893111
0.237963
from neutron_lib import exceptions as n_exc from oslo_config import cfg from oslo_log import log import sqlalchemy as sa from sqlalchemy import sql from neutron._i18n import _, _LE from neutron.db import model_base from neutron.plugins.common import constants as p_const from neutron.plugins.ml2.drivers import type_tu...
neutron/plugins/ml2/drivers/type_geneve.py
from neutron_lib import exceptions as n_exc from oslo_config import cfg from oslo_log import log import sqlalchemy as sa from sqlalchemy import sql from neutron._i18n import _, _LE from neutron.db import model_base from neutron.plugins.common import constants as p_const from neutron.plugins.ml2.drivers import type_tu...
0.715424
0.123762
import psycopg2, urlparse, re, os import urlparse # url de la base de donnees heroku DATABASE_URL="postgres://eoxdsmbgnnjprd:819342ac1961db6dceb37078f90e581b45743e34502382e75184184eae7b1948@ec2-23-21-220-152.compute-1.amazonaws.com:5432/decknecom629ch" class Db: """Connexion a la base de donnees postgres de l'envir...
db.py
import psycopg2, urlparse, re, os import urlparse # url de la base de donnees heroku DATABASE_URL="postgres://eoxdsmbgnnjprd:819342ac1961db6dceb37078f90e581b45743e34502382e75184184eae7b1948@ec2-23-21-220-152.compute-1.amazonaws.com:5432/decknecom629ch" class Db: """Connexion a la base de donnees postgres de l'envir...
0.356671
0.221098
import torch from model import Discrete_Q_Function_CNN_NN from parameters import NN_Paramters, Algo_Param, Save_Paths, Load_Paths import numpy as np from algorithms.epsilon_greedy import epsilon_greedy from util.replay_buffer import Replay_Memory from util.reservoir_with_fifo_replay_buffer_flow_through import Half_Re...
algorithms/q_learning_cnn.py
import torch from model import Discrete_Q_Function_CNN_NN from parameters import NN_Paramters, Algo_Param, Save_Paths, Load_Paths import numpy as np from algorithms.epsilon_greedy import epsilon_greedy from util.replay_buffer import Replay_Memory from util.reservoir_with_fifo_replay_buffer_flow_through import Half_Re...
0.513425
0.369173
import json from unittest.mock import Mock, patch from homeassistant.components.climate.const import ( HVAC_MODE_COOL, HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_FAN_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.components.fan import SPEED_HIGH, SPEED...
tests/components/melissa/test_climate.py
import json from unittest.mock import Mock, patch from homeassistant.components.climate.const import ( HVAC_MODE_COOL, HVAC_MODE_DRY, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_FAN_MODE, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.components.fan import SPEED_HIGH, SPEED...
0.66888
0.241031
import abc import random from dungeoncrawler import utils class Ability(abc.ABC): mp_cost = 100 name = "Ability" def __init__(self, world, caster): self.world = world self.caster = caster def __repr__(self): return self.name def predicate(self): return self.cas...
dungeoncrawler/skills.py
import abc import random from dungeoncrawler import utils class Ability(abc.ABC): mp_cost = 100 name = "Ability" def __init__(self, world, caster): self.world = world self.caster = caster def __repr__(self): return self.name def predicate(self): return self.cas...
0.548432
0.231126
import unittest class TestBatch(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.datastore.batch import Batch return Batch def _make_one(self, client): return self._get_target_class()(client) def test_ctor(self): from google.cloud.grpc.d...
datastore/unit_tests/test_batch.py
import unittest class TestBatch(unittest.TestCase): @staticmethod def _get_target_class(): from google.cloud.datastore.batch import Batch return Batch def _make_one(self, client): return self._get_target_class()(client) def test_ctor(self): from google.cloud.grpc.d...
0.611614
0.359083
from django.db import models from django.db.utils import OperationalError from channels.binding.websockets import WebsocketBinding from django.dispatch import receiver from django.db.models.signals import post_save,post_delete,pre_delete class Events(models.Model): Timestamp = models.DateTimeField(aut...
src/EventsAPP/models.py
from django.db import models from django.db.utils import OperationalError from channels.binding.websockets import WebsocketBinding from django.dispatch import receiver from django.db.models.signals import post_save,post_delete,pre_delete class Events(models.Model): Timestamp = models.DateTimeField(aut...
0.327883
0.048047
import torch import os def read_config(): import yaml import argparse def to_namespace(d): n = argparse.Namespace() for k, v in d.items(): setattr(n, k, to_namespace(v) if isinstance(v, dict) else v) return n arg_parser = argparse.ArgumentParser() arg_parser.a...
ai_challenge/utils/utils.py
import torch import os def read_config(): import yaml import argparse def to_namespace(d): n = argparse.Namespace() for k, v in d.items(): setattr(n, k, to_namespace(v) if isinstance(v, dict) else v) return n arg_parser = argparse.ArgumentParser() arg_parser.a...
0.628977
0.167525
import sys import csv import humanize import elftools.elf.elffile as elffile from elftools.elf.constants import SH_FLAGS from elftools.elf.sections import SymbolTableSection ''' Script to gather metrics on ROM,RAM,Stack and Heap usage. To produce the memory trace: - Compile etissvp_lib with SC_MEM_WRITE_TRACE defin...
vm/get_metrics.py
import sys import csv import humanize import elftools.elf.elffile as elffile from elftools.elf.constants import SH_FLAGS from elftools.elf.sections import SymbolTableSection ''' Script to gather metrics on ROM,RAM,Stack and Heap usage. To produce the memory trace: - Compile etissvp_lib with SC_MEM_WRITE_TRACE defin...
0.352202
0.253832
import random import numpy as np from sklearn.preprocessing import KBinsDiscretizer, StandardScaler class NegativeFaceRecognition: def __transform_random(self, features, bins): """ transform the given discrete vectors into a new random representation. No discrete value is retained. ...
unsupervised/negative_face_recognition/negative_face_recognition.py
import random import numpy as np from sklearn.preprocessing import KBinsDiscretizer, StandardScaler class NegativeFaceRecognition: def __transform_random(self, features, bins): """ transform the given discrete vectors into a new random representation. No discrete value is retained. ...
0.795975
0.666683
import pytest import numpy as np from astropy import units as u from astropy.tests.helper import assert_quantity_allclose from astropy.coordinates import (SkyCoord, ICRS, SphericalRepresentation, SphericalDifferential, SphericalCosLatDifferential, CartesianRepresentation, CartesianDiff...
astropy/coordinates/tests/test_sky_coord_velocities.py
import pytest import numpy as np from astropy import units as u from astropy.tests.helper import assert_quantity_allclose from astropy.coordinates import (SkyCoord, ICRS, SphericalRepresentation, SphericalDifferential, SphericalCosLatDifferential, CartesianRepresentation, CartesianDiff...
0.730866
0.529203
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('students', '0051_auto_20180705_1200'), ] operations = [ migrations.AlterField( model_name='customuser', name='applicationtype', field=models.CharField(b...
schoolproject/lgms/students/migrations/0052_auto_20180705_1221.py
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('students', '0051_auto_20180705_1200'), ] operations = [ migrations.AlterField( model_name='customuser', name='applicationtype', field=models.CharField(b...
0.469034
0.1532
import unittest import mock def _make_credentials(): import google.auth.credentials return mock.Mock(spec=google.auth.credentials.Credentials) class Test_ErrorReportingLoggingAPI(unittest.TestCase): PROJECT = "PROJECT" def _make_one(self, project, credentials, **kw): from google.cloud.e...
tests/unit/test__logging.py
import unittest import mock def _make_credentials(): import google.auth.credentials return mock.Mock(spec=google.auth.credentials.Credentials) class Test_ErrorReportingLoggingAPI(unittest.TestCase): PROJECT = "PROJECT" def _make_one(self, project, credentials, **kw): from google.cloud.e...
0.554229
0.214671
import os import time import numpy as np import tensorflow as tf from .li import LatentVariable from .gaminet import GAMINet from sklearn.metrics.pairwise import cosine_similarity from sklearn.cluster import KMeans from copy import deepcopy import networkx as nx import matplotlib.pyplot as plt from .utils import globa...
gammli/gammli.py
import os import time import numpy as np import tensorflow as tf from .li import LatentVariable from .gaminet import GAMINet from sklearn.metrics.pairwise import cosine_similarity from sklearn.cluster import KMeans from copy import deepcopy import networkx as nx import matplotlib.pyplot as plt from .utils import globa...
0.73659
0.475727
from django import forms from django.shortcuts import render from django.contrib.auth import get_user_model from .decorators import superuser_required from airmozilla.manage.forms import BaseForm from airmozilla.main.models import ( Event, SuggestedEvent, EventEmail, EventRevision, EventAssignment,...
airmozilla/manage/views/authmigrate.py
from django import forms from django.shortcuts import render from django.contrib.auth import get_user_model from .decorators import superuser_required from airmozilla.manage.forms import BaseForm from airmozilla.main.models import ( Event, SuggestedEvent, EventEmail, EventRevision, EventAssignment,...
0.337531
0.085709
import mysql.connector as mysql import Configuration as cfg import requests, uuid import notification.FBTabNotification as FBTabNotification class SQLTabNotification: def __init__(self): self.db = mysql.connect( host=cfg.db_host, user=cfg.db_user, passwd=cfg.db_passwd, ...
gymms_desktop/notification/SQLTabNotification.py
import mysql.connector as mysql import Configuration as cfg import requests, uuid import notification.FBTabNotification as FBTabNotification class SQLTabNotification: def __init__(self): self.db = mysql.connect( host=cfg.db_host, user=cfg.db_user, passwd=cfg.db_passwd, ...
0.236516
0.068944
import numpy as np COLUMN_COUNT = 7 ROW_COUNT = 6 class Board: """ this object created to deal with the board of the game itself. """ def __init__(self): """ this function define the Board object. self._board: the board itself. """ self._board = Board._create_n...
IntroToCS_ex12/ex12/board.py
import numpy as np COLUMN_COUNT = 7 ROW_COUNT = 6 class Board: """ this object created to deal with the board of the game itself. """ def __init__(self): """ this function define the Board object. self._board: the board itself. """ self._board = Board._create_n...
0.713232
0.540803
from square.api_helper import APIHelper from square.http.api_response import ApiResponse from square.api.base_api import BaseApi class LocationsApi(BaseApi): """A Controller to access Endpoints in the square API.""" def __init__(self, config, auth_managers, call_back=None): super(LocationsApi, self)...
square/api/locations_api.py
from square.api_helper import APIHelper from square.http.api_response import ApiResponse from square.api.base_api import BaseApi class LocationsApi(BaseApi): """A Controller to access Endpoints in the square API.""" def __init__(self, config, auth_managers, call_back=None): super(LocationsApi, self)...
0.921685
0.218523
import requests import sys from pingdomlib.check import PingdomCheck from pingdomlib.contact import PingdomContact from pingdomlib.reports import PingdomEmailReport, PingdomSharedReport server_address = 'https://api.pingdom.com' api_version = '2.0' class Pingdom(object): """Main connection object to interact wi...
pingdomlib/pingdom.py
import requests import sys from pingdomlib.check import PingdomCheck from pingdomlib.contact import PingdomContact from pingdomlib.reports import PingdomEmailReport, PingdomSharedReport server_address = 'https://api.pingdom.com' api_version = '2.0' class Pingdom(object): """Main connection object to interact wi...
0.580352
0.126623
from __future__ import unicode_literals from mock import Mock, call from h.routes import includeme def test_includeme(): config = Mock(spec_set=['add_route']) includeme(config) # This may look like a ridiculous test, but the cost of keeping it # up-to-date is hopefully pretty low (run the tests w...
tests/h/routes_test.py
from __future__ import unicode_literals from mock import Mock, call from h.routes import includeme def test_includeme(): config = Mock(spec_set=['add_route']) includeme(config) # This may look like a ridiculous test, but the cost of keeping it # up-to-date is hopefully pretty low (run the tests w...
0.538741
0.080647
import typing as t from muffin import Application from muffin.plugins import BasePlugin from apiclient import APIClient __version__ = "3.5.1" __project__ = "muffin-apiclient" __author__ = "<NAME> <<EMAIL>>" __license__ = "MIT" T = t.TypeVar('T', bound=t.Callable) class Plugin(BasePlugin): """Make external...
muffin_apiclient/__init__.py
import typing as t from muffin import Application from muffin.plugins import BasePlugin from apiclient import APIClient __version__ = "3.5.1" __project__ = "muffin-apiclient" __author__ = "<NAME> <<EMAIL>>" __license__ = "MIT" T = t.TypeVar('T', bound=t.Callable) class Plugin(BasePlugin): """Make external...
0.522446
0.110663
from __future__ import absolute_import import logging import datetime from urllib.parse import urlparse from kubernetes import watch from talos.common import cache from talos.core import config from talos.core.i18n import _ from wecubek8s.common import jsonfilter from wecubek8s.common import k8s from wecubek8s.commo...
api/wecubek8s/wecubek8s/apps/model/api.py
from __future__ import absolute_import import logging import datetime from urllib.parse import urlparse from kubernetes import watch from talos.common import cache from talos.core import config from talos.core.i18n import _ from wecubek8s.common import jsonfilter from wecubek8s.common import k8s from wecubek8s.commo...
0.629433
0.087994
import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader import argparse from data import FacialKeypointsDataset from model import Net from transforms import * parser = argparse.ArgumentParser(description = 'Keypoint Detector') parser.add_argument('-d','--dir', type=str, metavar='',he...
main.py
import torch.nn as nn import torch.optim as optim from torch.utils.data import DataLoader import argparse from data import FacialKeypointsDataset from model import Net from transforms import * parser = argparse.ArgumentParser(description = 'Keypoint Detector') parser.add_argument('-d','--dir', type=str, metavar='',he...
0.775817
0.348229
import io import util, solution_parser, cloudserviceconfig_parser, cloudservicedef_parser, proj_parser from runtime_tests import check_prescript def get_solution_data(location, tests=True): # Tests Included (9/6/16) if tests: check_prescript.test_location(location) solution = solution_parser.SolutionParser...
pyscripts/pre_script.py
import io import util, solution_parser, cloudserviceconfig_parser, cloudservicedef_parser, proj_parser from runtime_tests import check_prescript def get_solution_data(location, tests=True): # Tests Included (9/6/16) if tests: check_prescript.test_location(location) solution = solution_parser.SolutionParser...
0.475849
0.279394
from typing import List, Any from .audience import ( alias, amazon_channel, and_, android_channel, apid, channel, date_attribute, device_token, ios_channel, named_user, not_, number_attribute, open_channel, or_, segment, sms_id, sms_sender, subscr...
urbanairship/push/__init__.py
from typing import List, Any from .audience import ( alias, amazon_channel, and_, android_channel, apid, channel, date_attribute, device_token, ios_channel, named_user, not_, number_attribute, open_channel, or_, segment, sms_id, sms_sender, subscr...
0.717507
0.14682
import logging import osmo.api_historical from osmo.config_osmo import localconfig import osmo.constants as co def _transfers(log, wallet_address): """ Parses log element and returns (list of inbound transfers, list of outbound transfers), relative to wallet_address. """ transfers_in = _transfers...
src/osmo/util_osmo.py
import logging import osmo.api_historical from osmo.config_osmo import localconfig import osmo.constants as co def _transfers(log, wallet_address): """ Parses log element and returns (list of inbound transfers, list of outbound transfers), relative to wallet_address. """ transfers_in = _transfers...
0.481941
0.175927
from csv import writer from re import sub from flask import * from libs.admin_authentication import * from libs.s3 import s3_upload, create_client_key_pair from libs.streaming_bytes_io import StreamingBytesIO from database.models import Participant, Study from config.constants import * from pages.admin_page...
api/participant_administration.py
from csv import writer from re import sub from flask import * from libs.admin_authentication import * from libs.s3 import s3_upload, create_client_key_pair from libs.streaming_bytes_io import StreamingBytesIO from database.models import Participant, Study from config.constants import * from pages.admin_page...
0.416085
0.106226
from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import namedtuple import os import tensorflow as tf # Disable TensorFlow warnings. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # namedtuple for keeping models, graphs, and iterators as one unit....
text-performance-attribution/src/models/neural/tf_utils.py
from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import namedtuple import os import tensorflow as tf # Disable TensorFlow warnings. os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # namedtuple for keeping models, graphs, and iterators as one unit....
0.909023
0.442757
import json import uuid from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, Generic, List, Set, TypeVar, Union import safer from attr import attrs from black import FileContent, FileMode, InvalidInput, TargetVersion, format_str from typing_extensions import TypedDict from jupyterbla...
jupyterblack/parser.py
import json import uuid from abc import ABC, abstractmethod from pathlib import Path from typing import Dict, Generic, List, Set, TypeVar, Union import safer from attr import attrs from black import FileContent, FileMode, InvalidInput, TargetVersion, format_str from typing_extensions import TypedDict from jupyterbla...
0.774796
0.189484
import bson from env import pymongo_env class SinglePymongoDocument(object): """A database accessor for a single document.""" def __init__(self, doc_id=None, id_field=None, document=None, collection=None): """Initializes the SinglePymongoDocument. The document with id 'doc_id' is used from the given 'col...
src/utils/single_pymongo_document.py
import bson from env import pymongo_env class SinglePymongoDocument(object): """A database accessor for a single document.""" def __init__(self, doc_id=None, id_field=None, document=None, collection=None): """Initializes the SinglePymongoDocument. The document with id 'doc_id' is used from the given 'col...
0.779154
0.234999
# (c) 2015, <NAME> <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: taiga_issue short_description: Creates/deletes an issue in a Taiga Project M...
venv/lib/python3.6/site-packages/ansible_collections/community/general/plugins/modules/web_infrastructure/taiga_issue.py
# (c) 2015, <NAME> <<EMAIL>> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = ''' --- module: taiga_issue short_description: Creates/deletes an issue in a Taiga Project M...
0.742422
0.219944
import json import logging import os import socket from http.server import BaseHTTPRequestHandler, HTTPServer from threading import Event, Thread import httpretty from ambianic import config from ambianic.notification import sendCloudNotification from ambianic.pipeline.store import SaveDetectionSamples from ambianic....
tests/pipeline/test_notify.py
import json import logging import os import socket from http.server import BaseHTTPRequestHandler, HTTPServer from threading import Event, Thread import httpretty from ambianic import config from ambianic.notification import sendCloudNotification from ambianic.pipeline.store import SaveDetectionSamples from ambianic....
0.618204
0.165863
from abaqusConstants import * class TensionStiffening: """The TensionStiffening object defines the retained tensile stress normal to a crack in a Concrete model. Notes ----- This object can be accessed by: .. code-block:: python import material mdb.models[name]....
src/abaqus/Material/Plastic/Concrete/TensionStiffening.py
from abaqusConstants import * class TensionStiffening: """The TensionStiffening object defines the retained tensile stress normal to a crack in a Concrete model. Notes ----- This object can be accessed by: .. code-block:: python import material mdb.models[name]....
0.932837
0.614018
import argparse import numpy as np import pandas import collections import progressbar import os import warnings import flydra_analysis.a2.core_analysis as core_analysis import flydra_analysis.analysis.result_utils as result_utils import flydra_core.reconstruct as reconstruct class StringWidget(progressbar.Widget): ...
flydra_analysis/flydra_analysis/a2/calculate_reprojection_errors.py
import argparse import numpy as np import pandas import collections import progressbar import os import warnings import flydra_analysis.a2.core_analysis as core_analysis import flydra_analysis.analysis.result_utils as result_utils import flydra_core.reconstruct as reconstruct class StringWidget(progressbar.Widget): ...
0.29088
0.176069
from smc.base.model import Element, ElementCreator from smc.base.structs import NestedDict from smc.api.exceptions import ElementNotFound from smc.base.util import element_resolver class RuleElement(object): """ Rule Element encapsulates actions for source, destination and service fields. """ @p...
smc/policy/rule_elements.py
from smc.base.model import Element, ElementCreator from smc.base.structs import NestedDict from smc.api.exceptions import ElementNotFound from smc.base.util import element_resolver class RuleElement(object): """ Rule Element encapsulates actions for source, destination and service fields. """ @p...
0.884869
0.33158
# Lint as: python3 r"""Train and Eval PPOClipAgent in the Mujoco environments. All hyperparameters come from the PPO paper https://arxiv.org/abs/1707.06347.pdf """ import os from absl import logging import gin import reverb import tensorflow.compat.v2 as tf from tf_agents.agents.ppo import ppo_clip_agent from tf_a...
tf_agents/experimental/examples/ppo/train_eval_lib.py
# Lint as: python3 r"""Train and Eval PPOClipAgent in the Mujoco environments. All hyperparameters come from the PPO paper https://arxiv.org/abs/1707.06347.pdf """ import os from absl import logging import gin import reverb import tensorflow.compat.v2 as tf from tf_agents.agents.ppo import ppo_clip_agent from tf_a...
0.868423
0.46217
from ..internals.cache.redis import get_conn from ..internals.database.database import get_cursor from ..utils.utils import get_value import ujson import dateutil import copy import datetime def get_top_artists_by_faves(offset, count, reload = False): redis = get_conn() key = 'top_artists:' + str(off...
src/lib/artist.py
from ..internals.cache.redis import get_conn from ..internals.database.database import get_cursor from ..utils.utils import get_value import ujson import dateutil import copy import datetime def get_top_artists_by_faves(offset, count, reload = False): redis = get_conn() key = 'top_artists:' + str(off...
0.234494
0.109277
import binascii import sys import warnings from dataclasses import dataclass from datetime import datetime from enum import Enum from typing import Callable, TypeVar T = TypeVar('T') SMS_DATETIME_FORMAT = '%d/%m/%Y %H:%M %z' class EventType(Enum): NEW_MESSAGE = b'NM' MAILBOX_UPDATE = b'MBU' GREETINGS =...
vvm_decoder.py
import binascii import sys import warnings from dataclasses import dataclass from datetime import datetime from enum import Enum from typing import Callable, TypeVar T = TypeVar('T') SMS_DATETIME_FORMAT = '%d/%m/%Y %H:%M %z' class EventType(Enum): NEW_MESSAGE = b'NM' MAILBOX_UPDATE = b'MBU' GREETINGS =...
0.523177
0.165222
from Logger import Logger import signal import sys from time import sleep import zmq import subprocess from SerialWriter import MySerial class master: def __init__(self): self.logger = Logger("SoPine_MainLog") self.InPB = "10009" self.OutPB = "10010" self.InRPi = "10019" se...
SoPine/main.py
from Logger import Logger import signal import sys from time import sleep import zmq import subprocess from SerialWriter import MySerial class master: def __init__(self): self.logger = Logger("SoPine_MainLog") self.InPB = "10009" self.OutPB = "10010" self.InRPi = "10019" se...
0.123723
0.059428
import numpy as np import sys import cv2 class SLIC: def __init__(self, img, step, nc): self.img = img self.height, self.width = img.shape[:2] self._convertToLAB() self.step = step self.nc = nc self.ns = step self.FLT_MAX = 1000000 self.ITERATIONS = 1...
SLICcv.py
import numpy as np import sys import cv2 class SLIC: def __init__(self, img, step, nc): self.img = img self.height, self.width = img.shape[:2] self._convertToLAB() self.step = step self.nc = nc self.ns = step self.FLT_MAX = 1000000 self.ITERATIONS = 1...
0.304869
0.46132
import os import sys import time import subprocess def find_all(a_str, sub_str): start = 0 b_starts = [] while True: start = a_str.find(sub_str, start) if start == -1: return b_starts #print start b_starts.append(start) start += 1 if os.getuid() != 0: print "Ro...
apps/qos/mininet-add-queues_modified.py
import os import sys import time import subprocess def find_all(a_str, sub_str): start = 0 b_starts = [] while True: start = a_str.find(sub_str, start) if start == -1: return b_starts #print start b_starts.append(start) start += 1 if os.getuid() != 0: print "Ro...
0.022222
0.134406
from typing import List from termcolor import colored from data_set_info_data_class.data_class.data_set_info import DataSetInfo from data_set_statistic_reporter import StatisticReporter from data_set_statistic_reporter.classes.data_class.statistic_reporter_data_class import StatisticReporterDataClass from data_set_st...
automatization_of_data_mining_project/main_functionality/create_statistics.py
from typing import List from termcolor import colored from data_set_info_data_class.data_class.data_set_info import DataSetInfo from data_set_statistic_reporter import StatisticReporter from data_set_statistic_reporter.classes.data_class.statistic_reporter_data_class import StatisticReporterDataClass from data_set_st...
0.532425
0.411406
from flask import Flask from flask import request, jsonify from flask_cors import CORS # type: ignore from flask_expects_json import expects_json # type: ignore import dabing server = Flask('Dabing', static_url_path='/') CORS(server) @server.route("/flask/info/device") def HTTP_GET_flask_info_devi...
HTTP_SERVER.py
from flask import Flask from flask import request, jsonify from flask_cors import CORS # type: ignore from flask_expects_json import expects_json # type: ignore import dabing server = Flask('Dabing', static_url_path='/') CORS(server) @server.route("/flask/info/device") def HTTP_GET_flask_info_devi...
0.606032
0.092524
# Third-party import numpy as np from ...potential import Hamiltonian, NullPotential, StaticFrame from ...units import UnitSystem from ...util import atleast_2d from ...integrate.timespec import parse_time_specification from .. import Orbit, PhaseSpacePosition from .nbody import direct_nbody_dop853 __all__ = ['Dire...
gala/dynamics/nbody/core.py
# Third-party import numpy as np from ...potential import Hamiltonian, NullPotential, StaticFrame from ...units import UnitSystem from ...util import atleast_2d from ...integrate.timespec import parse_time_specification from .. import Orbit, PhaseSpacePosition from .nbody import direct_nbody_dop853 __all__ = ['Dire...
0.791257
0.399519
import cohesity_management_sdk.models.ad_domain_identity class AdDomain(object): """Implementation of the 'AdDomain' model. Specifies information about an AD Domain. Attributes: dns_root (string): Specifies DNS root. forest (string): Specifies AD forest name. identity (AdDomainI...
cohesity_management_sdk/models/ad_domain.py
import cohesity_management_sdk.models.ad_domain_identity class AdDomain(object): """Implementation of the 'AdDomain' model. Specifies information about an AD Domain. Attributes: dns_root (string): Specifies DNS root. forest (string): Specifies AD forest name. identity (AdDomainI...
0.832441
0.306709
import unittest import os import random from fem import LineStructure, Distance, Force from fem import FEMComput from fem import load_model, save_model class TestSaveLoad(unittest.TestCase): """Тестирование на сохранение и загрузку моделей""" def setUp(self): # Файлы для конструкции собираемой кодом ...
tests/test_load_save.py
import unittest import os import random from fem import LineStructure, Distance, Force from fem import FEMComput from fem import load_model, save_model class TestSaveLoad(unittest.TestCase): """Тестирование на сохранение и загрузку моделей""" def setUp(self): # Файлы для конструкции собираемой кодом ...
0.154599
0.307085
from keras.layers import Input, concatenate, Embedding, Dropout, add from keras.layers.normalization import BatchNormalization from keras.layers.core import Dense, Activation, Flatten from keras.models import Model from keras import backend as K """ 超参数: OPT = 'adam' LOSS = 'binary_crossentropy' dropout_ALPHA ...
model/92.22/pre_model.py
from keras.layers import Input, concatenate, Embedding, Dropout, add from keras.layers.normalization import BatchNormalization from keras.layers.core import Dense, Activation, Flatten from keras.models import Model from keras import backend as K """ 超参数: OPT = 'adam' LOSS = 'binary_crossentropy' dropout_ALPHA ...
0.782995
0.377799
import os import unittest import json from flask_sqlalchemy import SQLAlchemy from flaskr import create_app from models import setup_db, Question, Category class TriviaTestCase(unittest.TestCase): """This class represents the trivia test case""" def setUp(self): """Define test variables and initiali...
02_trivia_api/starter/backend/test_flaskr.py
import os import unittest import json from flask_sqlalchemy import SQLAlchemy from flaskr import create_app from models import setup_db, Question, Category class TriviaTestCase(unittest.TestCase): """This class represents the trivia test case""" def setUp(self): """Define test variables and initiali...
0.474388
0.423696
from collections import defaultdict import re matcher = re.compile(fr"(.*)\sbags?\scontain\s(.*).") matcher2 = re.compile(fr"(\d)\s(.*)\sbags?") with open('input7.txt') as f: mapping = defaultdict(list) #Reverse mapping because why not. It makes it slightly easier to count backwards. bag_tree = defaultdict(lis...
day7.py
from collections import defaultdict import re matcher = re.compile(fr"(.*)\sbags?\scontain\s(.*).") matcher2 = re.compile(fr"(\d)\s(.*)\sbags?") with open('input7.txt') as f: mapping = defaultdict(list) #Reverse mapping because why not. It makes it slightly easier to count backwards. bag_tree = defaultdict(lis...
0.35031
0.241277
# Copyright: (c) 2020, muradm <<EMAIL>> # Apache License, Version 2.0 (see https://opensource.org/licenses/Apache-2.0) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = r''' action: instance short_description: Create/update/remove a linode instance description: ...
plugins/modules/instance.py
# Copyright: (c) 2020, muradm <<EMAIL>> # Apache License, Version 2.0 (see https://opensource.org/licenses/Apache-2.0) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = r''' action: instance short_description: Create/update/remove a linode instance description: ...
0.794544
0.336277
import numpy as np import os from scipy.io import loadmat from sklearn.datasets import load_svmlight_file def gisette2npz(): data_path = "./dataset/GISETTE" train_data = np.loadtxt(os.path.join(data_path, "GISETTE/gisette_train.data")) train_labels = np.loadtxt(os.path.join(data_path, "GISETTE/gisette_tr...
featureband/util/data_util.py
import numpy as np import os from scipy.io import loadmat from sklearn.datasets import load_svmlight_file def gisette2npz(): data_path = "./dataset/GISETTE" train_data = np.loadtxt(os.path.join(data_path, "GISETTE/gisette_train.data")) train_labels = np.loadtxt(os.path.join(data_path, "GISETTE/gisette_tr...
0.522202
0.395718
from unittest import mock import os import unittest from cumulusci.core.flowrunner import StepSpec from cumulusci.tasks.salesforce import DeployBundles from cumulusci.utils import temporary_dir from .util import create_task class TestDeployBundles(unittest.TestCase): def test_run_task(self): with tempora...
cumulusci/tasks/salesforce/tests/test_DeployBundles.py
from unittest import mock import os import unittest from cumulusci.core.flowrunner import StepSpec from cumulusci.tasks.salesforce import DeployBundles from cumulusci.utils import temporary_dir from .util import create_task class TestDeployBundles(unittest.TestCase): def test_run_task(self): with tempora...
0.435421
0.351255
from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse from colossus.apps.campaigns import models from colossus.apps.campaigns.constants import CampaignStatus from colossus.apps.campaigns.models import Campaign from colossus.apps.templates.tests.factories import EmailTemplateFactor...
colossus/apps/campaigns/tests/test_models.py
from django.contrib.sites.shortcuts import get_current_site from django.urls import reverse from colossus.apps.campaigns import models from colossus.apps.campaigns.constants import CampaignStatus from colossus.apps.campaigns.models import Campaign from colossus.apps.templates.tests.factories import EmailTemplateFactor...
0.488039
0.184345
from quart import url_for from lnurl import Lnurl, LnurlWithdrawResponse, encode as lnurl_encode # type: ignore from sqlite3 import Row from typing import NamedTuple import shortuuid # type: ignore class WithdrawLink(NamedTuple): id: str wallet: str title: str min_withdrawable: int m...
lnbits/extensions/withdraw/models.py
from quart import url_for from lnurl import Lnurl, LnurlWithdrawResponse, encode as lnurl_encode # type: ignore from sqlite3 import Row from typing import NamedTuple import shortuuid # type: ignore class WithdrawLink(NamedTuple): id: str wallet: str title: str min_withdrawable: int m...
0.63409
0.130507
from packetbeat import BaseTest class Test(BaseTest): def test_amqp_emit_receive(self): self.render_config_template( amqp_ports=[5672], ) self.run_packetbeat(pcap="amqp_emit_receive.pcap", debug_selectors=["amqp,tcp,publish"]) objs = self.r...
packetbeat/tests/system/test_0052_amqp_emit_receive.py
from packetbeat import BaseTest class Test(BaseTest): def test_amqp_emit_receive(self): self.render_config_template( amqp_ports=[5672], ) self.run_packetbeat(pcap="amqp_emit_receive.pcap", debug_selectors=["amqp,tcp,publish"]) objs = self.r...
0.548915
0.579638
import requests import json class Node: def __init__(self, mac, ip, port=5000, units=1): self.mac = mac self.ip = ip self.storage_units = units self.port = port def set_storage_units(self, nb_units): self.storage_units = nb_units def write(self, filename, bytes)...
lead/node.py
import requests import json class Node: def __init__(self, mac, ip, port=5000, units=1): self.mac = mac self.ip = ip self.storage_units = units self.port = port def set_storage_units(self, nb_units): self.storage_units = nb_units def write(self, filename, bytes)...
0.133882
0.185762
import tensorflow as tf def smda(model, x, y, epochs=1.0, eps=1.0, clip_min=0.0, clip_max=1.0, min_proba=0.0): xshape = tf.shape(x) n = xshape[0] target = tf.cond(tf.equal(0, tf.rank(y)), lambda: tf.zeros([n], dtype=tf.int32)+y, lambda: y) if isinsta...
attacks/smda.py
import tensorflow as tf def smda(model, x, y, epochs=1.0, eps=1.0, clip_min=0.0, clip_max=1.0, min_proba=0.0): xshape = tf.shape(x) n = xshape[0] target = tf.cond(tf.equal(0, tf.rank(y)), lambda: tf.zeros([n], dtype=tf.int32)+y, lambda: y) if isinsta...
0.811937
0.353177
import logging import os import string import sys import types import warnings warnings.filterwarnings('ignore', category=FutureWarning) # use python-decoratortools if it is installed, otherwise use our own local # copy. Imported this locally because it doesnt appear to be available on SUSE # and the fedora RPM does...
src/GaIA/pkgs/libsmbios/libsmbios-2.2.28/src/python/libsmbios_c/trace_decorator.py
import logging import os import string import sys import types import warnings warnings.filterwarnings('ignore', category=FutureWarning) # use python-decoratortools if it is installed, otherwise use our own local # copy. Imported this locally because it doesnt appear to be available on SUSE # and the fedora RPM does...
0.285472
0.102709
#VersionNo: 1.0 #Author: fhh #DateTime: 2020/5/12 17:36 #Describe: 实现django ORM转数据库 写入 #Function: #Journal: import re from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.db import models # Create your models here. from django.utils.html import forma...
Python3/Tornado/apps/pg/PG_Admin/pgadmin/models.py
#VersionNo: 1.0 #Author: fhh #DateTime: 2020/5/12 17:36 #Describe: 实现django ORM转数据库 写入 #Function: #Journal: import re from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.db import models # Create your models here. from django.utils.html import forma...
0.39946
0.145631
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QSlider, QLabel, QComboBox from PyQt5.QtCore import Qt from PyQt5.QtCore import pyqtSlot, pyqtSignal from channels.channel import Channel class DoubleSlider(QSlider): # create our our signal that we can connect to if necessary doubleValueChanged = pyqtSignal(f...
gui/slider.py
from PyQt5.QtWidgets import QWidget, QVBoxLayout, QSlider, QLabel, QComboBox from PyQt5.QtCore import Qt from PyQt5.QtCore import pyqtSlot, pyqtSignal from channels.channel import Channel class DoubleSlider(QSlider): # create our our signal that we can connect to if necessary doubleValueChanged = pyqtSignal(f...
0.765418
0.364099
import uuid import html import celery from celery import current_app from celery.result import AsyncResult from . import celery_interface from .dataWorker import DataWorker from modules.Database.app import Database class DataAdministrationMiddleware: def __init__(self, config): self.config = config ...
modules/DataAdministration/backend/middleware.py
import uuid import html import celery from celery import current_app from celery.result import AsyncResult from . import celery_interface from .dataWorker import DataWorker from modules.Database.app import Database class DataAdministrationMiddleware: def __init__(self, config): self.config = config ...
0.178311
0.115661
from shutil import rmtree from datetime import datetime from tempfile import mkdtemp from functools import partial from itertools import count import io import os import os.path import re import sys import textwrap from mock import Mock, patch, call import frozendate import pytest import tms from yoyo import read_mi...
yoyo/tests/test_cli_script.py
from shutil import rmtree from datetime import datetime from tempfile import mkdtemp from functools import partial from itertools import count import io import os import os.path import re import sys import textwrap from mock import Mock, patch, call import frozendate import pytest import tms from yoyo import read_mi...
0.349533
0.131285
from flask import Flask, render_template, url_for, request, Response, jsonify from flask_restful import Resource, Api from werkzeug.utils import redirect import network app = Flask(__name__, static_folder="static") api = Api(app) network_controller = network.NetworkController() @app.route('/wifi', methods=['GET']) d...
app.py
from flask import Flask, render_template, url_for, request, Response, jsonify from flask_restful import Resource, Api from werkzeug.utils import redirect import network app = Flask(__name__, static_folder="static") api = Api(app) network_controller = network.NetworkController() @app.route('/wifi', methods=['GET']) d...
0.423935
0.072867
import numpy as np import time # Gera valores inteiros aleatorios de 1 ate 100000 def gera_valor_aleatorio(): valor = np.random.randint(0, 100000) return valor # Gera o vetor de valores randomicos def gera_lista(limite_superior): lista = [] for i in range(limite_superior): numero = gera_valo...
Lista_3.py
import numpy as np import time # Gera valores inteiros aleatorios de 1 ate 100000 def gera_valor_aleatorio(): valor = np.random.randint(0, 100000) return valor # Gera o vetor de valores randomicos def gera_lista(limite_superior): lista = [] for i in range(limite_superior): numero = gera_valo...
0.341802
0.489931
from collections import defaultdict from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.functional import cached_property from wagtail.core.models import Page, Locale class PageIndex: """ An in-memory index of pages to remove the need to query the database. ...
wagtail_localize/synctree.py
from collections import defaultdict from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.functional import cached_property from wagtail.core.models import Page, Locale class PageIndex: """ An in-memory index of pages to remove the need to query the database. ...
0.78964
0.187337
# Copyright (c) 2017-2018, <NAME>. # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
ukpc/__init__.py
# Copyright (c) 2017-2018, <NAME>. # All rights reserved. # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the ...
0.647575
0.103024
from __future__ import print_function import os import sys import logging import argparse import pandas as pd import numpy as np file_path = os.path.dirname(os.path.realpath(__file__)) lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common')) sys.path.append(lib_path2) import candle logger = loggi...
Pilot1/Combo/combo.py
from __future__ import print_function import os import sys import logging import argparse import pandas as pd import numpy as np file_path = os.path.dirname(os.path.realpath(__file__)) lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common')) sys.path.append(lib_path2) import candle logger = loggi...
0.460532
0.164315
import pathlib import pylexibank from idspy import IDSDataset, IDSEntry class Dataset(IDSDataset): dir = pathlib.Path(__file__).parent id = "spagnolmaltese" IDSDataset.form_spec.strip_inside_brackets = True def cmd_download(self, args): self.raw_dir.xls2csv("ids_cl_maltese_v1.xlsx") de...
lexibank_spagnolmaltese.py
import pathlib import pylexibank from idspy import IDSDataset, IDSEntry class Dataset(IDSDataset): dir = pathlib.Path(__file__).parent id = "spagnolmaltese" IDSDataset.form_spec.strip_inside_brackets = True def cmd_download(self, args): self.raw_dir.xls2csv("ids_cl_maltese_v1.xlsx") de...
0.188959
0.280718
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the...
{{cookiecutter.project_slug}}/{{cookiecutter.project_slug}}/settings.py
import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/ # SECURITY WARNING: keep the...
0.407687
0.104614
from __future__ import annotations from typing import Final from aiohttp.hdrs import ACCEPT, AUTHORIZATION, CONTENT_TYPE, ORIGIN from aiohttp.web import Application from aiohttp.web_urldispatcher import ( AbstractResource, AbstractRoute, Resource, ResourceRoute, StaticResource, ) from openpeerpow...
openpeerpower/components/http/cors.py
from __future__ import annotations from typing import Final from aiohttp.hdrs import ACCEPT, AUTHORIZATION, CONTENT_TYPE, ORIGIN from aiohttp.web import Application from aiohttp.web_urldispatcher import ( AbstractResource, AbstractRoute, Resource, ResourceRoute, StaticResource, ) from openpeerpow...
0.806662
0.079032
from unittest.mock import ANY, Mock, call import flask import pytest from marshmallow import Schema, fields from sqlalchemy import Column, Integer, String, sql from flask_resty import ( Api, ApiError, AuthenticationBase, AuthorizeModifyMixin, GenericModelView, HasAnyCredentialsAuthorization, ...
tests/test_auth.py
from unittest.mock import ANY, Mock, call import flask import pytest from marshmallow import Schema, fields from sqlalchemy import Column, Integer, String, sql from flask_resty import ( Api, ApiError, AuthenticationBase, AuthorizeModifyMixin, GenericModelView, HasAnyCredentialsAuthorization, ...
0.61057
0.237057
import argparse import importlib import logging import re import traceback from collections import defaultdict from datetime import datetime from urllib.parse import urlsplit from django.db import transaction from django.db.models import Count from opencivicdata.core.models import Jurisdiction, Membership, Organizatio...
reports/utils.py
import argparse import importlib import logging import re import traceback from collections import defaultdict from datetime import datetime from urllib.parse import urlsplit from django.db import transaction from django.db.models import Count from opencivicdata.core.models import Jurisdiction, Membership, Organizatio...
0.396185
0.095941
from nonebot import on_request, RequestSession, on_command, CommandSession import plugins.getUser @on_request('friend') async def _(session: RequestSession): await session.approve() return @on_request('group') async def _(session: RequestSession): await session.approve() return @on_command('help_s...
plugins/UserRegister.py
from nonebot import on_request, RequestSession, on_command, CommandSession import plugins.getUser @on_request('friend') async def _(session: RequestSession): await session.approve() return @on_request('group') async def _(session: RequestSession): await session.approve() return @on_command('help_s...
0.113838
0.0697
import os.path import tornado.httpserver import tornado.ioloop import tornado.web import tornado.escape import signal import sys import logging import gblog.handlers as handlers from gblog import mytorndb from gblog import config from gblog import uimodule class Application(tornado.web.Application): def __init__...
gblog/server.py
import os.path import tornado.httpserver import tornado.ioloop import tornado.web import tornado.escape import signal import sys import logging import gblog.handlers as handlers from gblog import mytorndb from gblog import config from gblog import uimodule class Application(tornado.web.Application): def __init__...
0.238462
0.064535
run_name = Citlaltepetl_A # Type of simulation (1: Default mode: Construction of probability map. 2: Calibration mode). type_sim = 1 # Source of DEM. # source_dem = type of input data (1: SRTM 30 m. 2: Uploaded DEM (UTM). 3: Uploaded Data (lat, lon)). # topography_file = location of file containing topography (only u...
EXAMPLES/Normal_Version/Citlaltepetl_A/input_data.py
run_name = Citlaltepetl_A # Type of simulation (1: Default mode: Construction of probability map. 2: Calibration mode). type_sim = 1 # Source of DEM. # source_dem = type of input data (1: SRTM 30 m. 2: Uploaded DEM (UTM). 3: Uploaded Data (lat, lon)). # topography_file = location of file containing topography (only u...
0.849722
0.81372
from zentropi import ( Agent, ZentropiShell, on_event, on_message, run_agents ) class SnippetBot(Agent): """ An agent that can save and search text snippets. """ def save(self, text: str) -> None: """Saves text to data-store.""" print('DUMMY Save: {!r}'.format(text)...
examples/00_tutorials/07_snippets/snippet_bot.py
from zentropi import ( Agent, ZentropiShell, on_event, on_message, run_agents ) class SnippetBot(Agent): """ An agent that can save and search text snippets. """ def save(self, text: str) -> None: """Saves text to data-store.""" print('DUMMY Save: {!r}'.format(text)...
0.674158
0.237057
import Live class QuickApi(object): def __init__(self, c_instance): self.__c_live_instance = c_instance self.tracks = Tracks(c_instance) self.scenes = Scene(c_instance) self.session_view = SessionView(c_instance) self.song = Song(c_instance) self.app = App(c_instance) self.clip_slots = ClipSlots(c_ins...
LiveApiHelper.py
import Live class QuickApi(object): def __init__(self, c_instance): self.__c_live_instance = c_instance self.tracks = Tracks(c_instance) self.scenes = Scene(c_instance) self.session_view = SessionView(c_instance) self.song = Song(c_instance) self.app = App(c_instance) self.clip_slots = ClipSlots(c_ins...
0.271735
0.155527
import tensorflow as tf from matplotlib import cm from lmnet.networks.base import BaseNetwork class Base(BaseNetwork): """base network for classification This base network is for classification. Every classification's network class should extend this class. """ def __init__( self, ...
lmnet/lmnet/networks/classification/base.py
import tensorflow as tf from matplotlib import cm from lmnet.networks.base import BaseNetwork class Base(BaseNetwork): """base network for classification This base network is for classification. Every classification's network class should extend this class. """ def __init__( self, ...
0.956715
0.432183
from matplotlib.artist import Artist import matplotlib.figure import matplotlib.axes import inspect """ These exceptions are intended to be used by each converter. PPTXTranscriber catches these exceptions and decide processings. """ class NonDisplayException(Exception): """It is used for ``Artist`` which is not...
figpptx/converter_manager.py
from matplotlib.artist import Artist import matplotlib.figure import matplotlib.axes import inspect """ These exceptions are intended to be used by each converter. PPTXTranscriber catches these exceptions and decide processings. """ class NonDisplayException(Exception): """It is used for ``Artist`` which is not...
0.80456
0.479016
from __future__ import absolute_import import unittest from testutils import ADMIN_CLIENT, suppress_urllib3_warning from testutils import harbor_server from testutils import TEARDOWN from library.base import _assert_status_code from library.project import Project from library.user import User from library...
tests/apitests/python/test_del_repo.py
from __future__ import absolute_import import unittest from testutils import ADMIN_CLIENT, suppress_urllib3_warning from testutils import harbor_server from testutils import TEARDOWN from library.base import _assert_status_code from library.project import Project from library.user import User from library...
0.498291
0.181771
from __future__ import absolute_import from builtins import next from builtins import object from abc import ABCMeta, abstractmethod import logging import shutil import threading import subprocess import multiprocessing from bd2k.util.processes import which from bd2k.util.threading import ExceptionalThread from future...
src/toil/batchSystems/mesos/test/__init__.py
from __future__ import absolute_import from builtins import next from builtins import object from abc import ABCMeta, abstractmethod import logging import shutil import threading import subprocess import multiprocessing from bd2k.util.processes import which from bd2k.util.threading import ExceptionalThread from future...
0.508788
0.113334
from crops.about import __prog__, __description__, __author__, __date__, __version__, __copyright__ import os import argparse def check_path(path,typeofpath=None): """Returns full path if correct. :param path: Input (local) path. :type path: str :param typeofpath: The type of path, 'dir' or 'file', ...
crops/io/__init__.py
from crops.about import __prog__, __description__, __author__, __date__, __version__, __copyright__ import os import argparse def check_path(path,typeofpath=None): """Returns full path if correct. :param path: Input (local) path. :type path: str :param typeofpath: The type of path, 'dir' or 'file', ...
0.572842
0.121113
import unittest from unittest import mock import commands.commandfactory as commandfactory import commands.multicommand as multicommand import filters.allbatchfilter as allbatchfilter class CommandFactoryTests(unittest.TestCase): def setUp(self): self.command_name = 'test' self.mock_command = moc...
tasks/tests/commandfactory_test.py
import unittest from unittest import mock import commands.commandfactory as commandfactory import commands.multicommand as multicommand import filters.allbatchfilter as allbatchfilter class CommandFactoryTests(unittest.TestCase): def setUp(self): self.command_name = 'test' self.mock_command = moc...
0.584271
0.305309
import logging from homeassistant.components.camera import Camera import requests import os import pickle from homeassistant.components.local_file.camera import LocalFile from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import ( DOMAIN, CONF_PHOTOS_ENTITY, CONF_PHOTOS, ...
custom_components/ha_strava/camera.py
import logging from homeassistant.components.camera import Camera import requests import os import pickle from homeassistant.components.local_file.camera import LocalFile from homeassistant.helpers.aiohttp_client import async_get_clientsession from .const import ( DOMAIN, CONF_PHOTOS_ENTITY, CONF_PHOTOS, ...
0.699254
0.121061
from typing import (TypeVar, Iterable, Any, Callable, List, Tuple) from .list import FSharpList from .map_util import (add_to_set, try_get_value, get_item_from_dict, add_to_dict) from .mutable_map import Dictionary from .mutable_set import HashSet from .seq import (delay, filter, map, to_array, to_list) from .types imp...
_tbnf/fable_modules/fable_library/seq2.py
from typing import (TypeVar, Iterable, Any, Callable, List, Tuple) from .list import FSharpList from .map_util import (add_to_set, try_get_value, get_item_from_dict, add_to_dict) from .mutable_map import Dictionary from .mutable_set import HashSet from .seq import (delay, filter, map, to_array, to_list) from .types imp...
0.52683
0.319254
from typing import Optional import struct from ._const import CMD_PREFIX, \ CMD_PREFIX_LEN, \ CMD_END, \ CMD_END_LEN, \ CMD_LEN, \ CMD_DATA_SIZE_LEN, \ CMD_PARITY_LEN, \ MAX_DATA_SIZE, \ CMD_PING from ._data import CommandRequest from ._exception import In...
picmd/_receiver.py
from typing import Optional import struct from ._const import CMD_PREFIX, \ CMD_PREFIX_LEN, \ CMD_END, \ CMD_END_LEN, \ CMD_LEN, \ CMD_DATA_SIZE_LEN, \ CMD_PARITY_LEN, \ MAX_DATA_SIZE, \ CMD_PING from ._data import CommandRequest from ._exception import In...
0.705886
0.103115