code
stringlengths
2k
1.04M
repo_path
stringlengths
5
517
parsed_code
stringlengths
0
1.04M
quality_prob
float64
0.02
0.95
learning_prob
float64
0.02
0.93
from bs4 import BeautifulSoup import requests import re from math import ceil all_quotes= {} global_countr= 1 def clean_quote(quote_uncleaned): # remove unwanted characters cleaned_quote1= re.sub('\n','',quote_uncleaned) cleaned_quote2= re.sub(' +',' ',cleaned_quote1) cleaned_quote3= re.sub(' “','',...
scrapper/web_scrapper.py
from bs4 import BeautifulSoup import requests import re from math import ceil all_quotes= {} global_countr= 1 def clean_quote(quote_uncleaned): # remove unwanted characters cleaned_quote1= re.sub('\n','',quote_uncleaned) cleaned_quote2= re.sub(' +',' ',cleaned_quote1) cleaned_quote3= re.sub(' “','',...
0.136637
0.095687
from ..builder import EMBEDDING from torch import nn import torch import math class BertLayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-12): """Construct a layernorm module in the TF style (epsilon inside the square root).""" super(BertLayerNorm, self).__init__() self...
imix/models/embedding/visual_dialog_embedding.py
from ..builder import EMBEDDING from torch import nn import torch import math class BertLayerNorm(nn.Module): def __init__(self, hidden_size, eps=1e-12): """Construct a layernorm module in the TF style (epsilon inside the square root).""" super(BertLayerNorm, self).__init__() self...
0.962365
0.420302
import click from .measurement_composite import MeasurementComposite from .plotter import Plotter @click.command( help='Calculate snow albedo from a sequence of up and down looking ' 'measurements with the ASD field spectrometer.' ) @click.option( '-in', '--input-dir', prompt=True, type=click.Pa...
src/spectro_dp/asd/albedo.py
import click from .measurement_composite import MeasurementComposite from .plotter import Plotter @click.command( help='Calculate snow albedo from a sequence of up and down looking ' 'measurements with the ASD field spectrometer.' ) @click.option( '-in', '--input-dir', prompt=True, type=click.Pa...
0.370225
0.196614
import base64 import re from nbconvert.exporters.html import HTMLExporter from ipython_genutils.ipstruct import Struct import os try: from urllib.request import urlopen # py3 except ImportError: from urllib2 import urlopen class EmbedHTMLExporter(HTMLExporter): """ :mod:`nbconvert` Exporter which e...
jupyter_contrib_nbextensions/nbconvert_support/embedhtml.py
import base64 import re from nbconvert.exporters.html import HTMLExporter from ipython_genutils.ipstruct import Struct import os try: from urllib.request import urlopen # py3 except ImportError: from urllib2 import urlopen class EmbedHTMLExporter(HTMLExporter): """ :mod:`nbconvert` Exporter which e...
0.591133
0.200577
# Práctica 1, <NAME> # <NAME> # Método de Newton para minimizar funciones import numpy as np import sympy as sp import matplotlib.pyplot as plt x, y = sp.symbols('x y') # Función a minimizar f_sym=sp.Lambda((x,y), sp.simplify((x-2)**2+2*(y+2)**2+2*sp.sin(2*sp.pi*x)*sp.sin(2*sp.pi*y))) def f(w): return float(f_sym...
practica1/bonus.py
# Práctica 1, <NAME> # <NAME> # Método de Newton para minimizar funciones import numpy as np import sympy as sp import matplotlib.pyplot as plt x, y = sp.symbols('x y') # Función a minimizar f_sym=sp.Lambda((x,y), sp.simplify((x-2)**2+2*(y+2)**2+2*sp.sin(2*sp.pi*x)*sp.sin(2*sp.pi*y))) def f(w): return float(f_sym...
0.334589
0.588357
import sys _style_dict = { "reset": "\033[0m", "bold": "\033[01m", "disable": '\033[02m', "underline": '\033[04m', "reverse": '\033[07m', "strikethrough": '\033[09m', "invisible": '\033[08m' } _fg_dict = { "black": "\033[30m", "red": "\033[31m", "green": "\033[32m", "orange...
stylization/stylization.py
import sys _style_dict = { "reset": "\033[0m", "bold": "\033[01m", "disable": '\033[02m', "underline": '\033[04m', "reverse": '\033[07m', "strikethrough": '\033[09m', "invisible": '\033[08m' } _fg_dict = { "black": "\033[30m", "red": "\033[31m", "green": "\033[32m", "orange...
0.434941
0.234752
from __init__ import * # no functions # classes class MyList(FindableList): """ MyList() """ def ZZZ(self): """hardcoded/mock instance of the class""" return MyList() instance=ZZZ() """hardcoded/returns an instance of the class""" def ToString(self): """ ToString(self: MyList) -> str """ pa...
release/stubs.min/Wms/RemotingObjects/Settings/SettingObjects.py
from __init__ import * # no functions # classes class MyList(FindableList): """ MyList() """ def ZZZ(self): """hardcoded/mock instance of the class""" return MyList() instance=ZZZ() """hardcoded/returns an instance of the class""" def ToString(self): """ ToString(self: MyList) -> str """ pa...
0.637934
0.113653
import os from codecs import open from setuptools import setup try: from ConfigParser import ConfigParser except ImportError: from configparser import ConfigParser CONF = ConfigParser() HERE = os.path.abspath(os.path.dirname(__file__)) def create_version_py(packagename, version, source_dir='.'): packa...
setup.py
import os from codecs import open from setuptools import setup try: from ConfigParser import ConfigParser except ImportError: from configparser import ConfigParser CONF = ConfigParser() HERE = os.path.abspath(os.path.dirname(__file__)) def create_version_py(packagename, version, source_dir='.'): packa...
0.269422
0.102305
import torch.nn as nn import numpy as np import time import cv2 import os import shutil import tqdm import torch import wandb from utils.metrics import AUC from data.utils import transform from model.models import Stacking, save_dense_backbone, load_dense_backbone, save_resnet_backbone, load_resnet_backbone, Ensemble, ...
model/classifier.py
import torch.nn as nn import numpy as np import time import cv2 import os import shutil import tqdm import torch import wandb from utils.metrics import AUC from data.utils import transform from model.models import Stacking, save_dense_backbone, load_dense_backbone, save_resnet_backbone, load_resnet_backbone, Ensemble, ...
0.84367
0.24659
import pytest from core.test_run import TestRun from iotrace import IotracePlugin from utils.installer import insert_module def test_help(): TestRun.LOGGER.info("Testing cli help") output = TestRun.executor.run('iotrace -H') if output.exit_code != 0: raise Exception("Failed to run executable") ...
tests/security/test_sanity.py
import pytest from core.test_run import TestRun from iotrace import IotracePlugin from utils.installer import insert_module def test_help(): TestRun.LOGGER.info("Testing cli help") output = TestRun.executor.run('iotrace -H') if output.exit_code != 0: raise Exception("Failed to run executable") ...
0.229104
0.356923
import pandas as pd from google.cloud import translate import os import numpy as np import csv os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'/Users/hbae/PycharmProjects/keraconocr/venv/credentials2.json' def test(): df = pd.read_csv('/Users/hbae/PycharmProjects/keraconocr/venv/Final_Data_v2_Cleansing_spell_ch...
collect/csvTotxt.py
import pandas as pd from google.cloud import translate import os import numpy as np import csv os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'/Users/hbae/PycharmProjects/keraconocr/venv/credentials2.json' def test(): df = pd.read_csv('/Users/hbae/PycharmProjects/keraconocr/venv/Final_Data_v2_Cleansing_spell_ch...
0.079859
0.064742
from django.utils.translation import ugettext_lazy as _ from wagtail.core import blocks from wagtail.images.blocks import ImageChooserBlock __all__ = ['LinkBlock', 'Badge', 'Button', 'FAB', 'Breadcrumb', 'Card', 'Collection', 'Icon', 'Preloader'] class LinkStructValue(blocks.StructValue): def url(self): ...
wagtail_materializecss/components.py
from django.utils.translation import ugettext_lazy as _ from wagtail.core import blocks from wagtail.images.blocks import ImageChooserBlock __all__ = ['LinkBlock', 'Badge', 'Button', 'FAB', 'Breadcrumb', 'Card', 'Collection', 'Icon', 'Preloader'] class LinkStructValue(blocks.StructValue): def url(self): ...
0.764452
0.094343
import math import os import random import re import sys def anagrams_in_string(s): ''' Given a string, find the number of pairs of substrings of the string that are anagrams of each other. For example 'mom', the list of all anagrammatic pairs is [m,m], [mo, om]. Anagrams = the letters of one strin...
strings/anagrams_in_string.py
import math import os import random import re import sys def anagrams_in_string(s): ''' Given a string, find the number of pairs of substrings of the string that are anagrams of each other. For example 'mom', the list of all anagrammatic pairs is [m,m], [mo, om]. Anagrams = the letters of one strin...
0.097589
0.415492
from django.contrib.gis.geos import * from django.contrib.gis.measure import D from procyon.starsystemmaker.space_helpers import * from django.contrib.gis.db import models from procyon.starcatalog.models import Star, StarType, StarLuminosityType import json class StarModel(models.Model): """ Additional data a...
procyon/starsystemmaker/models.py
from django.contrib.gis.geos import * from django.contrib.gis.measure import D from procyon.starsystemmaker.space_helpers import * from django.contrib.gis.db import models from procyon.starcatalog.models import Star, StarType, StarLuminosityType import json class StarModel(models.Model): """ Additional data a...
0.417034
0.216136
import pathlib import tempfile from ldp.parse import splits import pytest @pytest.yield_fixture def paths(): """Yields fake (representation, annotation) path pair for testing.""" with tempfile.TemporaryDirectory() as tempdir: root = pathlib.Path(tempdir) representations = root / 'train_reps...
tests/parse/splits_test.py
import pathlib import tempfile from ldp.parse import splits import pytest @pytest.yield_fixture def paths(): """Yields fake (representation, annotation) path pair for testing.""" with tempfile.TemporaryDirectory() as tempdir: root = pathlib.Path(tempdir) representations = root / 'train_reps...
0.770119
0.731754
__author__ = '<NAME>' __email__ = '<EMAIL>' import numpy as np import scipy.signal as sig from skimage.filters import gaussian from tv_fista import deconvolve_fista def deconvolve_tv(image, psf, noise_level=0.05, min_value=0, max_value=1, intermediate_it=30, it=40, intermediate_eps=1e-3, eps=1e-5):...
improve/easy_deconvolve.py
__author__ = '<NAME>' __email__ = '<EMAIL>' import numpy as np import scipy.signal as sig from skimage.filters import gaussian from tv_fista import deconvolve_fista def deconvolve_tv(image, psf, noise_level=0.05, min_value=0, max_value=1, intermediate_it=30, it=40, intermediate_eps=1e-3, eps=1e-5):...
0.891964
0.716913
import time from typing import Any, Dict, Optional from airflow.exceptions import AirflowException from airflow.providers.google.cloud.hooks.dataproc import DataprocHook from airflow.providers.google.cloud.links.dataproc import ( DATAPROC_CLUSTER_LINK, DataprocLink, ) from airflow.providers.google.cloud.operat...
astronomer/providers/google/cloud/operators/dataproc.py
import time from typing import Any, Dict, Optional from airflow.exceptions import AirflowException from airflow.providers.google.cloud.hooks.dataproc import DataprocHook from airflow.providers.google.cloud.links.dataproc import ( DATAPROC_CLUSTER_LINK, DataprocLink, ) from airflow.providers.google.cloud.operat...
0.887613
0.452899
import os from typing import List, Tuple import random import string from collections import OrderedDict import pandas as pd from engine.utils.preprocessing import Preprocessor from engine.utils.preprocess_utils import delete_overlapping_tuples from engine.preprocess.preprocess_superclass import Preprocess class Rep...
engine/preprocess/replace_longforms.py
import os from typing import List, Tuple import random import string from collections import OrderedDict import pandas as pd from engine.utils.preprocessing import Preprocessor from engine.utils.preprocess_utils import delete_overlapping_tuples from engine.preprocess.preprocess_superclass import Preprocess class Rep...
0.801431
0.327037
from bs4 import BeautifulSoup import requests from typing import List, Dict import json import time def get_all_whiskys(urls: List[str], headers: Dict[str, str]) -> Dict[str, str]: """Function to scrape name and further details link from each row of whisky from every page on each url in a list of urls from master...
web-scraper/src/scraping_functions.py
from bs4 import BeautifulSoup import requests from typing import List, Dict import json import time def get_all_whiskys(urls: List[str], headers: Dict[str, str]) -> Dict[str, str]: """Function to scrape name and further details link from each row of whisky from every page on each url in a list of urls from master...
0.721351
0.289557
import numpy as np from .network import BooleanNetwork class ECA(BooleanNetwork): """ ECA is a class to represent elementary cellular automaton rules. Each ECA contains an 8-bit integral member variable ``code`` representing the Wolfram code for the ECA rule and a set of boundary conditions which is ...
neet/boolean/eca.py
import numpy as np from .network import BooleanNetwork class ECA(BooleanNetwork): """ ECA is a class to represent elementary cellular automaton rules. Each ECA contains an 8-bit integral member variable ``code`` representing the Wolfram code for the ECA rule and a set of boundary conditions which is ...
0.887507
0.517266
import torch from objective.base import Objective from utils import assert_true class Ridge(Objective): def _validate_inputs(self, w, x, y): assert_true(w.dim() == 2, "Input w should be 2D") assert_true(w.size(1) == 1, "Ridge regression can only perform reg...
optimization/prac1/objective/ridge.py
import torch from objective.base import Objective from utils import assert_true class Ridge(Objective): def _validate_inputs(self, w, x, y): assert_true(w.dim() == 2, "Input w should be 2D") assert_true(w.size(1) == 1, "Ridge regression can only perform reg...
0.399343
0.704732
"""tasks.py: Django data_replication""" import logging from celery import shared_task from .backends.base import ImproperlyConfiguredException from .backends.mongo import MongoRequest from .backends.splunk import SplunkRequest __author__ = '<NAME>' __date__ = '9/26/17 10:12' __copyright__ = 'Copyright 2017 IC Manag...
data_replication/tasks.py
"""tasks.py: Django data_replication""" import logging from celery import shared_task from .backends.base import ImproperlyConfiguredException from .backends.mongo import MongoRequest from .backends.splunk import SplunkRequest __author__ = '<NAME>' __date__ = '9/26/17 10:12' __copyright__ = 'Copyright 2017 IC Manag...
0.468791
0.224459
[ { 'date': '2019-01-01', 'description': 'Újév', 'locale': 'hu-HU', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '2019-03-15', 'description': 'Az 1848-as forradalom ünnepe', 'locale': 'hu-HU', 'notes': '', 'regio...
tests/snapshots/snap_test_holidata/test_holidata_produces_holidays_for_locale_and_year[hu_HU-2019] 1.py
[ { 'date': '2019-01-01', 'description': 'Újév', 'locale': 'hu-HU', 'notes': '', 'region': '', 'type': 'NF' }, { 'date': '2019-03-15', 'description': 'Az 1848-as forradalom ünnepe', 'locale': 'hu-HU', 'notes': '', 'regio...
0.352313
0.101456
import logging class CommandBase: ''' A base class providing functionality common to all commands. ''' def __init__(self, context): self._logger = logging.getLogger(__class__.__name__) self._context = context @property def context(self): ''' The command context...
tasks/commands/commandbase.py
import logging class CommandBase: ''' A base class providing functionality common to all commands. ''' def __init__(self, context): self._logger = logging.getLogger(__class__.__name__) self._context = context @property def context(self): ''' The command context...
0.742515
0.121764
import math import itertools import numpy as np from pytest import raises, approx from pystrafe import motion def test_strafe_K(): with raises(ZeroDivisionError): motion.strafe_K(0, 0, 0, 0) assert motion.strafe_K(30, 0.001, 320, 0) == 0.0 assert motion.strafe_K(30, 0.01, 320, 10) == approx(90000) ...
pystrafe/tests/test_motion.py
import math import itertools import numpy as np from pytest import raises, approx from pystrafe import motion def test_strafe_K(): with raises(ZeroDivisionError): motion.strafe_K(0, 0, 0, 0) assert motion.strafe_K(30, 0.001, 320, 0) == 0.0 assert motion.strafe_K(30, 0.01, 320, 10) == approx(90000) ...
0.653127
0.777975
from flask import Flask, render_template, request, jsonify from goodreads_search import search_book, get_book_isbn from review_parser import scrape_reviews from youtube_search import get_video_ids from pprint import pprint from time import time app = Flask(__name__) @app.route("/") def index(): return render_tem...
app.py
from flask import Flask, render_template, request, jsonify from goodreads_search import search_book, get_book_isbn from review_parser import scrape_reviews from youtube_search import get_video_ids from pprint import pprint from time import time app = Flask(__name__) @app.route("/") def index(): return render_tem...
0.274157
0.124107
import asyncio import logging import multiprocessing import os import queue from gabriel_protocol import gabriel_pb2 from gabriel_server import cognitive_engine from gabriel_server.websocket_server import WebsocketServer _NUM_BYTES_FOR_SIZE = 4 _BYTEORDER = 'big' logger = logging.getLogger(__name__) def run(engin...
src/gabriel_server/local_engine.py
import asyncio import logging import multiprocessing import os import queue from gabriel_protocol import gabriel_pb2 from gabriel_server import cognitive_engine from gabriel_server.websocket_server import WebsocketServer _NUM_BYTES_FOR_SIZE = 4 _BYTEORDER = 'big' logger = logging.getLogger(__name__) def run(engin...
0.390941
0.080647
from django.db import models from .models import UserProfile, Comment class Flagged(models.Model): flagged_by = models.ForeignKey(UserProfile) # offensive, violent/threat, against the rules, bullying reason_description = models.CharField() flag_count = models.IntegerField() flagged_to_comment = mo...
flagged.py
from django.db import models from .models import UserProfile, Comment class Flagged(models.Model): flagged_by = models.ForeignKey(UserProfile) # offensive, violent/threat, against the rules, bullying reason_description = models.CharField() flag_count = models.IntegerField() flagged_to_comment = mo...
0.418222
0.145085
import torch from torch.autograd import Variable import numpy as np from collections import defaultdict from vocab import Vocab import os def read_corpus(file_path, pad_bos_eos=False): data = [] for line in open(file_path): sent = line.strip().split(' ') # only append <s> and </s> to the target...
generation/hncm_dataloader.py
import torch from torch.autograd import Variable import numpy as np from collections import defaultdict from vocab import Vocab import os def read_corpus(file_path, pad_bos_eos=False): data = [] for line in open(file_path): sent = line.strip().split(' ') # only append <s> and </s> to the target...
0.490968
0.28354
import random from datacenter.models import Chastisement from datacenter.models import Commendation from datacenter.models import Lesson from datacenter.models import Mark from datacenter.models import Schoolkid def get_schoolkid_object(child_name): child = Schoolkid.objects.get(full_name__contains=child_name) ...
scripts.py
import random from datacenter.models import Chastisement from datacenter.models import Commendation from datacenter.models import Lesson from datacenter.models import Mark from datacenter.models import Schoolkid def get_schoolkid_object(child_name): child = Schoolkid.objects.get(full_name__contains=child_name) ...
0.241042
0.173778
class GrowthContent: introduction = ( "There are many ways to measure the growth of COVID-19 cases and " "deaths in countries around the world. For example, one could simply " "measure an increase in the absolute number of cases or deaths in a " "country over a period of time. Measur...
global_covid_tracker/content/growth_content.py
class GrowthContent: introduction = ( "There are many ways to measure the growth of COVID-19 cases and " "deaths in countries around the world. For example, one could simply " "measure an increase in the absolute number of cases or deaths in a " "country over a period of time. Measur...
0.720172
0.969179
import os import ssl import socketpool import wifi import golioth.golioth as Golioth # Get wifi details and more from a secrets.py file try: from secrets import secrets except ImportError: print("WiFi secrets are kept in secrets.py, please add them there!") raise def connected(client): print("Connec...
examples/native_networking/dfu/code.py
import os import ssl import socketpool import wifi import golioth.golioth as Golioth # Get wifi details and more from a secrets.py file try: from secrets import secrets except ImportError: print("WiFi secrets are kept in secrets.py, please add them there!") raise def connected(client): print("Connec...
0.114752
0.052765
# Futures from __future__ import absolute_import # Built-in modules import abc # Third party modules import six # Own modules from microprobe.exceptions import MicroprobeArchitectureDefinitionError from microprobe.utils.imp import find_subclasses from microprobe.utils.logger import get_logger # Constants LOG = get...
src/microprobe/target/isa/comparator.py
# Futures from __future__ import absolute_import # Built-in modules import abc # Third party modules import six # Own modules from microprobe.exceptions import MicroprobeArchitectureDefinitionError from microprobe.utils.imp import find_subclasses from microprobe.utils.logger import get_logger # Constants LOG = get...
0.723895
0.311728
import json import logging import os import quopri import re import smtplib import subprocess import sys import threading from base64 import b64decode from email import policy from email.header import Header, decode_header from email.mime.text import MIMEText from email.parser import BytesParser, BytesHeaderParser fr...
api.py
import json import logging import os import quopri import re import smtplib import subprocess import sys import threading from base64 import b64decode from email import policy from email.header import Header, decode_header from email.mime.text import MIMEText from email.parser import BytesParser, BytesHeaderParser fr...
0.232659
0.091544
import argparse import os import resource import subprocess import time from urllib.parse import urljoin from bs4 import BeautifulSoup as bs from PyPDF2 import PdfFileReader, PdfFileWriter import requests # Use html5lib because html.parser makes a mess of malformed HTML PARSER = 'html5lib' def remove_wayback_header...
android_scraper_2018.py
import argparse import os import resource import subprocess import time from urllib.parse import urljoin from bs4 import BeautifulSoup as bs from PyPDF2 import PdfFileReader, PdfFileWriter import requests # Use html5lib because html.parser makes a mess of malformed HTML PARSER = 'html5lib' def remove_wayback_header...
0.449151
0.112137
from django.db import transaction from rest_framework import status from rest_framework.response import Response from json_api.exceptions import MethodNotAllowed class RetrieveRelationshipMixin(object): def retrieve_relationship(self, request, pk, relname, *args, **kwargs): rel = self.get_relationship(rel...
json_api/mixins/relationships.py
from django.db import transaction from rest_framework import status from rest_framework.response import Response from json_api.exceptions import MethodNotAllowed class RetrieveRelationshipMixin(object): def retrieve_relationship(self, request, pk, relname, *args, **kwargs): rel = self.get_relationship(rel...
0.588416
0.089097
import gpu_util import os os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_util.pick_gpu_lowest_memory()) import matplotlib matplotlib.use('Agg') from matplotlib import pyplot import sys import skimage.measure import numpy import numpy as np import skimage.io from skimage.morphology import disk, dilation import skimage.fea...
metric_evaluation.py
import gpu_util import os os.environ["CUDA_VISIBLE_DEVICES"] = str(gpu_util.pick_gpu_lowest_memory()) import matplotlib matplotlib.use('Agg') from matplotlib import pyplot import sys import skimage.measure import numpy import numpy as np import skimage.io from skimage.morphology import disk, dilation import skimage.fea...
0.201577
0.288663
import numpy as np import tensorflow as tf import bidirectional_autoencoder as bd import data_utils as du # 5719 total samples # 5147 training samples # 321 batches of size 16 # 10 epochs more or less #STEPS = 3250 STEPS = 10000 #batch_size = bd.batch_size starting_learning_rate = 1e-2 decay_rate = 5e-1 decay_...
Seq2Seq-gait-analysis/conv_classifier_eval.py
import numpy as np import tensorflow as tf import bidirectional_autoencoder as bd import data_utils as du # 5719 total samples # 5147 training samples # 321 batches of size 16 # 10 epochs more or less #STEPS = 3250 STEPS = 10000 #batch_size = bd.batch_size starting_learning_rate = 1e-2 decay_rate = 5e-1 decay_...
0.601711
0.517937
from __future__ import absolute_import from plaidcloud.rpc import utc from six import text_type __author__ = '<NAME>' __maintainer__ = '<NAME> <<EMAIL>>' __copyright__ = '© Copyright 2017, Tartan Solutions, Inc' __license__ = 'Apache 2.0' def user_auth(*args, **kwargs): auth = Auth() auth.user(*args, **kwar...
plaidcloud/rpc/remote/auth.py
from __future__ import absolute_import from plaidcloud.rpc import utc from six import text_type __author__ = '<NAME>' __maintainer__ = '<NAME> <<EMAIL>>' __copyright__ = '© Copyright 2017, Tartan Solutions, Inc' __license__ = 'Apache 2.0' def user_auth(*args, **kwargs): auth = Auth() auth.user(*args, **kwar...
0.794624
0.075551
# In[4]: import os import numpy as np import pickle import quandl import pandas as pd import plotly.offline as py import plotly.graph_objs as go py.init_notebook_mode(connected=True) # In[5]: quandl.ApiConfig.api_key = 'tWWv7RoNKzyaxKKRnc8d' # In[10]: def get_quandl_data(quandl_code): cache_path = '{}.pkl'...
Bitcoin Cryptocurrency Price Visualization.py
# In[4]: import os import numpy as np import pickle import quandl import pandas as pd import plotly.offline as py import plotly.graph_objs as go py.init_notebook_mode(connected=True) # In[5]: quandl.ApiConfig.api_key = 'tWWv7RoNKzyaxKKRnc8d' # In[10]: def get_quandl_data(quandl_code): cache_path = '{}.pkl'...
0.392337
0.267617
import os import fnmatch import fileinput import json import re import urllib.request def getTestsCount(): testDir = "tests" testFilePattern = r'test_a*.py' count = 0 for file in fnmatch.filter(os.listdir(testDir), testFilePattern): if file == 'test_a0000blank.py': continue testFile = os.path.j...
progress.py
import os import fnmatch import fileinput import json import re import urllib.request def getTestsCount(): testDir = "tests" testFilePattern = r'test_a*.py' count = 0 for file in fnmatch.filter(os.listdir(testDir), testFilePattern): if file == 'test_a0000blank.py': continue testFile = os.path.j...
0.443118
0.113138
import uuid from aiohttp import web from aiohttp_session import get_session from twython import Twython from cursed.parrot import db async def twitter_authorize(request): app = request.app auth = app['twitter'].get_authentication_tokens( callback_url=app['settings']['twitter']['callback_url'] ) ...
src/cursed/parrot/twitter.py
import uuid from aiohttp import web from aiohttp_session import get_session from twython import Twython from cursed.parrot import db async def twitter_authorize(request): app = request.app auth = app['twitter'].get_authentication_tokens( callback_url=app['settings']['twitter']['callback_url'] ) ...
0.264263
0.047404
from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, redirect, render from django.contrib.auth.models import User from django.views import View from .models import BankAccount, Transaction from .forms import BankAccountForm, RegistrationForm, TransactionForm from django.core.pagi...
bank_account_app/bank_account/views.py
from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, redirect, render from django.contrib.auth.models import User from django.views import View from .models import BankAccount, Transaction from .forms import BankAccountForm, RegistrationForm, TransactionForm from django.core.pagi...
0.434221
0.076511
import argparse from urdf_parser_py.urdf import URDF import yaml import sys def findJointByName(robot, name): for j in robot.joints: if j.name == name: return j return None def jointDiff(original, new): """ only take origin into account """ if hasattr(original, "origin"...
euscollada/scripts/urdf_patch.py
import argparse from urdf_parser_py.urdf import URDF import yaml import sys def findJointByName(robot, name): for j in robot.joints: if j.name == name: return j return None def jointDiff(original, new): """ only take origin into account """ if hasattr(original, "origin"...
0.26588
0.395659
from policies import TabularPolicy, DQNPolicy, IntentionPolicy, IntentionAblatedPolicy from tabular_class import QTabularRLModel, MCTabularRLModel from deep_class import DQNModel, IntentionModel, IntentionAblatedModel import argparse import numpy as np import gym from wrappers import DiscretizedObservationWrapper, Tax...
train_taxi.py
from policies import TabularPolicy, DQNPolicy, IntentionPolicy, IntentionAblatedPolicy from tabular_class import QTabularRLModel, MCTabularRLModel from deep_class import DQNModel, IntentionModel, IntentionAblatedModel import argparse import numpy as np import gym from wrappers import DiscretizedObservationWrapper, Tax...
0.589362
0.262975
import unittest #importing the unittest module from credential import Credential #importing the credential class class TestCredential(unittest.TestCase): ''' Test case defines test cases for the credential class behaivors ''' def setUp(self): ''' set up to run before each test case ...
credential_test.py
import unittest #importing the unittest module from credential import Credential #importing the credential class class TestCredential(unittest.TestCase): ''' Test case defines test cases for the credential class behaivors ''' def setUp(self): ''' set up to run before each test case ...
0.395951
0.374162
from matplotlib import collections import json import os import copy import torch from torchvision import transforms import numpy as np from tqdm import tqdm from random import sample import torchaudio import logging import collections from glob import glob import sys import albumentations sys.path.insert(0, '.') # n...
specvqgan/data/greatesthit.py
from matplotlib import collections import json import os import copy import torch from torchvision import transforms import numpy as np from tqdm import tqdm from random import sample import torchaudio import logging import collections from glob import glob import sys import albumentations sys.path.insert(0, '.') # n...
0.475362
0.111241
import re class classification: #constructor is a single number or a range def __init__(self, id): self.id = id #self.id = self.id.replace('O','0') def is_sane(self): sane = True if not reduce(lambda a, b: a and b, map(lambda c: c in '0123456789.', s...
pyddc.py
import re class classification: #constructor is a single number or a range def __init__(self, id): self.id = id #self.id = self.id.replace('O','0') def is_sane(self): sane = True if not reduce(lambda a, b: a and b, map(lambda c: c in '0123456789.', s...
0.372619
0.413892
import csv import json import xlrd import argparse """ ## Usage python mic_lglist_to_json.py mic-lglist.xls -x ## Input - 総務省トップ > 政策 > 地方行財政 > 電子自治体 > 全国地方公共団体コード https://www.soumu.go.jp/denshijiti/code.html - 都道府県コード及び市区町村コード」(令和元年5月1日現在) curl -o mic-lglist.xls https://www.soumu.go.jp/main_content/0006181...
tools/mic_lglist_to_json.py
団体コード 都道府県名 市町村名
0.181336
0.457682
from django.shortcuts import render, Http404, get_object_or_404, redirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.http import HttpResponseRedirect from django.views import View from django.contrib.auth.models import User from .forms import CommentForm from .models impo...
louis/webdev/myblog/blog/views.py
from django.shortcuts import render, Http404, get_object_or_404, redirect from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.http import HttpResponseRedirect from django.views import View from django.contrib.auth.models import User from .forms import CommentForm from .models impo...
0.440951
0.062445
import os from abc import ABC from enum import Enum from typing import List from xtermcolor import colorize class Score(Enum): BLANK = 0 INCORRECT = 1 INCORRECT_POSITION = 2 CORRECT = 3 class Renderer(ABC): """ Abstract class that contains rendering logic. Subclass this to a concrete cl...
renderer.py
import os from abc import ABC from enum import Enum from typing import List from xtermcolor import colorize class Score(Enum): BLANK = 0 INCORRECT = 1 INCORRECT_POSITION = 2 CORRECT = 3 class Renderer(ABC): """ Abstract class that contains rendering logic. Subclass this to a concrete cl...
0.775435
0.290981
from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from openapi_server.models.base_model_ import Model from openapi_server import util class UserCreateRequest(Model): """NOTE: This class is auto generated by OpenAPI Generator (ht...
apps/api/openapi_server/models/user_create_request.py
from __future__ import absolute_import from datetime import date, datetime # noqa: F401 from typing import List, Dict # noqa: F401 from openapi_server.models.base_model_ import Model from openapi_server import util class UserCreateRequest(Model): """NOTE: This class is auto generated by OpenAPI Generator (ht...
0.755457
0.068444
import numpy as np import matplotlib.pyplot as plt import random import detector as dct class Particle: def __init__(self,id,pos,mu,energy): self.id = id self.__x = pos[0] self.__y = pos[1] self.__z = pos[2] self.__mu_x = mu[0] self.__mu_y = mu[1] self._...
src/particle.py
import numpy as np import matplotlib.pyplot as plt import random import detector as dct class Particle: def __init__(self,id,pos,mu,energy): self.id = id self.__x = pos[0] self.__y = pos[1] self.__z = pos[2] self.__mu_x = mu[0] self.__mu_y = mu[1] self._...
0.644449
0.431165
import logging import typing import uuid from forml import flow, io, project from forml.conf.parsed import provider as provcfg from forml.io import dsl, layout from forml.runtime import facility from forml.testing import _spec LOGGER = logging.getLogger(__name__) class DataSet(dsl.Schema): """Testing schema. ...
forml/testing/_facility.py
import logging import typing import uuid from forml import flow, io, project from forml.conf.parsed import provider as provcfg from forml.io import dsl, layout from forml.runtime import facility from forml.testing import _spec LOGGER = logging.getLogger(__name__) class DataSet(dsl.Schema): """Testing schema. ...
0.863521
0.414425
# Cookie import requests import pandas as pd from bs4 import BeautifulSoup headers = { 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36', 'Cookie':'JSESSIONID=68E5E9087DD3404B3502CD3077A8CDB4', } url = 'http://172.16.17.32...
main.py
# Cookie import requests import pandas as pd from bs4 import BeautifulSoup headers = { 'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36', 'Cookie':'JSESSIONID=68E5E9087DD3404B3502CD3077A8CDB4', } url = 'http://172.16.17.32...
0.053169
0.285364
import numpy as np import cv2 #MEAN_STD = [[0.29010095242892997, 0.32808144844279574, 0.28696394422942517], [0.1829540508368939, 0.18656561047509476, 0.18447508988480435]] MEAN_STD = np.array([[0.5, 0.5, 0.5], [1, 1, 1]], dtype=np.float32) MAX_DEPTH = 10 ## Global color mapping class ColorPalette: def __init__(se...
pytorch/utils.py
import numpy as np import cv2 #MEAN_STD = [[0.29010095242892997, 0.32808144844279574, 0.28696394422942517], [0.1829540508368939, 0.18656561047509476, 0.18447508988480435]] MEAN_STD = np.array([[0.5, 0.5, 0.5], [1, 1, 1]], dtype=np.float32) MAX_DEPTH = 10 ## Global color mapping class ColorPalette: def __init__(se...
0.510496
0.382545
import asyncio import unittest from collections import deque from typing import List, Optional from unittest.mock import ANY, MagicMock, Mock import asynctest # type: ignore from hathorlib.client import BlockTemplate, HathorClient import txstratum.time from txstratum.jobs import JobStatus, TxJob from txstratum.manag...
tests/test_manager.py
import asyncio import unittest from collections import deque from typing import List, Optional from unittest.mock import ANY, MagicMock, Mock import asynctest # type: ignore from hathorlib.client import BlockTemplate, HathorClient import txstratum.time from txstratum.jobs import JobStatus, TxJob from txstratum.manag...
0.620047
0.191895
import logging import socket import urllib.request from urllib.error import HTTPError, URLError from urllib.parse import urlparse, parse_qs from bs4 import BeautifulSoup from django.utils.translation import gettext from pypeach_django.app_config import AppConfig """ Scrapy関連の共通処理を定義する """ class ScrapyHelper: ...
backend/chart/application/helper/scrapy.py
import logging import socket import urllib.request from urllib.error import HTTPError, URLError from urllib.parse import urlparse, parse_qs from bs4 import BeautifulSoup from django.utils.translation import gettext from pypeach_django.app_config import AppConfig """ Scrapy関連の共通処理を定義する """ class ScrapyHelper: ...
0.226527
0.058373
from __future__ import absolute_import from tests import util _EXPECT_NAME = 'publishing.withsphinx' _EXPECT_VERSION = '0.0.1' _EXPECT_DATE = '2016-10-11' _EXPECT_AUTHOR = '<NAME>' _EXPECT_AUTHOR_EMAIL = '<EMAIL>' _EXPECT_SPHINX_EXTENSION_METADATA = { 'version': _EXPECT_VERSION, 'parallel_read_safe': True,...
tests/unit/test_meta_data.py
from __future__ import absolute_import from tests import util _EXPECT_NAME = 'publishing.withsphinx' _EXPECT_VERSION = '0.0.1' _EXPECT_DATE = '2016-10-11' _EXPECT_AUTHOR = '<NAME>' _EXPECT_AUTHOR_EMAIL = '<EMAIL>' _EXPECT_SPHINX_EXTENSION_METADATA = { 'version': _EXPECT_VERSION, 'parallel_read_safe': True,...
0.609757
0.377369
from django.http.response import Http404, HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.urls import reverse from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from dja...
smart_cctv/users/views.py
from django.http.response import Http404, HttpResponse, HttpResponseRedirect, JsonResponse from django.shortcuts import render from django.contrib.auth.decorators import login_required from django.urls import reverse from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from dja...
0.427277
0.05526
from nltk.corpus import wordnet as wn from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem.wordnet import WordNetLemmatizer import nltk def get_words_with_all_langs(synset_id): langs = sorted(wn.langs()) list_lang = [] list_useful_lang=[] for lang in langs: i...
src/semantickit/lang/wordnet.py
from nltk.corpus import wordnet as wn from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from nltk.stem.wordnet import WordNetLemmatizer import nltk def get_words_with_all_langs(synset_id): langs = sorted(wn.langs()) list_lang = [] list_useful_lang=[] for lang in langs: i...
0.084429
0.054024
from autoarray import decorator_util import numpy as np from astropy.io import fits import os @decorator_util.jit() def data_vector_from_blurred_mapping_matrix_and_data( blurred_mapping_matrix, image, noise_map ): """Compute the hyper_galaxies vector *D* from a blurred util matrix *f* and the 1D image *d* and...
autoarray/util/inversion_util.py
from autoarray import decorator_util import numpy as np from astropy.io import fits import os @decorator_util.jit() def data_vector_from_blurred_mapping_matrix_and_data( blurred_mapping_matrix, image, noise_map ): """Compute the hyper_galaxies vector *D* from a blurred util matrix *f* and the 1D image *d* and...
0.921935
0.857112
import json import threading from socket import gethostname from typing import Any, Dict, List, Tuple, Sequence from http.server import HTTPServer from prometheus_client.exposition import MetricsHandler from . import app_settings from .types import QueueName, WorkerNumber def get_config_response( worker_queue_a...
django_lightweight_queue/exposition.py
import json import threading from socket import gethostname from typing import Any, Dict, List, Tuple, Sequence from http.server import HTTPServer from prometheus_client.exposition import MetricsHandler from . import app_settings from .types import QueueName, WorkerNumber def get_config_response( worker_queue_a...
0.66454
0.143998
import numpy as np from distpy import sequence_types try: # this runs with no issues in python 2 but raises error in python 3 basestring except: # this try/except allows for python 2/3 compatible string type checking basestring = str class VariableGrid(object): """ Class representing an object ...
pylinex/util/VariableGrid.py
import numpy as np from distpy import sequence_types try: # this runs with no issues in python 2 but raises error in python 3 basestring except: # this try/except allows for python 2/3 compatible string type checking basestring = str class VariableGrid(object): """ Class representing an object ...
0.786787
0.607227
import threading class MessageMetrics: def __init__(self): """ """ self.byte_sum = 0 self.message_count = 0 self.message_handle_time = 0 def increment_message_count(self, message_size, time_taken): self.message_count += 1 self.byte_sum += message_size s...
ros2relay/metrics/metrics.py
import threading class MessageMetrics: def __init__(self): """ """ self.byte_sum = 0 self.message_count = 0 self.message_handle_time = 0 def increment_message_count(self, message_size, time_taken): self.message_count += 1 self.byte_sum += message_size s...
0.659953
0.198064
import os,json from .block_functions import * report_known_blocks = False report_unknown_blocks = True unknown_as_air = False converted_blocks = {} mods_available = {} mods_priority = [] mods_enabled = {} def str_mod(name): author = mods_available[name]['author'] download = mods_available[name]['download'] ...
mc2mtlib/block_conversion.py
import os,json from .block_functions import * report_known_blocks = False report_unknown_blocks = True unknown_as_air = False converted_blocks = {} mods_available = {} mods_priority = [] mods_enabled = {} def str_mod(name): author = mods_available[name]['author'] download = mods_available[name]['download'] ...
0.158077
0.111773
import requests from django.shortcuts import render # ****************************** GET ******************************** # get the list of all events of a client def getEvents(request): clientId = request.user url = 'https://hzmEndpoint.ch/events/' # https://hzmplaceholder.ch/events/<clientId>/ res...
app/services.py
import requests from django.shortcuts import render # ****************************** GET ******************************** # get the list of all events of a client def getEvents(request): clientId = request.user url = 'https://hzmEndpoint.ch/events/' # https://hzmplaceholder.ch/events/<clientId>/ res...
0.393735
0.133021
from datetime import datetime from io import BytesIO import json import os from unittest import TestCase from unittest.mock import ANY, patch import boto3 from botocore import UNSIGNED from botocore.client import Config from botocore.stub import Stubber import responses from .. import index class MockContext(): ...
lambdas/es/indexer/test/test_index.py
from datetime import datetime from io import BytesIO import json import os from unittest import TestCase from unittest.mock import ANY, patch import boto3 from botocore import UNSIGNED from botocore.client import Config from botocore.stub import Stubber import responses from .. import index class MockContext(): ...
0.61659
0.260895
from enum import Enum import random from tokenize import String import strings as Strings import spotipy from spotipy.oauth2 import SpotifyClientCredentials import config as Config import strings as Strings from youtube_search import YoutubeSearch import json import discord def playType(message): url = message.re...
BotUtils.py
from enum import Enum import random from tokenize import String import strings as Strings import spotipy from spotipy.oauth2 import SpotifyClientCredentials import config as Config import strings as Strings from youtube_search import YoutubeSearch import json import discord def playType(message): url = message.re...
0.34798
0.064772
import re import time import json from tqdm import tqdm import requests from bs4 import BeautifulSoup import img2pdf class Bookq(): URL = 'https://bookq.s.kyushu-u.ac.jp' def __init__(self): self._session = None def login(self, secrets_file :str='secrets.json'): """Log in to BookQ. ...
bookq2pdf.py
import re import time import json from tqdm import tqdm import requests from bs4 import BeautifulSoup import img2pdf class Bookq(): URL = 'https://bookq.s.kyushu-u.ac.jp' def __init__(self): self._session = None def login(self, secrets_file :str='secrets.json'): """Log in to BookQ. ...
0.592313
0.12943
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.impo...
pysnmp/GNOME-PRODUCT-ZEBRA-MIB.py
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.impo...
0.358915
0.107017
class Character: """ Represents a Character with it's aliases and alternative spellings during the books """ def __init__(self, ref_name: str, alt_names: list): """ :param ref_name: reference name of the Character (displayed in figures, for example) :param alt_names: list of alt...
src/object/Character.py
class Character: """ Represents a Character with it's aliases and alternative spellings during the books """ def __init__(self, ref_name: str, alt_names: list): """ :param ref_name: reference name of the Character (displayed in figures, for example) :param alt_names: list of alt...
0.85186
0.700914
from google.colab import drive drive.mount('/content/gdrive/') import os import datetime import random import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import tensorflow as tf import tensorflow.python.keras.backend as K from tensorflow.python....
results/SimpleLast/main2_LinearReg.py
from google.colab import drive drive.mount('/content/gdrive/') import os import datetime import random import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split import tensorflow as tf import tensorflow.python.keras.backend as K from tensorflow.python....
0.693265
0.29022
import ConfigSpace def get_hyperparameter_search_space_small(seed): """ Small version of svm config space, featuring important hyperparameters based on https://arxiv.org/abs/1710.04725 Parameters ---------- seed: int Random seed that will be used to sample random configurations R...
openmldefaults/config_spaces/svc.py
import ConfigSpace def get_hyperparameter_search_space_small(seed): """ Small version of svm config space, featuring important hyperparameters based on https://arxiv.org/abs/1710.04725 Parameters ---------- seed: int Random seed that will be used to sample random configurations R...
0.870556
0.382891
import pkg_resources import unittest import pyface.toolkit class TestToolkit(unittest.TestCase): def test_missing_import(self): # test that we get an undefined object if no toolkit implementation cls = pyface.toolkit.toolkit_object('tests:Missing') with self.assertRaises(NotImplementedEr...
Latest/venv/Lib/site-packages/pyface/tests/test_toolkit.py
import pkg_resources import unittest import pyface.toolkit class TestToolkit(unittest.TestCase): def test_missing_import(self): # test that we get an undefined object if no toolkit implementation cls = pyface.toolkit.toolkit_object('tests:Missing') with self.assertRaises(NotImplementedEr...
0.433022
0.390883
from zeep import Client c = Client('http://localhost:8000?wsdl') def get_header(): return c.get_type('ns0:Header')( Message_Type='mt', Company_ID='ci', Version='v', Source='s', Destination='d', Action_Type='read', Sequence_Number='1', Batch_ID='bi',...
util/client.py
from zeep import Client c = Client('http://localhost:8000?wsdl') def get_header(): return c.get_type('ns0:Header')( Message_Type='mt', Company_ID='ci', Version='v', Source='s', Destination='d', Action_Type='read', Sequence_Number='1', Batch_ID='bi',...
0.493897
0.089137
from typing import List import numpy from mlxtk import dvr from mlxtk.log import get_logger from mlxtk.parameters import Parameters from mlxtk.tasks import MBOperatorSpecification, OperatorSpecification class BoseHubbard: def __init__(self, parameters: Parameters): self.parameters = parameters s...
mlxtk/systems/single_species/bose_hubbard.py
from typing import List import numpy from mlxtk import dvr from mlxtk.log import get_logger from mlxtk.parameters import Parameters from mlxtk.tasks import MBOperatorSpecification, OperatorSpecification class BoseHubbard: def __init__(self, parameters: Parameters): self.parameters = parameters s...
0.853776
0.55266
import importlib import inspect import pkgutil import sys def package_classes(package): """Get a list of classes in a package. Return a list of qualified names of classes in the specified package. Classes in modules with names beginning with an "_" are omitted, as are classes whose internal module name ...
docs/source/docutil.py
import importlib import inspect import pkgutil import sys def package_classes(package): """Get a list of classes in a package. Return a list of qualified names of classes in the specified package. Classes in modules with names beginning with an "_" are omitted, as are classes whose internal module name ...
0.521959
0.328583
import trace import os import subprocess import tempfile import unittest import shlex import libutil class TraceTest(unittest.TestCase): def setUp(self): # create a directory hierarchy to do tests in self.test_data_dir = os.path.realpath(os.path.join(tempfile.gettempdir(), 'trace_test')) if os.path.exist...
src/trace_test.py
import trace import os import subprocess import tempfile import unittest import shlex import libutil class TraceTest(unittest.TestCase): def setUp(self): # create a directory hierarchy to do tests in self.test_data_dir = os.path.realpath(os.path.join(tempfile.gettempdir(), 'trace_test')) if os.path.exist...
0.22414
0.33269
import random from scapy.all import * import threading import socket import sys from urllib.parse import urlparse import colors import time class DDoS(object): def __init__(self, url, ip, start_port, end_port, dport, threads, interval): if url is not None and ip is not None: ...
src/lib/attacks/ddos/ddos.py
import random from scapy.all import * import threading import socket import sys from urllib.parse import urlparse import colors import time class DDoS(object): def __init__(self, url, ip, start_port, end_port, dport, threads, interval): if url is not None and ip is not None: ...
0.322633
0.09187
import re from oslo.config import cfg from marconi.openstack.common.gettextutils import _ MIN_MESSAGE_TTL = 60 MIN_CLAIM_TTL = 60 MIN_CLAIM_GRACE = 60 _TRANSPORT_LIMITS_OPTIONS = ( cfg.IntOpt('max_queues_per_page', default=20, deprecated_name='queue_paging_uplimit', deprecated_gr...
marconi/queues/transport/validation.py
import re from oslo.config import cfg from marconi.openstack.common.gettextutils import _ MIN_MESSAGE_TTL = 60 MIN_CLAIM_TTL = 60 MIN_CLAIM_GRACE = 60 _TRANSPORT_LIMITS_OPTIONS = ( cfg.IntOpt('max_queues_per_page', default=20, deprecated_name='queue_paging_uplimit', deprecated_gr...
0.677794
0.096408
import plotly.graph_objects as go # plots import pandas import os import locale locale.setlocale(locale.LC_ALL, 'de_DE') os.system("python plot_barchart.py") confirmed_df = pandas.read_csv("data/time_series/time_series_covid-19_nrw_confirmed.csv") recovered_df = pandas.read_csv("data/time_series/time_series_covid-1...
plot_data.py
import plotly.graph_objects as go # plots import pandas import os import locale locale.setlocale(locale.LC_ALL, 'de_DE') os.system("python plot_barchart.py") confirmed_df = pandas.read_csv("data/time_series/time_series_covid-19_nrw_confirmed.csv") recovered_df = pandas.read_csv("data/time_series/time_series_covid-1...
0.376165
0.189465
from Grafo import Grafo, Vertice, Aresta import random import pandas as pd import numpy as np from copy import deepcopy, copy from Busca import Busca # Criando o grafo e arestas file = pd.read_csv( "entrada8.txt", skiprows=1, delimiter='\t', header=None).applymap(str) # matrixSize = int(file.readline(1).strip()) ...
Main.py
from Grafo import Grafo, Vertice, Aresta import random import pandas as pd import numpy as np from copy import deepcopy, copy from Busca import Busca # Criando o grafo e arestas file = pd.read_csv( "entrada8.txt", skiprows=1, delimiter='\t', header=None).applymap(str) # matrixSize = int(file.readline(1).strip()) ...
0.175044
0.339472
# In[13]: import helper import numpy as np from distutils.version import LooseVersion import warnings import tensorflow as tf from tensorflow.contrib import seq2seq # In[14]: int_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess() # 建立NN网络 # In[15]: # Check TensorFlow Version assert ...
generation_train_and_save.py
# In[13]: import helper import numpy as np from distutils.version import LooseVersion import warnings import tensorflow as tf from tensorflow.contrib import seq2seq # In[14]: int_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess() # 建立NN网络 # In[15]: # Check TensorFlow Version assert ...
0.571169
0.442757
from os import path from bes.common.check import check from bes.common.object_util import object_util from bes.fs.file_check import file_check from bes.fs.file_find import file_find from bes.git.git import git class cli_helper(object): 'A class to help implement cli tools' @classmethod def resolve_files(clazz...
lib/bes/cli/cli_helper.py
from os import path from bes.common.check import check from bes.common.object_util import object_util from bes.fs.file_check import file_check from bes.fs.file_find import file_find from bes.git.git import git class cli_helper(object): 'A class to help implement cli tools' @classmethod def resolve_files(clazz...
0.479747
0.117648
import logging import pytest from test_app.models import Auth0User from tests.utils.auth0 import ( create_auth0_users_and_confirm, delete_all_auth0_users as delete_all_auth0_users_via_api, delete_all_auth0_users_with_confirmation, pause_and_confirm_total_auth0_users, ) logger = logging.getLogger(__n...
tests/fixtures/auth0.py
import logging import pytest from test_app.models import Auth0User from tests.utils.auth0 import ( create_auth0_users_and_confirm, delete_all_auth0_users as delete_all_auth0_users_via_api, delete_all_auth0_users_with_confirmation, pause_and_confirm_total_auth0_users, ) logger = logging.getLogger(__n...
0.235724
0.263629
import uuid import hashlib import base64 from urllib.parse import quote_plus import fgourl import mytime class ParameterBuilder: def __init__(self, uid: str, auth_key: str, secret_key: str): self.uid_ = uid self.auth_key_ = auth_key self.secret_key_ = secret_key self.content_ = '' ...
user.py
import uuid import hashlib import base64 from urllib.parse import quote_plus import fgourl import mytime class ParameterBuilder: def __init__(self, uid: str, auth_key: str, secret_key: str): self.uid_ = uid self.auth_key_ = auth_key self.secret_key_ = secret_key self.content_ = '' ...
0.26569
0.107601
import os, sys for i in range(10): if sys.platform[:3] == 'win': pypath = sys.executable os.spawnv(os.P_NOWAIT, pypath, ('python', 'child.py', str(i))) else: pid = os.fork() if pid != 0: print('Process %d spawned' % pid) else: os.execlp('python', ...
chapter_5/spawnv.py
import os, sys for i in range(10): if sys.platform[:3] == 'win': pypath = sys.executable os.spawnv(os.P_NOWAIT, pypath, ('python', 'child.py', str(i))) else: pid = os.fork() if pid != 0: print('Process %d spawned' % pid) else: os.execlp('python', ...
0.149438
0.308099
import torch import numpy as np from utils.block_diag_matrix import block_diag_irregular from scipy.spatial import distance_matrix def compute_adjs(args, seq_start_end): adj_out = [] for _, (start, end) in enumerate(seq_start_end): mat = [] for t in range(0, args.obs_len + args.pred_len): ...
utils/adj_matrix.py
import torch import numpy as np from utils.block_diag_matrix import block_diag_irregular from scipy.spatial import distance_matrix def compute_adjs(args, seq_start_end): adj_out = [] for _, (start, end) in enumerate(seq_start_end): mat = [] for t in range(0, args.obs_len + args.pred_len): ...
0.560734
0.4575
from SPARQLTransformer import sparqlTransformer from .lemma import Lemma SKOS = 'http://www.w3.org/2004/02/skos/core#' class Vocabulary: list = {} @classmethod def createVocabulary(cls, name, trunkNamespace, namespaces, prop, lang): Vocabulary.add(name, Vocabulary(name, trunkNamespace, namespace...
populate/entities/vocabularies/vocabulary.py
from SPARQLTransformer import sparqlTransformer from .lemma import Lemma SKOS = 'http://www.w3.org/2004/02/skos/core#' class Vocabulary: list = {} @classmethod def createVocabulary(cls, name, trunkNamespace, namespaces, prop, lang): Vocabulary.add(name, Vocabulary(name, trunkNamespace, namespace...
0.702122
0.205117
import requests from lxml import etree import json class Qiushi(object): def __init__(self): self.url = 'https://www.qiushibaike.com/8hr/page/{}/' self.url_list = None self.headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome...
day05/qiushibaike.py
import requests from lxml import etree import json class Qiushi(object): def __init__(self): self.url = 'https://www.qiushibaike.com/8hr/page/{}/' self.url_list = None self.headers = { 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome...
0.079642
0.133641
import json import subprocess from . import collectors class CompletedProcessMock: def __init__(self, stdout='', stderr=''): self.stdout = stdout self.stderr = stderr blame_text = """\ aacd7f517fb0312ec73f882a345d50c6e8512405 1 1 1 author <NAME> ... filename file.txt line one 4cbb5a68de251bf42e...
gitstats/test_collectors.py
import json import subprocess from . import collectors class CompletedProcessMock: def __init__(self, stdout='', stderr=''): self.stdout = stdout self.stderr = stderr blame_text = """\ aacd7f517fb0312ec73f882a345d50c6e8512405 1 1 1 author <NAME> ... filename file.txt line one 4cbb5a68de251bf42e...
0.40028
0.225204
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 CreateStreamDetails(object): """ Object used to create a stream. """ def __init__(self, **kwargs): ...
src/oci/streaming/models/create_stream_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 CreateStreamDetails(object): """ Object used to create a stream. """ def __init__(self, **kwargs): ...
0.838018
0.318167
from sparts.sparts import option from sparts.vtask import ExecuteContext, VTask from sparts.tests.base import BaseSpartsTestCase, SingleTaskTestCase class ExecuteContextTests(BaseSpartsTestCase): def test_comparisons(self): self.assertEqual(ExecuteContext(), ExecuteContext()) self.assertEqual(Execu...
tests/test_vtask.py
from sparts.sparts import option from sparts.vtask import ExecuteContext, VTask from sparts.tests.base import BaseSpartsTestCase, SingleTaskTestCase class ExecuteContextTests(BaseSpartsTestCase): def test_comparisons(self): self.assertEqual(ExecuteContext(), ExecuteContext()) self.assertEqual(Execu...
0.630002
0.213787
import json from datetime import datetime from typing import Callable, Optional import logging from fastapi import Request, Response from fastapi.routing import APIRoute def reformat_body(body: bin, obfuscate: bool = False): """ Decodes the binary body into something more useful for logging. - body - the...
starlette_logging_request_body/router.py
import json from datetime import datetime from typing import Callable, Optional import logging from fastapi import Request, Response from fastapi.routing import APIRoute def reformat_body(body: bin, obfuscate: bool = False): """ Decodes the binary body into something more useful for logging. - body - the...
0.759315
0.211417
from unittest import TestCase from scoville.signal import GenericSignal, DelayedSignal INPUT_RESISTANCE = 10 LOW = 0.0 HIGH = 5.0 MAX_CURRENT = 0.01 MAX_LOW_VOLTAGE = 0.5 MIN_HIGH_VOLTAGE = 4.5 class AndUnitTests(TestCase): def testLowLowShouldResultInLow(self): circuit = self.getCircuit() circuit.setSi...
test/unitTests/test_AND.py
from unittest import TestCase from scoville.signal import GenericSignal, DelayedSignal INPUT_RESISTANCE = 10 LOW = 0.0 HIGH = 5.0 MAX_CURRENT = 0.01 MAX_LOW_VOLTAGE = 0.5 MIN_HIGH_VOLTAGE = 4.5 class AndUnitTests(TestCase): def testLowLowShouldResultInLow(self): circuit = self.getCircuit() circuit.setSi...
0.760028
0.621254
import logging from smart_home.mqtt_client import MQTTClient from smart_home.utils_lambda import get_utc_timestamp, error_response, success_response, get_payload, get_request_message_id, get_mqtt_topics_from_request,\ get_friendly_name_from_request class PercentageController(object): @staticmethod def h...
smart_home/percentage_controller.py
import logging from smart_home.mqtt_client import MQTTClient from smart_home.utils_lambda import get_utc_timestamp, error_response, success_response, get_payload, get_request_message_id, get_mqtt_topics_from_request,\ get_friendly_name_from_request class PercentageController(object): @staticmethod def h...
0.610802
0.122078
from odoo import _, api, fields, models from odoo.exceptions import ValidationError class ReturnPicking(models.TransientModel): _inherit = 'stock.return.picking' create_rma = fields.Boolean( string="Create RMAs" ) picking_type_code = fields.Selection( selection=[ ('incomi...
rma/setup/rma/odoo/addons/rma/wizard/stock_picking_return.py
from odoo import _, api, fields, models from odoo.exceptions import ValidationError class ReturnPicking(models.TransientModel): _inherit = 'stock.return.picking' create_rma = fields.Boolean( string="Create RMAs" ) picking_type_code = fields.Selection( selection=[ ('incomi...
0.539954
0.132739
from GAML.functions import file_size_check, file_gen_new from GAML.file_gen_gromacstop import File_gen_gromacstop from GAML.charge_gen_scheme import Charge_gen_scheme import os import shutil from pkg_resources import resource_string class GAML_autotrain(object): def __init__(self,*args,**kwargs): if 'fi...
GAML/gaml_autotrain.py
from GAML.functions import file_size_check, file_gen_new from GAML.file_gen_gromacstop import File_gen_gromacstop from GAML.charge_gen_scheme import Charge_gen_scheme import os import shutil from pkg_resources import resource_string class GAML_autotrain(object): def __init__(self,*args,**kwargs): if 'fi...
0.164215
0.076857
from unittest import TestCase from unittest.mock import MagicMock, patch from napps.kytos.storehouse.backends.etcd import (Etcd, join_fullname, split_fullname) from napps.kytos.storehouse.main import Box # pylint: disable=protected-access, unused-argument, no-member ...
tests/unit/test_etcd.py
from unittest import TestCase from unittest.mock import MagicMock, patch from napps.kytos.storehouse.backends.etcd import (Etcd, join_fullname, split_fullname) from napps.kytos.storehouse.main import Box # pylint: disable=protected-access, unused-argument, no-member ...
0.81538
0.352397