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 collectd
import subprocess
import re
import requests
NAME = 'rabbitmq_info'
# Override in config by specifying 'RmqcBin'.
RABBITMQCTL_BIN = '/usr/sbin/rabbitmqctl'
RABBITMQ_API = 'http://localhost:15672/api/queues'
# Override in config by specifying 'PmapBin'
PMAP_BIN = '/usr/bin/pmap'
# Override in config by ... | cookbooks/collectd_old_10302014/files/default/rabbitmq_info.py |
import collectd
import subprocess
import re
import requests
NAME = 'rabbitmq_info'
# Override in config by specifying 'RmqcBin'.
RABBITMQCTL_BIN = '/usr/sbin/rabbitmqctl'
RABBITMQ_API = 'http://localhost:15672/api/queues'
# Override in config by specifying 'PmapBin'
PMAP_BIN = '/usr/bin/pmap'
# Override in config by ... | 0.256366 | 0.082475 |
from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from .models import Equipment, Attachment
from .forms import EquipmentForm, AttachmentForm
def equipment_list(request, template='equipment/equipment_list.html'):
equipment_list = Equipment.objects.order_by('equipm... | sniffersapp/equipment/views.py | from django.contrib import messages
from django.shortcuts import render, get_object_or_404, redirect
from .models import Equipment, Attachment
from .forms import EquipmentForm, AttachmentForm
def equipment_list(request, template='equipment/equipment_list.html'):
equipment_list = Equipment.objects.order_by('equipm... | 0.417271 | 0.088387 |
import pytest
from binflakes.types import BinWord, BinInt
class TestBinInt:
def test_construct(self):
a = BinInt(12)
assert a == 12
a = BinInt(BinWord(12, 0x123))
assert a == 0x123
a = BinInt(a)
assert a == 0x123
def test_display(self):
a = BinInt(12)
... | tests/types/test_int.py | import pytest
from binflakes.types import BinWord, BinInt
class TestBinInt:
def test_construct(self):
a = BinInt(12)
assert a == 12
a = BinInt(BinWord(12, 0x123))
assert a == 0x123
a = BinInt(a)
assert a == 0x123
def test_display(self):
a = BinInt(12)
... | 0.68437 | 0.889481 |
import joblib
import numpy as np
import pandas as pd
model = joblib.load('weights_model.pkl')
print('Lets check your heart!!!!!')
#Application
print('Enter you age?')
age = input()
print('The persons resting blood pressure (mm Hg on admission to the hospital)')
trestbps = input()
print('The persons cholesterol measur... | Application/heart_disease_uci_application.py | import joblib
import numpy as np
import pandas as pd
model = joblib.load('weights_model.pkl')
print('Lets check your heart!!!!!')
#Application
print('Enter you age?')
age = input()
print('The persons resting blood pressure (mm Hg on admission to the hospital)')
trestbps = input()
print('The persons cholesterol measur... | 0.167934 | 0.330498 |
from class_only_design import constants
from class_only_design import util
# This is inserted into decorated classes. Note, __new__ is implicitly converted to a staticmethod
# during class creation. I'm doing so explicitly here so I have a reference I can check later. This
# seems to prevent the implicit transformatio... | class_only_design/meta.py | from class_only_design import constants
from class_only_design import util
# This is inserted into decorated classes. Note, __new__ is implicitly converted to a staticmethod
# during class creation. I'm doing so explicitly here so I have a reference I can check later. This
# seems to prevent the implicit transformatio... | 0.679072 | 0.073763 |
import data
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OrdinalEncoder
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
import feature_selection
from sklearn.pr... | voting_ml/dec_tree_method_example.py | import data
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OrdinalEncoder
from sklearn.model_selection import train_test_split
import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt
import feature_selection
from sklearn.pr... | 0.500732 | 0.53358 |
from core.terraform.resources.aws import iam
from resources.iam.ecs_role import ECSRole
from core.config import Settings
class PolicyDocumentForBaseRole(iam.IAMPolicyDocumentData):
statement = [
{
'actions': ["sts:AssumeRole"],
'principals': {
'type': "Service",
... | installer/resources/iam/base_role.py | from core.terraform.resources.aws import iam
from resources.iam.ecs_role import ECSRole
from core.config import Settings
class PolicyDocumentForBaseRole(iam.IAMPolicyDocumentData):
statement = [
{
'actions': ["sts:AssumeRole"],
'principals': {
'type': "Service",
... | 0.487795 | 0.114666 |
import json
import uuid
from datetime import datetime
from .descriptors import BlobDescriptor
class _IngestionBlobInfo:
def __init__(self, blob, ingestionProperties, deleteSourcesOnSuccess=True, authContext=None):
if not isinstance(blob, BlobDescriptor):
raise TypeError("blob must be of type Bl... | azure-kusto-ingest/azure/kusto/ingest/ingestion_blob_info.py | import json
import uuid
from datetime import datetime
from .descriptors import BlobDescriptor
class _IngestionBlobInfo:
def __init__(self, blob, ingestionProperties, deleteSourcesOnSuccess=True, authContext=None):
if not isinstance(blob, BlobDescriptor):
raise TypeError("blob must be of type Bl... | 0.260484 | 0.053255 |
"""Library for reading values from labjack."""
import sys
import traceback
import multiprocessing
from typing import Dict
from typing import Text
from absl import logging
import u3
class Labjack(object):
"""Interface for the labjack DAQ."""
HIGH_VOLTAGE_CHANNELS = (0, 1, 2, 3)
def __init__(self, config, start... | labjack.py | """Library for reading values from labjack."""
import sys
import traceback
import multiprocessing
from typing import Dict
from typing import Text
from absl import logging
import u3
class Labjack(object):
"""Interface for the labjack DAQ."""
HIGH_VOLTAGE_CHANNELS = (0, 1, 2, 3)
def __init__(self, config, start... | 0.684897 | 0.18385 |
import os
import re
import time
import requests
# 创建一个全局的 requests 的会话
CONNECTION = requests.Session()
# 模拟浏览器
HEADER = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'}
# 更新会话的 user agent
CONNECTION.headers.update(HEADER)
# Windows 文... | icourse.py | import os
import re
import time
import requests
# 创建一个全局的 requests 的会话
CONNECTION = requests.Session()
# 模拟浏览器
HEADER = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.84 Safari/537.36'}
# 更新会话的 user agent
CONNECTION.headers.update(HEADER)
# Windows 文... | 0.142143 | 0.148633 |
import itertools
import os
import configparser
import argparse
import sys
MODALITIES_img = ['T1', 'T1c', 'T2', 'Flair']
cwd = os.getcwd()
#sys.path.append(os.path.join(cwd,'extensions/'))
sys.path.insert(0,os.path.join(os.path.dirname(os.path.abspath(__file__)),'extensions'))
print(sys.path)
def find_exclusion(pa... | inference.py | import itertools
import os
import configparser
import argparse
import sys
MODALITIES_img = ['T1', 'T1c', 'T2', 'Flair']
cwd = os.getcwd()
#sys.path.append(os.path.join(cwd,'extensions/'))
sys.path.insert(0,os.path.join(os.path.dirname(os.path.abspath(__file__)),'extensions'))
print(sys.path)
def find_exclusion(pa... | 0.232659 | 0.112356 |
from __future__ import unicode_literals
import json
import os
from distutils.version import StrictVersion
from nose.plugins.skip import SkipTest
from elasticsearch import (
Elasticsearch
)
ELASTICSEARCH_URL = "localhost"
conn = Elasticsearch(ELASTICSEARCH_URL)
index_name = "foo"
default_doc_type = "my_doc_type"... | tests/helpers.py | from __future__ import unicode_literals
import json
import os
from distutils.version import StrictVersion
from nose.plugins.skip import SkipTest
from elasticsearch import (
Elasticsearch
)
ELASTICSEARCH_URL = "localhost"
conn = Elasticsearch(ELASTICSEARCH_URL)
index_name = "foo"
default_doc_type = "my_doc_type"... | 0.569613 | 0.196421 |
import tkinter
import tkinter.ttk as tk
from tkinter import (DoubleVar, StringVar, LEFT, TOP, RIGHT, W, Y, N, S, Toplevel,
Menu, CENTER)
from view.table import Table
from view.figure import Figure
class SpecSelector:
""" The SpecSelector is the popup window that is used to select spectra to
... | view/specselector.py | import tkinter
import tkinter.ttk as tk
from tkinter import (DoubleVar, StringVar, LEFT, TOP, RIGHT, W, Y, N, S, Toplevel,
Menu, CENTER)
from view.table import Table
from view.figure import Figure
class SpecSelector:
""" The SpecSelector is the popup window that is used to select spectra to
... | 0.562537 | 0.135632 |
import os
import cv2
import numpy as np
class ImageFileName(str):
def __init__(self, fname):
self.fname = fname
def __str__(self):
return self.fname
def __repr__(self):
return self.fname
@property
def jpg(self):
return '{}.jpg'.format(self.fname)
@property
... | data_io.py | import os
import cv2
import numpy as np
class ImageFileName(str):
def __init__(self, fname):
self.fname = fname
def __str__(self):
return self.fname
def __repr__(self):
return self.fname
@property
def jpg(self):
return '{}.jpg'.format(self.fname)
@property
... | 0.610802 | 0.195038 |
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, WebDriverExce... | src/makroClick.py | from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, WebDriverExce... | 0.192463 | 0.040408 |
from http import HTTPStatus
import io
import json
import sys
from aiohttp import hdrs
from aiohttp import web
from aiohttp.web_request import FileField
from aiohttp.web_request import Request
from aiohttp.web_response import Response
from apispec.core import VALID_METHODS_OPENAPI_V2
import marshmallow
import pytest
f... | tests/ext/unit/test_aiohttp.py | from http import HTTPStatus
import io
import json
import sys
from aiohttp import hdrs
from aiohttp import web
from aiohttp.web_request import FileField
from aiohttp.web_request import Request
from aiohttp.web_response import Response
from apispec.core import VALID_METHODS_OPENAPI_V2
import marshmallow
import pytest
f... | 0.427755 | 0.170473 |
import abc
import numpy as np
from scipy import signal
from fsic import util
class Kernel(metaclass=abc.ABCMeta):
"""Abstract class for kernels"""
@abc.abstractmethod
def eval(self, X1, X2):
"""Evalute the kernel on data X1 and X2 """
class KHoPoly(Kernel):
"""Homogeneous polynomial kern... | fsic/kernel.py |
import abc
import numpy as np
from scipy import signal
from fsic import util
class Kernel(metaclass=abc.ABCMeta):
"""Abstract class for kernels"""
@abc.abstractmethod
def eval(self, X1, X2):
"""Evalute the kernel on data X1 and X2 """
class KHoPoly(Kernel):
"""Homogeneous polynomial kern... | 0.873633 | 0.534066 |
from typing import Callable
class Parser:
"""Base class for text parser.
This class provides method for a text parser. This can be used as an instance
or be extended for a custom parser.
Attributes:
buffer: the text buffer to parse.
offset: offset of the current parsing position ... | bin/docs/parser.py | from typing import Callable
class Parser:
"""Base class for text parser.
This class provides method for a text parser. This can be used as an instance
or be extended for a custom parser.
Attributes:
buffer: the text buffer to parse.
offset: offset of the current parsing position ... | 0.952364 | 0.582907 |
import iris
import numpy as np
import pytest
from numpy.testing import assert_allclose
from wildfires.data.datasets import MonthlyDataset, dummy_lat_lon_cube, regrid
from wildfires.utils import get_centres
from .utils import simple_cube
class DummyDataset(MonthlyDataset):
def __init__(self, shape=(10, 360, 720... | tests/test_upsampling.py |
import iris
import numpy as np
import pytest
from numpy.testing import assert_allclose
from wildfires.data.datasets import MonthlyDataset, dummy_lat_lon_cube, regrid
from wildfires.utils import get_centres
from .utils import simple_cube
class DummyDataset(MonthlyDataset):
def __init__(self, shape=(10, 360, 720... | 0.85149 | 0.666361 |
from __future__ import print_function
import boto3
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
sns = boto3.client('sns')
phone_number = '+xxxxxxxxxxx' # change it to your phone number
ses = boto3.client('ses')
email_address = 'xxxxxx.xxxx@xx.x' # change it to your email ad... | smartDoorbell_AWSButton.py | from __future__ import print_function
import boto3
import json
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
sns = boto3.client('sns')
phone_number = '+xxxxxxxxxxx' # change it to your phone number
ses = boto3.client('ses')
email_address = 'xxxxxx.xxxx@xx.x' # change it to your email ad... | 0.400398 | 0.069258 |
from datetime import datetime, timedelta
from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status
from edx_toggles.toggles.testutils import override_waffle_flag
from freezegun import freeze_time
from common.djangoapps.student.tests.factories import UserFactory, Adm... | Part-03-Understanding-Software-Crafting-Your-Own-Tools/models/edx-platform/openedx/core/djangoapps/agreements/tests/test_views.py | from datetime import datetime, timedelta
from django.urls import reverse
from rest_framework.test import APITestCase
from rest_framework import status
from edx_toggles.toggles.testutils import override_waffle_flag
from freezegun import freeze_time
from common.djangoapps.student.tests.factories import UserFactory, Adm... | 0.564459 | 0.243323 |
import matlab.engine
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
import networkx as nx
import mne
def setup_matlab():
eng = matlab.engine.start_matlab()
# add MVGC2 paths
eng.addpath("~/Documents/MATLAB/MVGC2/core")
eng.addpath("~/Documents/MATLAB/MVGC2/gc/var")
... | utils.py | import matlab.engine
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
import networkx as nx
import mne
def setup_matlab():
eng = matlab.engine.start_matlab()
# add MVGC2 paths
eng.addpath("~/Documents/MATLAB/MVGC2/core")
eng.addpath("~/Documents/MATLAB/MVGC2/gc/var")
... | 0.845911 | 0.625867 |
import logging
from collections import defaultdict
from contextlib import ExitStack
import pandas as pd
from xopen import xopen
from igdiscover.table import read_table
from igdiscover.utils import slice_arg
from igdiscover.clonotypes import is_similar_with_junction, CLONOTYPE_COLUMNS
logger = logging.getLogger(__nam... | misc/clonointersect.py | import logging
from collections import defaultdict
from contextlib import ExitStack
import pandas as pd
from xopen import xopen
from igdiscover.table import read_table
from igdiscover.utils import slice_arg
from igdiscover.clonotypes import is_similar_with_junction, CLONOTYPE_COLUMNS
logger = logging.getLogger(__nam... | 0.273574 | 0.234999 |
import glob
import os
import torch
import matplotlib.pyplot as plt
from datetime import datetime
from torchvision.utils import save_image
import constants
import train_utils
import box_utils
import threading
import random
import numpy as np
from adversary import attack_batch
def save_and_upload_image(tensor, save_path... | viz_utils.py | import glob
import os
import torch
import matplotlib.pyplot as plt
from datetime import datetime
from torchvision.utils import save_image
import constants
import train_utils
import box_utils
import threading
import random
import numpy as np
from adversary import attack_batch
def save_and_upload_image(tensor, save_path... | 0.689619 | 0.259151 |
__docformat__ = "numpy"
import functools
import logging
import os
from gamestonk_terminal.rich_config import console
logger = logging.getLogger(__name__)
def log_start_end(func=None, log=None):
"""Wrap function to add a log entry at execution start and end.
Parameters
----------
func : optional
... | gamestonk_terminal/decorators.py | __docformat__ = "numpy"
import functools
import logging
import os
from gamestonk_terminal.rich_config import console
logger = logging.getLogger(__name__)
def log_start_end(func=None, log=None):
"""Wrap function to add a log entry at execution start and end.
Parameters
----------
func : optional
... | 0.550849 | 0.220657 |
from pyomo.environ import *
model = m = ConcreteModel()
m.x2 = Var(within=Reals,bounds=(0,40),initialize=0)
m.x3 = Var(within=Reals,bounds=(0,40),initialize=0)
m.x4 = Var(within=Reals,bounds=(0,40),initialize=0)
m.x5 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x6 = Var(within=Reals,bounds=(0,None),initializ... | models_all_solvable2/syn05m03m.py |
from pyomo.environ import *
model = m = ConcreteModel()
m.x2 = Var(within=Reals,bounds=(0,40),initialize=0)
m.x3 = Var(within=Reals,bounds=(0,40),initialize=0)
m.x4 = Var(within=Reals,bounds=(0,40),initialize=0)
m.x5 = Var(within=Reals,bounds=(0,None),initialize=0)
m.x6 = Var(within=Reals,bounds=(0,None),initializ... | 0.570331 | 0.1929 |
from typing import List
from typing import Union
import pandas as pd # type: ignore
from tnl.ast import Module
from tnl.ast import Transform
from tnl.ast import Test
from tnl.ast import AliasBlock
from tnl.ast import HeaderBlock
from tnl.ast import ValueBlock
from tnl.ast import AliasRule
from tnl.ast import HeaderR... | tnl/vm.py | from typing import List
from typing import Union
import pandas as pd # type: ignore
from tnl.ast import Module
from tnl.ast import Transform
from tnl.ast import Test
from tnl.ast import AliasBlock
from tnl.ast import HeaderBlock
from tnl.ast import ValueBlock
from tnl.ast import AliasRule
from tnl.ast import HeaderR... | 0.430626 | 0.379263 |
import re
import pyperclip
class Output:
def text(self, options, parameters):
for parameter in parameters:
name = parameter['Name'] if options.full or options.list else parameter['Name'].split(
'/')[-1]
if options.list:
print(name)
elif ... | aws_stash/Output.py |
import re
import pyperclip
class Output:
def text(self, options, parameters):
for parameter in parameters:
name = parameter['Name'] if options.full or options.list else parameter['Name'].split(
'/')[-1]
if options.list:
print(name)
elif ... | 0.261331 | 0.194559 |
# =============================================================================
# DOCS
# =============================================================================
"""SIMUS (Sequential Interactive Model for Urban Systems) Method."""
# =============================================================================
... | skcriteria/madm/simus.py |
# =============================================================================
# DOCS
# =============================================================================
"""SIMUS (Sequential Interactive Model for Urban Systems) Method."""
# =============================================================================
... | 0.851398 | 0.49823 |
import wx
import os
import shutil
import webbrowser
from wxGUI.CreditsGUI import CreditsGUI
from PIL import Image
class SettingsGUI(wx.Frame):
def __init__(self):
# setup window
wx.Frame.__init__(self, None, wx.ID_ANY, "Control Panel Settings",
style=wx.SYSTEM_MENU | wx... | wxGUI/SettingsGUI.py | import wx
import os
import shutil
import webbrowser
from wxGUI.CreditsGUI import CreditsGUI
from PIL import Image
class SettingsGUI(wx.Frame):
def __init__(self):
# setup window
wx.Frame.__init__(self, None, wx.ID_ANY, "Control Panel Settings",
style=wx.SYSTEM_MENU | wx... | 0.379378 | 0.060529 |
import argparse
import json
import os
from ansible import constants as C
from ansible.parsing import dataloader
from ansible.parsing import vault
from ansible.parsing.yaml import objects
def _dictify(root):
# Because ansible dataloader returns a lazy mapping (and decodes
# on access, which is not really the... | padre/cmd/decoder.py |
import argparse
import json
import os
from ansible import constants as C
from ansible.parsing import dataloader
from ansible.parsing import vault
from ansible.parsing.yaml import objects
def _dictify(root):
# Because ansible dataloader returns a lazy mapping (and decodes
# on access, which is not really the... | 0.512205 | 0.136148 |
import cgi, json, logging, pprint
from bib_ourl_api_app import settings_app
from bib_ourl_api_app.lib.openurl import bib_from_openurl, bib_from_qdict, openurl_from_bib
from django.test import SimpleTestCase ## TestCase requires db
log = logging.getLogger(__name__)
SimpleTestCase.maxDiff = None
class TestClient( ... | bib_ourl_api_app/tests/test_bib_to_ourl.py |
import cgi, json, logging, pprint
from bib_ourl_api_app import settings_app
from bib_ourl_api_app.lib.openurl import bib_from_openurl, bib_from_qdict, openurl_from_bib
from django.test import SimpleTestCase ## TestCase requires db
log = logging.getLogger(__name__)
SimpleTestCase.maxDiff = None
class TestClient( ... | 0.450118 | 0.184584 |
"""Functions of optimizer"""
from mindspore import Parameter
from mindspore import dtype as mstype
from mindspore import numpy as mnp
from mindspore import ops
from mindspore._checkparam import Validator
from mindspore.common.tensor import Tensor
from mindspore.nn.optim import Optimizer
from mindspore.ops import funct... | research/cv/NFNet/src/tools/AGCSGD.py | """Functions of optimizer"""
from mindspore import Parameter
from mindspore import dtype as mstype
from mindspore import numpy as mnp
from mindspore import ops
from mindspore._checkparam import Validator
from mindspore.common.tensor import Tensor
from mindspore.nn.optim import Optimizer
from mindspore.ops import funct... | 0.91542 | 0.534248 |
import logging
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import (
UserChangeForm as BaseUserChangeForm,
UserCreationForm as BaseUserCreationForm)
from django.core.exceptions import ValidationError
from django.utils.text import slugify
from .models i... | user/forms.py | import logging
from django import forms
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import (
UserChangeForm as BaseUserChangeForm,
UserCreationForm as BaseUserCreationForm)
from django.core.exceptions import ValidationError
from django.utils.text import slugify
from .models i... | 0.378574 | 0.045353 |
from json import dumps as json_to_str, loads as str_to_json
from cafe.engine.models.base import AutoMarshallingModel
from cafe.engine.models.base import AutoMarshallingListModel
class UpdateHost(AutoMarshallingModel):
def __init__(self, hostname=None, profile_id=None, ip_address_v4=None,
ip_addre... | cloudcafe/meniscus/tenant_api/models/host.py | from json import dumps as json_to_str, loads as str_to_json
from cafe.engine.models.base import AutoMarshallingModel
from cafe.engine.models.base import AutoMarshallingListModel
class UpdateHost(AutoMarshallingModel):
def __init__(self, hostname=None, profile_id=None, ip_address_v4=None,
ip_addre... | 0.596903 | 0.065815 |
import json
import re
import pytest
from dpath.util import values as get_in
from fastapi.testclient import TestClient
from mockito import any, mock
import soap_to_rest
from soap_to_rest import app
from soap_to_rest.wsdl_service import WsdlError
from tests.fake_wsdl_server import create_fake_server
client = TestClien... | tests/test_app.py | import json
import re
import pytest
from dpath.util import values as get_in
from fastapi.testclient import TestClient
from mockito import any, mock
import soap_to_rest
from soap_to_rest import app
from soap_to_rest.wsdl_service import WsdlError
from tests.fake_wsdl_server import create_fake_server
client = TestClien... | 0.552298 | 0.330377 |
import pandas as pd
import numpy as np
import re
import dask
from collections import Counter
from typing import Any,List
from spacy.lang.es import STOP_WORDS
import os
import seaborn as sns
import spacy
cm = sns.light_palette("green", as_cmap=True)
sp_nlp=spacy.load('es_core_news_sm')
# Cols=['JUSTIFICACION_AJU... | notebook/pnud_textanalysis/basic.py | import pandas as pd
import numpy as np
import re
import dask
from collections import Counter
from typing import Any,List
from spacy.lang.es import STOP_WORDS
import os
import seaborn as sns
import spacy
cm = sns.light_palette("green", as_cmap=True)
sp_nlp=spacy.load('es_core_news_sm')
# Cols=['JUSTIFICACION_AJU... | 0.253306 | 0.199991 |
from __future__ import print_function
import numpy as np
import unittest
import paddle.fluid as fluid
import paddle.fluid.core as core
import paddle.fluid.layers as layers
import paddle.fluid.framework as framework
from paddle.fluid.executor import Executor
from paddle.fluid.framework import Program, program_guard
fr... | python/paddle/fluid/tests/unittests/test_while_loop_op.py | from __future__ import print_function
import numpy as np
import unittest
import paddle.fluid as fluid
import paddle.fluid.core as core
import paddle.fluid.layers as layers
import paddle.fluid.framework as framework
from paddle.fluid.executor import Executor
from paddle.fluid.framework import Program, program_guard
fr... | 0.6488 | 0.346901 |
from pprint import pprint, pformat
from PyQt5 import Qt, QtGui, QtWidgets, uic, QtCore
import sys
import IAMS.helper as h
import IAMS.runners.runner_helper as rh
import json
from sim_tree import *
from edit_simulation import edit_simulation_window
from run_simulation import run_simulation_window
DEFAULT_SIM_DICT = dic... | gui/main.py | from pprint import pprint, pformat
from PyQt5 import Qt, QtGui, QtWidgets, uic, QtCore
import sys
import IAMS.helper as h
import IAMS.runners.runner_helper as rh
import json
from sim_tree import *
from edit_simulation import edit_simulation_window
from run_simulation import run_simulation_window
DEFAULT_SIM_DICT = dic... | 0.321673 | 0.103567 |
"""Auto-generate a rough portion of absvalue.(h|cpp)."""
import dis
import operator
import pathlib
import types
forward_declaration = """
class {avk_name}Value : public AbstractValue {{
virtual AbstractValueKind kind();
virtual AbstractValue* binary(AbstractSource* selfSources, int op, AbstractValueWithSourc... | Tools/absvalue.py | """Auto-generate a rough portion of absvalue.(h|cpp)."""
import dis
import operator
import pathlib
import types
forward_declaration = """
class {avk_name}Value : public AbstractValue {{
virtual AbstractValueKind kind();
virtual AbstractValue* binary(AbstractSource* selfSources, int op, AbstractValueWithSourc... | 0.714827 | 0.20458 |
import io
import re
import json
import pydoc
import zipfile
import traceback
import argparse
import collections
from datetime import datetime
import urllib.request as request
from itertools import count
Vec3d = collections.namedtuple('Vec3d', 'x,y,z')
Orient3d = collections.namedtuple('Orient3d', 'x,y,z,q')
def pars... | Logs2JSON.py | import io
import re
import json
import pydoc
import zipfile
import traceback
import argparse
import collections
from datetime import datetime
import urllib.request as request
from itertools import count
Vec3d = collections.namedtuple('Vec3d', 'x,y,z')
Orient3d = collections.namedtuple('Orient3d', 'x,y,z,q')
def pars... | 0.261708 | 0.126273 |
import random
import os
import PIL.Image
import numpy as np
from io import BytesIO, StringIO
from discord.ext import commands
from wordcloud import WordCloud, ImageColorGenerator
from mods.cog import Cog
cool = "```xl\n{0}\n```"
code = "```py\n{0}\n```"
class Wc(Cog):
def __init__(self, bot):
super()... | mods/Wc.py | import random
import os
import PIL.Image
import numpy as np
from io import BytesIO, StringIO
from discord.ext import commands
from wordcloud import WordCloud, ImageColorGenerator
from mods.cog import Cog
cool = "```xl\n{0}\n```"
code = "```py\n{0}\n```"
class Wc(Cog):
def __init__(self, bot):
super()... | 0.174973 | 0.189559 |
import pickle
import os.path
alpha="abcdefghijklmnopqrstuvwxyz"
def read_config(date):
with open("./{}-config.enig".format(date),"rb") as file:
rotor_one,rotor_two,rotor_three = pickle.load(file)
return rotor_one , rotor_two , rotor_three
def code_decode_enigma(each):
out_rotor_one= rotor_one... | enigma.py | import pickle
import os.path
alpha="abcdefghijklmnopqrstuvwxyz"
def read_config(date):
with open("./{}-config.enig".format(date),"rb") as file:
rotor_one,rotor_two,rotor_three = pickle.load(file)
return rotor_one , rotor_two , rotor_three
def code_decode_enigma(each):
out_rotor_one= rotor_one... | 0.210401 | 0.230032 |
import abc
from typing import List, Tuple, Any
import numpy as np
class BaseCost(metaclass=abc.ABCMeta):
@classmethod
def __subclasshook__(cls, subclass):
return (hasattr(subclass, 'fit') and
callable(subclass.fit) and
hasattr(subclass, 'error') and
call... | step_detection/base.py | import abc
from typing import List, Tuple, Any
import numpy as np
class BaseCost(metaclass=abc.ABCMeta):
@classmethod
def __subclasshook__(cls, subclass):
return (hasattr(subclass, 'fit') and
callable(subclass.fit) and
hasattr(subclass, 'error') and
call... | 0.855112 | 0.435061 |
#!/usr/bin/env python3
from . import lexer
from . import ast
import contextlib
import functools
class ParseError(Exception):
pass
class ParseFail(Exception):
pass
class TokenState(object):
def __init__(self, data):
self.tokens = [x for x in lexer.lex(data)]
self.pos = 0
def __getite... | src/parser.py | #!/usr/bin/env python3
from . import lexer
from . import ast
import contextlib
import functools
class ParseError(Exception):
pass
class ParseFail(Exception):
pass
class TokenState(object):
def __init__(self, data):
self.tokens = [x for x in lexer.lex(data)]
self.pos = 0
def __getite... | 0.465873 | 0.304455 |
from unittest import TestCase
from monorail_scraper.issue.issue_scraper import IssueScraper
from monorail_scraper.oss_fuzz.oss_fuzz_bug_report_parser import *
from monorail_scraper.oss_fuzz.oss_fuzz_bug_report_parser import _get_project, _get_fuzzing_engine, _get_fuzz_target_binary, \
_get_job_type, _get_platform_... | tests/oss_fuzz/test_oss_fuzz_bug_report_parser.py | from unittest import TestCase
from monorail_scraper.issue.issue_scraper import IssueScraper
from monorail_scraper.oss_fuzz.oss_fuzz_bug_report_parser import *
from monorail_scraper.oss_fuzz.oss_fuzz_bug_report_parser import _get_project, _get_fuzzing_engine, _get_fuzz_target_binary, \
_get_job_type, _get_platform_... | 0.438545 | 0.253855 |
import io
import platform
import os
import sys
import time
import socket
import logging
from functools import partial
class SimulatorError(Exception):
"""
Simulator specific Error
"""
pass
class FMLogger(object):
"""! Yet another logger flavour """
def __init__(self, name, lv=logging.INFO):
... | fm_agent/utils.py | import io
import platform
import os
import sys
import time
import socket
import logging
from functools import partial
class SimulatorError(Exception):
"""
Simulator specific Error
"""
pass
class FMLogger(object):
"""! Yet another logger flavour """
def __init__(self, name, lv=logging.INFO):
... | 0.239527 | 0.04982 |
import sys
sys.path.append("..")
from typing import List, Dict, Any, Optional, Tuple, Set
from collections import defaultdict
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from antNRE.src.word_encoder import WordCharEncoder
from antNRE.modules.seq2seq_encoders.seq2seq_bilstm im... | joint_entrel_gcn/src/joint_model.py | import sys
sys.path.append("..")
from typing import List, Dict, Any, Optional, Tuple, Set
from collections import defaultdict
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from antNRE.src.word_encoder import WordCharEncoder
from antNRE.modules.seq2seq_encoders.seq2seq_bilstm im... | 0.689619 | 0.21628 |
import unittest
from intrepyd.iec611312py.parsest import parse_st
from intrepyd.iec611312py.variable import Variable
from intrepyd.iec611312py.stmtprinter import StmtPrinter
from intrepyd.iec611312py.summarizer import Summarizer
from intrepyd.iec611312py.datatype import Primitive
from intrepyd.iec611312py.expression im... | intrepyd/tests/test_st_summarizer.py | import unittest
from intrepyd.iec611312py.parsest import parse_st
from intrepyd.iec611312py.variable import Variable
from intrepyd.iec611312py.stmtprinter import StmtPrinter
from intrepyd.iec611312py.summarizer import Summarizer
from intrepyd.iec611312py.datatype import Primitive
from intrepyd.iec611312py.expression im... | 0.348645 | 0.399402 |
from __future__ import annotations
import numpy as np
from colour.algebra import spow
from colour.hints import FloatingOrArrayLike, FloatingOrNDArray
from colour.utilities import (
as_float,
domain_range_scale,
from_range_1,
to_domain_1,
)
__author__ = "Colour Developers"
__copyright__ = "Copyright (... | colour/models/rgb/transfer_functions/itur_bt_601.py | from __future__ import annotations
import numpy as np
from colour.algebra import spow
from colour.hints import FloatingOrArrayLike, FloatingOrNDArray
from colour.utilities import (
as_float,
domain_range_scale,
from_range_1,
to_domain_1,
)
__author__ = "Colour Developers"
__copyright__ = "Copyright (... | 0.944061 | 0.343975 |
from objecttype_generator import templates
import pytest
def test_resolver(assert_template):
result = templates.resolver('attr_name')
expected = ('''
def resolve_attr_name(self, info, *args, **kwargs):
pass
''').strip() #get rid of leading and trailing white space
assert_template(result, ex... | test/test_templates.py | from objecttype_generator import templates
import pytest
def test_resolver(assert_template):
result = templates.resolver('attr_name')
expected = ('''
def resolve_attr_name(self, info, *args, **kwargs):
pass
''').strip() #get rid of leading and trailing white space
assert_template(result, ex... | 0.653238 | 0.482734 |
from __future__ import absolute_import, print_function
import logging
from datetime import timedelta
from django.conf import settings
from django.utils import timezone
from sentry.tasks.base import instrumented_task
from sentry.utils.locking import UnableToAcquireLock
logger = logging.getLogger(__name__)
@instrum... | src/sentry/tasks/reprocessing.py | from __future__ import absolute_import, print_function
import logging
from datetime import timedelta
from django.conf import settings
from django.utils import timezone
from sentry.tasks.base import instrumented_task
from sentry.utils.locking import UnableToAcquireLock
logger = logging.getLogger(__name__)
@instrum... | 0.415966 | 0.054299 |
import os
from telemetry.page.actions.gesture_action import GestureAction
from telemetry.page.actions import page_action
class SwipeAction(GestureAction):
def __init__(self, attributes=None):
super(SwipeAction, self).__init__(attributes)
self._SetTimelineMarkerBaseName('SwipeAction::RunAction')
def WillR... | tools/telemetry/telemetry/page/actions/swipe.py | import os
from telemetry.page.actions.gesture_action import GestureAction
from telemetry.page.actions import page_action
class SwipeAction(GestureAction):
def __init__(self, attributes=None):
super(SwipeAction, self).__init__(attributes)
self._SetTimelineMarkerBaseName('SwipeAction::RunAction')
def WillR... | 0.327131 | 0.061115 |
import os
import time
sudo = 'sudo'
def huanyuan():
now_time = time.strftime("%y-%m-%d--%S") # 时间是 年-月-日--秒
os.system(f'{sudo} cp /etc/apt/sources.list /etc/apt/sources.{now_time}.list')
os.system(f'{sudo} cp ./lists/aliyun.list /etc/apt/sources.list')
os.system(f'{sudo} apt-get update')
def ... | 1001install_zsh/main.py |
import os
import time
sudo = 'sudo'
def huanyuan():
now_time = time.strftime("%y-%m-%d--%S") # 时间是 年-月-日--秒
os.system(f'{sudo} cp /etc/apt/sources.list /etc/apt/sources.{now_time}.list')
os.system(f'{sudo} cp ./lists/aliyun.list /etc/apt/sources.list')
os.system(f'{sudo} apt-get update')
def ... | 0.272218 | 0.059647 |
import csv
import cv2
import numpy as np
import os
import sklearn
import math
import matplotlib.pyplot as plt
import random
from scipy import ndimage
# get_data function obtained data from the working directory and returns the training/validation data in an array
def get_data():
# Used to split up data for testing... | model.py | import csv
import cv2
import numpy as np
import os
import sklearn
import math
import matplotlib.pyplot as plt
import random
from scipy import ndimage
# get_data function obtained data from the working directory and returns the training/validation data in an array
def get_data():
# Used to split up data for testing... | 0.748904 | 0.636558 |
from scapy.all import *
from time import *
import cmd
class dhcp_client:
def __init__(self,
mac_address='',
ip_address='',
target_server=''):
self.broadcast_mac_address = 'ff:ff:ff:ff:ff:ff'
self.broadcast_ip_address = '255.255.255.255'
self.null_ip_address = '0.0.0.0'
self.dhcp_server_port ... | Network Security/DHCP/dhcp_client_v3.py | from scapy.all import *
from time import *
import cmd
class dhcp_client:
def __init__(self,
mac_address='',
ip_address='',
target_server=''):
self.broadcast_mac_address = 'ff:ff:ff:ff:ff:ff'
self.broadcast_ip_address = '255.255.255.255'
self.null_ip_address = '0.0.0.0'
self.dhcp_server_port ... | 0.149625 | 0.086555 |
import discord
class ConfirmerSession:
"""Class that interactively paginates
a set of embed using reactions."""
def __init__(self, page, color=discord.Color.green(), footer=''):
"""Confirmer, for confirming things obv duh."""
super().__init__()
self.page = page # the list of embe... | src/ext/confirmer.py | import discord
class ConfirmerSession:
"""Class that interactively paginates
a set of embed using reactions."""
def __init__(self, page, color=discord.Color.green(), footer=''):
"""Confirmer, for confirming things obv duh."""
super().__init__()
self.page = page # the list of embe... | 0.740456 | 0.303758 |
from __future__ import division, absolute_import
import unittest
import bilby
import os
import sys
class TestBBHPriorDict(unittest.TestCase):
def setUp(self):
self.prior_dict = dict()
self.base_directory =\
'/'.join(os.path.dirname(
os.path.abspath(sys.argv[0])).split(... | test/gw_prior_test.py | from __future__ import division, absolute_import
import unittest
import bilby
import os
import sys
class TestBBHPriorDict(unittest.TestCase):
def setUp(self):
self.prior_dict = dict()
self.base_directory =\
'/'.join(os.path.dirname(
os.path.abspath(sys.argv[0])).split(... | 0.606732 | 0.297062 |
from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from category_encoders.basen import BaseNEncoder
from examples.source_data.loader... | examples/grid_search_example.py | from sklearn.model_selection import GridSearchCV
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from category_encoders.basen import BaseNEncoder
from examples.source_data.loader... | 0.716814 | 0.438304 |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class CreateAwsS3Details(object):
"""
AWS S3 bucket details used for source Connection resources with RDS_ORACLE ty... | src/oci/database_migration/models/create_aws_s3_details.py |
from oci.util import formatted_flat_dict, NONE_SENTINEL, value_allowed_none_or_none_sentinel # noqa: F401
from oci.decorators import init_model_state_from_kwargs
@init_model_state_from_kwargs
class CreateAwsS3Details(object):
"""
AWS S3 bucket details used for source Connection resources with RDS_ORACLE ty... | 0.780788 | 0.199444 |
import inspect
import os
from pathlib import Path
class MissingConfigError(Exception):
pass
class Config:
RABBIT_QUEUE = os.getenv('RABBIT_QUEUE', 'Action.Printer')
RABBIT_EXCHANGE = os.getenv('RABBIT_EXCHANGE', 'action-outbound-exchange')
RABBIT_HOST = os.getenv('RABBIT_HOST')
RABBIT_PORT = os.... | config.py | import inspect
import os
from pathlib import Path
class MissingConfigError(Exception):
pass
class Config:
RABBIT_QUEUE = os.getenv('RABBIT_QUEUE', 'Action.Printer')
RABBIT_EXCHANGE = os.getenv('RABBIT_EXCHANGE', 'action-outbound-exchange')
RABBIT_HOST = os.getenv('RABBIT_HOST')
RABBIT_PORT = os.... | 0.202759 | 0.043083 |
import os
import sys
if sys.version_info[0] < 3:
from cPickle \
import \
load, dump, dumps
else:
from pickle \
import \
load, dump, dumps
from yaku._config \
import \
DEFAULT_ENV, BUILD_CONFIG, BUILD_CACHE, CONFIG_CACHE, HOOK_DUMP, \
_OUTPUT
from yak... | bento/private/_yaku/yaku/context.py | import os
import sys
if sys.version_info[0] < 3:
from cPickle \
import \
load, dump, dumps
else:
from pickle \
import \
load, dump, dumps
from yaku._config \
import \
DEFAULT_ENV, BUILD_CONFIG, BUILD_CACHE, CONFIG_CACHE, HOOK_DUMP, \
_OUTPUT
from yak... | 0.247623 | 0.145419 |
import pymunk
def lerp(x1, x2, lerp_amount):
return x1 + ( ( x2 - x1 ) * x1 )
def clamp(value, range):
if not (isinstance(value, (int, float))):
raise ValueError(f"Clamp not supported between type {type(value)} and {type(range[0])}")
if not len(range) == 2:
raise ValueError(f"range argumen... | utils.py | import pymunk
def lerp(x1, x2, lerp_amount):
return x1 + ( ( x2 - x1 ) * x1 )
def clamp(value, range):
if not (isinstance(value, (int, float))):
raise ValueError(f"Clamp not supported between type {type(value)} and {type(range[0])}")
if not len(range) == 2:
raise ValueError(f"range argumen... | 0.484136 | 0.514522 |
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayPcreditLoanApplyQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayPcreditLoanApplyQueryResponse, self).__init__()
self._apply_amt = None
self._apply_date = None
self._ar_no = No... | alipay/aop/api/response/AlipayPcreditLoanApplyQueryResponse.py | import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayPcreditLoanApplyQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayPcreditLoanApplyQueryResponse, self).__init__()
self._apply_amt = None
self._apply_date = None
self._ar_no = No... | 0.609292 | 0.101367 |
from .lims_autosamplerMethod_postgresql_models import *
from SBaaS_base.sbaas_base_query_update import sbaas_base_query_update
from SBaaS_base.sbaas_base_query_drop import sbaas_base_query_drop
from SBaaS_base.sbaas_base_query_initialize import sbaas_base_query_initialize
from SBaaS_base.sbaas_base_query_insert impor... | SBaaS_LIMS/lims_autosamplerMethod_query.py | from .lims_autosamplerMethod_postgresql_models import *
from SBaaS_base.sbaas_base_query_update import sbaas_base_query_update
from SBaaS_base.sbaas_base_query_drop import sbaas_base_query_drop
from SBaaS_base.sbaas_base_query_initialize import sbaas_base_query_initialize
from SBaaS_base.sbaas_base_query_insert impor... | 0.385143 | 0.084795 |
import os,sys
import getpass
import os.path as osp
import numpy as np
from detectron2.config import CfgNode as CN
def add_sparsercnn_config(cfg):
"""
Add config for SparseRCNN.
"""
cfg.MODEL.SparseRCNN = CN()
cfg.MODEL.SparseRCNN.NUM_CLASSES = 80
cfg.MODEL.SparseRCNN.NUM_PROPOSALS = 300
# ... | projects/sparse-rcnn-baseline/config.py | import os,sys
import getpass
import os.path as osp
import numpy as np
from detectron2.config import CfgNode as CN
def add_sparsercnn_config(cfg):
"""
Add config for SparseRCNN.
"""
cfg.MODEL.SparseRCNN = CN()
cfg.MODEL.SparseRCNN.NUM_CLASSES = 80
cfg.MODEL.SparseRCNN.NUM_PROPOSALS = 300
# ... | 0.28887 | 0.080647 |
from functools import partial
from mission.framework.helpers import call_if_function, within_deadband
from mission.framework.task import Task
from shm import kalman
from shm import navigation_desires as desires
from shm.navigation_settings import position_controls
class PositionalControlNeedy(Task):
def on_first_... | mission/framework/movement.py | from functools import partial
from mission.framework.helpers import call_if_function, within_deadband
from mission.framework.task import Task
from shm import kalman
from shm import navigation_desires as desires
from shm.navigation_settings import position_controls
class PositionalControlNeedy(Task):
def on_first_... | 0.805211 | 0.209935 |
from pathlib import Path
from typing import Any
import pytest
import torch
from pytorch_lightning.callbacks import ModelCheckpoint
from InnerEye.Common.output_directories import OutputFolderForTests
from InnerEye.ML.common import (AUTOSAVE_CHECKPOINT_CANDIDATES, LAST_CHECKPOINT_FILE_NAME,
... | Tests/ML/utils/test_model_util.py | from pathlib import Path
from typing import Any
import pytest
import torch
from pytorch_lightning.callbacks import ModelCheckpoint
from InnerEye.Common.output_directories import OutputFolderForTests
from InnerEye.ML.common import (AUTOSAVE_CHECKPOINT_CANDIDATES, LAST_CHECKPOINT_FILE_NAME,
... | 0.865665 | 0.390331 |
import os
import sys
import multiprocessing as mp
import numpy as np
import experiments
import data
import logger as MLogger
import config as MConfig
import utils
def backup_code(config):
result_folder = config.experiment.result_path
if not os.path.isdir(result_folder):
os.makedirs(result_folder)
... | main.py |
import os
import sys
import multiprocessing as mp
import numpy as np
import experiments
import data
import logger as MLogger
import config as MConfig
import utils
def backup_code(config):
result_folder = config.experiment.result_path
if not os.path.isdir(result_folder):
os.makedirs(result_folder)
... | 0.078842 | 0.075075 |
import sys, threading
sys.setrecursionlimit(10**6) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
class TreeOrders:
def read(self):
self.n = int(sys.stdin.readline())
self.key = [0 for i in range(self.n)]
self.left = [0 for i in range(self.n)]
self.... | 02-data-structures-fundamentals/05-week/tree-orders.py | import sys, threading
sys.setrecursionlimit(10**6) # max depth of recursion
threading.stack_size(2**27) # new thread will get stack of such size
class TreeOrders:
def read(self):
self.n = int(sys.stdin.readline())
self.key = [0 for i in range(self.n)]
self.left = [0 for i in range(self.n)]
self.... | 0.421076 | 0.373962 |
from tools.checks import get_empty_result_resource
from tools.getter import get_values
from tools.helpers import parse_date
version = 1.0
def calculate(item):
result = get_empty_result_resource(version)
first_dates = []
first_dates.extend(get_values(item, "planning.milestones.dateModified"))
first_d... | contracting_process/resource_level/coherent/milestones_dates.py | from tools.checks import get_empty_result_resource
from tools.getter import get_values
from tools.helpers import parse_date
version = 1.0
def calculate(item):
result = get_empty_result_resource(version)
first_dates = []
first_dates.extend(get_values(item, "planning.milestones.dateModified"))
first_d... | 0.381104 | 0.297261 |
def read_file() -> str:
with open((__file__.rstrip("code.py")+"input.txt"), 'r', encoding="utf-8") as input_file:
input_data = input_file.read()
return input_data
def parse_input(input_data: str) -> list:
# Parces input string to list of integers
input_list = input_data.strip().split('\n')
... | 2021/3/code.py |
def read_file() -> str:
with open((__file__.rstrip("code.py")+"input.txt"), 'r', encoding="utf-8") as input_file:
input_data = input_file.read()
return input_data
def parse_input(input_data: str) -> list:
# Parces input string to list of integers
input_list = input_data.strip().split('\n')
... | 0.674908 | 0.603786 |
from cola.commands import Command
from cola.context import Context
from cola.core.utils import get_ip
from cola.core.logs import get_logger
class MasterCommand(Command):
def __init__(self):
self.logger = get_logger('cola_master_command')
def add_arguments(self, parser):
ip = get_ip()
... | cola/commands/master.py | from cola.commands import Command
from cola.context import Context
from cola.core.utils import get_ip
from cola.core.logs import get_logger
class MasterCommand(Command):
def __init__(self):
self.logger = get_logger('cola_master_command')
def add_arguments(self, parser):
ip = get_ip()
... | 0.565299 | 0.133359 |
import json
from collections import OrderedDict
class Cube(object):
def __init__(self, dimensions):
super().__init__()
self.dimensions = dimensions
self.cube = {}
self.dictionaries = {}
self._current_cells = {} # a dictionary dim->cell for the current fact
@staticmet... | cubefilter/cubefilter.py | import json
from collections import OrderedDict
class Cube(object):
def __init__(self, dimensions):
super().__init__()
self.dimensions = dimensions
self.cube = {}
self.dictionaries = {}
self._current_cells = {} # a dictionary dim->cell for the current fact
@staticmet... | 0.561455 | 0.363223 |
import sys
import numpy as np
import os
def parse_file_list(name, std_brn, single=True):
if single:
dirs = name.split(',')[0].split('/')
patient, name = dirs[-2], dirs[-1]
for m in ['GD', 'GT', 'FLAIR', 'T1', 'T2']:
if m in name:
return patient + '__' + std_brn +... | src/feature_computation/summarize2tsv_incep_res2.py | import sys
import numpy as np
import os
def parse_file_list(name, std_brn, single=True):
if single:
dirs = name.split(',')[0].split('/')
patient, name = dirs[-2], dirs[-1]
for m in ['GD', 'GT', 'FLAIR', 'T1', 'T2']:
if m in name:
return patient + '__' + std_brn +... | 0.083965 | 0.162513 |
from flask import Flask, render_template, request, flash, redirect, url_for, session, logging
from flask_sqlalchemy import SQLAlchemy
from wtforms import Form, StringField, TextAreaField, PasswordField, validators
from passlib.hash import sha256_crypt
from data import Services, Works
app = Flask(__name__)
ENV = 'dev... | app.py | from flask import Flask, render_template, request, flash, redirect, url_for, session, logging
from flask_sqlalchemy import SQLAlchemy
from wtforms import Form, StringField, TextAreaField, PasswordField, validators
from passlib.hash import sha256_crypt
from data import Services, Works
app = Flask(__name__)
ENV = 'dev... | 0.484624 | 0.067577 |
# pylint: disable=not-callable,multiple-statements,no-member
from sqlalchemy.orm.exc import NoResultFound
from tortuga.db.tortugaDbObjectHandler import TortugaDbObjectHandler
from tortuga.exceptions.adminAlreadyExists import AdminAlreadyExists
from tortuga.exceptions.adminNotFound import AdminNotFound
from tortuga.e... | src/installer/src/tortuga/db/adminsDbHandler.py |
# pylint: disable=not-callable,multiple-statements,no-member
from sqlalchemy.orm.exc import NoResultFound
from tortuga.db.tortugaDbObjectHandler import TortugaDbObjectHandler
from tortuga.exceptions.adminAlreadyExists import AdminAlreadyExists
from tortuga.exceptions.adminNotFound import AdminNotFound
from tortuga.e... | 0.497803 | 0.063395 |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
import os
import pytest # type: ignore
import yaml
from scalyr_agent.__scalyr__ import DEV_INSTALL, PACKAGE_INSTALL
from scalyr_agent import compat
from smoke_tests.tools.compat import Path
# mappi... | smoke_tests/conftest.py |
from __future__ import unicode_literals
from __future__ import print_function
from __future__ import absolute_import
import os
import pytest # type: ignore
import yaml
from scalyr_agent.__scalyr__ import DEV_INSTALL, PACKAGE_INSTALL
from scalyr_agent import compat
from smoke_tests.tools.compat import Path
# mappi... | 0.613121 | 0.142113 |
from collections import OrderedDict
import networkx as nx
import yaml
from .node import Node, OUTPUT_ID
from .task import Task
from .taskSpecSchema import TaskSpecSchema
import warnings
__all__ = ['TaskGraph']
class TaskGraph(object):
''' TaskGraph class that is used to store the graph.
'''
__SETUP_YAM... | gquant/dataframe_flow/taskGraph.py | from collections import OrderedDict
import networkx as nx
import yaml
from .node import Node, OUTPUT_ID
from .task import Task
from .taskSpecSchema import TaskSpecSchema
import warnings
__all__ = ['TaskGraph']
class TaskGraph(object):
''' TaskGraph class that is used to store the graph.
'''
__SETUP_YAM... | 0.677901 | 0.266665 |
import pytz
from dateutil.relativedelta import relativedelta
from calendar import monthrange
from .tools import yearrange
from .dow import DATEUTIL_DOWS,DOWS
class BaseSnap(object):
def __init__(self,timezone):
self.timezone = timezone
def _localized_datetime(self,datetime):
return self.tim... | upoutdf/snapping.py |
import pytz
from dateutil.relativedelta import relativedelta
from calendar import monthrange
from .tools import yearrange
from .dow import DATEUTIL_DOWS,DOWS
class BaseSnap(object):
def __init__(self,timezone):
self.timezone = timezone
def _localized_datetime(self,datetime):
return self.tim... | 0.628521 | 0.485966 |
import logging
import click
import colorama
import crayons
import jinja2
import pendulum
import qtoml
from zeitig import aggregates, events, sourcing, store, utils
log = logging.getLogger(__name__)
TEMPLATE_DEFAULTS_NAME = 'template_defaults.toml'
TEMPLATE_SYNTAX_NAME = 'template_syntax.toml'
TEMPLATE_PATH_NAME = '... | src/zeitig/reporting.py | import logging
import click
import colorama
import crayons
import jinja2
import pendulum
import qtoml
from zeitig import aggregates, events, sourcing, store, utils
log = logging.getLogger(__name__)
TEMPLATE_DEFAULTS_NAME = 'template_defaults.toml'
TEMPLATE_SYNTAX_NAME = 'template_syntax.toml'
TEMPLATE_PATH_NAME = '... | 0.292393 | 0.085824 |
from __future__ import unicode_literals
from ..keys import Keys
from ..enums import InputMode
from ..line import ClipboardData
from .utils import create_handle_decorator
def basic_bindings(registry, cli_ref):
cli = cli_ref()
line = cli_ref().line
system_line = cli_ref().lines['system']
renderer = cl... | prompt_toolkit/key_bindings/basic.py | from __future__ import unicode_literals
from ..keys import Keys
from ..enums import InputMode
from ..line import ClipboardData
from .utils import create_handle_decorator
def basic_bindings(registry, cli_ref):
cli = cli_ref()
line = cli_ref().line
system_line = cli_ref().lines['system']
renderer = cl... | 0.397354 | 0.166641 |
from datetime import date
from django.test import TestCase
from restclients.models.uwnetid import Subscription
from restclients.uwnetid.subscription import get_email_forwarding, \
get_netid_subscriptions, modify_subscription_status, update_subscription
from restclients.exceptions import DataFailureException
from re... | restclients/test/uwnetid/subscription.py | from datetime import date
from django.test import TestCase
from restclients.models.uwnetid import Subscription
from restclients.uwnetid.subscription import get_email_forwarding, \
get_netid_subscriptions, modify_subscription_status, update_subscription
from restclients.exceptions import DataFailureException
from re... | 0.625896 | 0.346182 |
from math import sin, cos, sqrt
from .vefm_271 import *
class form(mesh):
def __init__(self, uresolution, vresolution, uscale, vscale, upart,
vpart, uphase, vphase, utwist, vtwist, xscale, yscale, sform):
mesh.__init__(self)
self.PKHG_parameters = [uresolution, vresolution, uscal... | blender/2.79/scripts/addons/add_mesh_extra_objects/geodesic_domes/forms_271.py | from math import sin, cos, sqrt
from .vefm_271 import *
class form(mesh):
def __init__(self, uresolution, vresolution, uscale, vscale, upart,
vpart, uphase, vphase, utwist, vtwist, xscale, yscale, sform):
mesh.__init__(self)
self.PKHG_parameters = [uresolution, vresolution, uscal... | 0.468061 | 0.242766 |
import numpy as np
import math as mt
import sys
from sklearn.cluster import KMeans
from sklearn import datasets
from sklearn import metrics
class XMeans:
def loglikelihood(self, r, rn, var, m, k):
l1 = - rn / 2.0 * mt.log(2 * mt.pi)
l2 = - rn * m / 2.0 * mt.log(var)
l3 = - (rn - k) / 2.0
... | simple_xmeans.py | import numpy as np
import math as mt
import sys
from sklearn.cluster import KMeans
from sklearn import datasets
from sklearn import metrics
class XMeans:
def loglikelihood(self, r, rn, var, m, k):
l1 = - rn / 2.0 * mt.log(2 * mt.pi)
l2 = - rn * m / 2.0 * mt.log(var)
l3 = - (rn - k) / 2.0
... | 0.473657 | 0.468122 |
import hParser as parser
import sys
from math import floor
class EndException(Exception):
pass
class Interpreter:
def __init__(self, code):
self.code = code
self.toks = list(parser.parse(self.code))
self.stacks = [[], [], [], []]
self.current_stack = 3
self.commands =... | src/interpreter.py | import hParser as parser
import sys
from math import floor
class EndException(Exception):
pass
class Interpreter:
def __init__(self, code):
self.code = code
self.toks = list(parser.parse(self.code))
self.stacks = [[], [], [], []]
self.current_stack = 3
self.commands =... | 0.134833 | 0.220238 |
import sys
from pprint import pprint
from textwrap import dedent
python3 = sys.version_info >= (3,0)
if python3:
from unittest.mock import Mock
from unittest.mock import patch
else:
from mock import Mock
from mock import patch
ats_mock = Mock()
with patch.dict('sys.modules',
{'ats' : ats_mo... | parsergen/pyAtsStandaloneUt/nontabular_parser_xrvr.py | import sys
from pprint import pprint
from textwrap import dedent
python3 = sys.version_info >= (3,0)
if python3:
from unittest.mock import Mock
from unittest.mock import patch
else:
from mock import Mock
from mock import patch
ats_mock = Mock()
with patch.dict('sys.modules',
{'ats' : ats_mo... | 0.32029 | 0.213316 |
__author__ = 'dang'
import unittest
from biokbase.narrative.common.service import get_func_info, get_func_desc
from biokbase.narrative.common import kbtypes
class FakeFunction(object):
"""Float like a class-fly, sting like a function-bee.
"""
def __init__(self, doc):
self.__doc__ = doc
empty_in... | src/biokbase/narrative/common/tests/test_func_info.py | __author__ = 'dang'
import unittest
from biokbase.narrative.common.service import get_func_info, get_func_desc
from biokbase.narrative.common import kbtypes
class FakeFunction(object):
"""Float like a class-fly, sting like a function-bee.
"""
def __init__(self, doc):
self.__doc__ = doc
empty_in... | 0.490724 | 0.254868 |
import base64
import os
from appium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions
import time
desired_caps = {}
desired_caps[... | TestSuite/04_LocationSenario.py | import base64
import os
from appium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions
import time
desired_caps = {}
desired_caps[... | 0.180793 | 0.039085 |
@tasks.loop(seconds=10)
async def update_stats():
print("running")
print(client.guilds)
for guild in client.guilds:
print(guild.name + " " + str(guild.id))
with open("statsoptionlist.json") as f:
print("open statsoptionlist")
data = json.load(f)
print(data... | Discord Bots/Meme6-BOT/testing.py | @tasks.loop(seconds=10)
async def update_stats():
print("running")
print(client.guilds)
for guild in client.guilds:
print(guild.name + " " + str(guild.id))
with open("statsoptionlist.json") as f:
print("open statsoptionlist")
data = json.load(f)
print(data... | 0.134577 | 0.15374 |
from evaluation import ner_evaluate
from huggingface_utils import MODELS, get_special_tokens_from_teacher, get_word_embedding, get_output_state_indices
from preprocessing import generate_sequence_data, get_labels
from tensorflow.keras.layers import Input, Dropout, Dense, Lambda
from tensorflow.keras.mixed_precision... | run_xtreme_distil.py | from evaluation import ner_evaluate
from huggingface_utils import MODELS, get_special_tokens_from_teacher, get_word_embedding, get_output_state_indices
from preprocessing import generate_sequence_data, get_labels
from tensorflow.keras.layers import Input, Dropout, Dense, Lambda
from tensorflow.keras.mixed_precision... | 0.399109 | 0.077274 |
import cv2
from imutils import paths
import os
import face_recognition
import pickle
import dlib
if __name__ == "__main__":
print("Accessing database")
#Opening the image folder where all the photos to train data are stored
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
im... | face_rec_dlib/face_rec.py | import cv2
from imutils import paths
import os
import face_recognition
import pickle
import dlib
if __name__ == "__main__":
print("Accessing database")
#Opening the image folder where all the photos to train data are stored
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
im... | 0.078272 | 0.134208 |
import random
while 1==1:
print("")
print("This is a programme written in python to test your mental maths skills. It was created by SirEdBr, from reading-school-cs-club.")
print("Press Ctrl and the letter 'C' to stop this programme.")
print("What type of test do you want? Type 1 for addition, 2 for subtraction, 3... | MathsTest.py | import random
while 1==1:
print("")
print("This is a programme written in python to test your mental maths skills. It was created by SirEdBr, from reading-school-cs-club.")
print("Press Ctrl and the letter 'C' to stop this programme.")
print("What type of test do you want? Type 1 for addition, 2 for subtraction, 3... | 0.047947 | 0.254694 |
import math
import re
from abc import ABC, abstractmethod
from typing import Callable, Optional, Tuple, Union
import numpy as np
import pymap3d as p3d
from pyproj import CRS, Transformer
from pyfite.utils import DECIMAL_REGEX, static_vars
__pdoc__ = {}
_OPTIONAL_OFFSET = f'(?: ({DECIMAL_REGEX}) ({DECIMAL_REGEX}) ({... | pyfite/coordinates.py | import math
import re
from abc import ABC, abstractmethod
from typing import Callable, Optional, Tuple, Union
import numpy as np
import pymap3d as p3d
from pyproj import CRS, Transformer
from pyfite.utils import DECIMAL_REGEX, static_vars
__pdoc__ = {}
_OPTIONAL_OFFSET = f'(?: ({DECIMAL_REGEX}) ({DECIMAL_REGEX}) ({... | 0.921499 | 0.413063 |
import copy
import numpy as np
from datetime import datetime
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import models
import utils
import networks
def init_model(model_dir, nb_of_classes):
device = torch.device("cuda:0")
resnext50_32x4d = models.resnext50_32x4d(pret... | identification_model.py | import copy
import numpy as np
from datetime import datetime
import torch
import torch.nn as nn
import torch.optim as optim
from torchvision import models
import utils
import networks
def init_model(model_dir, nb_of_classes):
device = torch.device("cuda:0")
resnext50_32x4d = models.resnext50_32x4d(pret... | 0.766119 | 0.369173 |
import argparse
import logging
import os
from pathlib import Path
from typing import List
# pyre-ignore[21]
from utils import run_pysa_integration_test
LOG: logging.Logger = logging.getLogger(__name__)
def main(
run_directory: Path,
filter_issues: bool,
skip_model_verification: bool,
run_from_sourc... | tools/pysa_integration_tests/run.py |
import argparse
import logging
import os
from pathlib import Path
from typing import List
# pyre-ignore[21]
from utils import run_pysa_integration_test
LOG: logging.Logger = logging.getLogger(__name__)
def main(
run_directory: Path,
filter_issues: bool,
skip_model_verification: bool,
run_from_sourc... | 0.674372 | 0.209874 |
import re
from utils import *
with open("input.txt", "r") as file:
data = file.read()
@test(45)
def part1(data):
data = data.strip()
minx, maxx, miny, maxy = map(int, re.findall(r"-?\d+", data))
def compute(x, y):
ycap = 0
class X:
x: int
y: int
start =... | day17/main.py | import re
from utils import *
with open("input.txt", "r") as file:
data = file.read()
@test(45)
def part1(data):
data = data.strip()
minx, maxx, miny, maxy = map(int, re.findall(r"-?\d+", data))
def compute(x, y):
ycap = 0
class X:
x: int
y: int
start =... | 0.380989 | 0.381392 |
import pandas as pd
import argparse
import os
# create argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True,
help="path to dataset")
ap.add_argument("-s", "--split", required = True,
help="name the split train/valid/test")
ap.add_argument("... | align_session_two_all.py | import pandas as pd
import argparse
import os
# create argument parser and parse the arguments
ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required=True,
help="path to dataset")
ap.add_argument("-s", "--split", required = True,
help="name the split train/valid/test")
ap.add_argument("... | 0.241579 | 0.192938 |
from abc import ABC
import requests
import pathlib
import os
import sys
from urllib.parse import urlencode, quote_plus
from requests import HTTPError
from applications.reports.process.reporting_service import ReportingService
from config.settings import (SERVICE_BIC_PASSWORD, SERVICE_BIC_USERNAME,
... | applications/reports/process/__init__.py | from abc import ABC
import requests
import pathlib
import os
import sys
from urllib.parse import urlencode, quote_plus
from requests import HTTPError
from applications.reports.process.reporting_service import ReportingService
from config.settings import (SERVICE_BIC_PASSWORD, SERVICE_BIC_USERNAME,
... | 0.356671 | 0.076339 |
from figcli.test.cli.actions.delete import DeleteAction
from figcli.test.cli.actions.put import PutAction
from figcli.test.cli.config import *
from figcli.test.cli.figgy import FiggyTest
from figcli.test.cli.test_utils import TestUtils
from figcli.utils.utils import *
class DevPromote(FiggyTest):
def __init__(s... | src/figcli/test/cli/dev/promote.py | from figcli.test.cli.actions.delete import DeleteAction
from figcli.test.cli.actions.put import PutAction
from figcli.test.cli.config import *
from figcli.test.cli.figgy import FiggyTest
from figcli.test.cli.test_utils import TestUtils
from figcli.utils.utils import *
class DevPromote(FiggyTest):
def __init__(s... | 0.520009 | 0.181535 |