text string | size int64 | token_count int64 |
|---|---|---|
import json
siteList = []
for i in range(1,20):
siteList.append(input(f'Enter site {i}: '))
print(siteList)
#print(siteList)
with open('host_list.json', 'w', encoding='utf-8') as f:
json.dump(siteList, f, ensure_ascii=False, indent=4) | 257 | 107 |
from output.models.nist_data.atomic.g_year.schema_instance.nistschema_sv_iv_atomic_g_year_min_exclusive_4_xsd.nistschema_sv_iv_atomic_g_year_min_exclusive_4 import NistschemaSvIvAtomicGYearMinExclusive4
__all__ = [
"NistschemaSvIvAtomicGYearMinExclusive4",
]
| 264 | 113 |
from checkov.dockerfile.checks import * | 39 | 12 |
import pytest
from eth_utils import (
encode_hex,
remove_0x_prefix,
)
def test_contract_constructor_abi_encoding_with_no_constructor_fn(MathContract, MATH_CODE):
deploy_data = MathContract._encode_constructor_data()
assert deploy_data == MATH_CODE
def test_contract_constructor_abi_encoding_with_con... | 4,354 | 1,769 |
"""
Author: Matt Hanson
Created: 18/12/2020 9:30 AM
"""
from Pasture_Growth_Modelling.initialisation_support.inital_long_term_runs import run_past_basgra_irrigated, \
run_past_basgra_dryland, plot_multiple_results
import pandas as pd
import numpy as np
if __name__ == '__main__':
reseed=True
irr_ox = ru... | 832 | 345 |
from vintageColorizer._device import _Device
device = _Device() | 64 | 19 |
from django import forms
from django.contrib import admin
from .models import (DocumentationRecord, Hardware, MaintenanceRecord,
MaintenanceRecordRelationship, MaintenanceType, Software, SysAdmin, System)
class ReferencingRecordInline(admin.TabularInline):
model = MaintenanceRecordRelationship
fk_name = ... | 5,570 | 1,647 |
# handle url encoding
# do 'quote' on url
from urllib.parse import quote
class Parse(object):
'''
parse and encode webservice payload
'''
def __init__(self, web_url, quote_body, quote_recipients):
self.web_url = web_url
self.quote_body = quote_body
... | 859 | 272 |
import itertools
from copy import deepcopy
from string import Formatter
from .utils import unicode
class FormatSpec(object):
# A format string to generate e.g. role names.
def __init__(self, spec):
self.spec = spec
self._fields = None
def __repr__(self):
return "%s(%r)" % (self.... | 9,579 | 2,681 |
from socket import *
def banner():
print("""
###########################################################
#------------------PORT SCAN V 1.0-----------------------#
#--------------------Coder By Bozkurt-------------------#
###########################################################
""")
... | 1,190 | 406 |
from string import punctuation
import random
import jsonlines
import regex
class Evaluator:
"""Class for evaluating NER models on two IOB tagged datasets: SUC 3.0 and Web News 2012, both from Språkbanken."""
def __init__(self, suc):
self.suc = suc
if suc:
self.path = "data/input... | 5,413 | 1,802 |
# Copyright 2011 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,... | 9,456 | 3,530 |
#!/usr/share/python
# -*- encoding: utf-8 -*-
#
# Extract synset-word pairs from the Japanese Wordnet
#
import sys
import codecs
#import re
wndata="/home/bond/svn/wnja-code/tab/"
wnname = "Japanese Wordnet"
wnlang = "jpn"
wnurl = "http://nlpwww.nict.go.jp/wn-ja/"
wnlicense = "wordnet"
#
# header
#
outfile = "wn-dat... | 825 | 375 |
from locust.stats import RequestStats
from locust import HttpLocust, TaskSet, task, events
import os
import sys, getopt, argparse
from random import randint,random
import json
from locust.events import EventHook
import requests
import re
import time
import resource
import socket
import signal
from socket import error a... | 5,701 | 1,799 |
from measure import metrics, norms
if __name__ == "__main__":
metrics.metric(1)
norms.norms()
| 106 | 40 |
import threading
import pytest
import numpy as np
import pandas as pd
import sys
from keras import losses
from keras.engine import Input
from keras.engine.training import Model
from keras.engine import training_utils
from keras.layers import Dense, Dropout
from keras.utils.generic_utils import slice_arrays
from keras.... | 8,475 | 3,022 |
from django.http import QueryDict
from django.test import TestCase, RequestFactory
from directory.views import DirectoryView
from .models import TestModelB, MultipleFieldModel
class DirectoryViewGetContextData(TestCase):
def test_filter_is_not_supplied_in_kwargs___filter_is_added(self):
class TestDirector... | 10,522 | 3,013 |
#!/usr/bin/env python3
import os, sys, subprocess
from dataclasses import dataclass
# Input variables:
# INPUT_CHECKS
# INPUT_DEPENDENCIES
# INPUT_DIRECTORY
# INPUT_BUILDDIR
# INPUT_CC
# INPUT_CFLAGS
# INPUT_CXXFLAGS
# INPUT_CONANFLAGS
# INPUT_CMAKEFLAGS
# INPUT_CTESTFLAGS
# INPUT_MAKEFLAGS
# ... | 17,466 | 5,927 |
import unittest
class Solution:
def isPowerOfFour(self, num: int) -> bool:
if num <= 0:
return False
number_format_bin = format(num, 'b')
number_ones = number_format_bin.count('1')
if number_ones == 1:
if (len(number_format_bin)-1) % 2 == 0:
... | 1,811 | 632 |
from django.urls import path
from .views import ExchangeCreateView, ExchangeDeleteView, ExchangeDetailView, ExchangeListView, ExchangeUpdateView
app_name = "exchange"
urlpatterns = [
path("", ExchangeListView.as_view(), name="exchange_list"),
path("add/", ExchangeCreateView.as_view(), name="exchange_add"),
... | 561 | 161 |
from collections import OrderedDict
from mycv.utils.general import ANSI
class SimpleTable(OrderedDict):
def __init__(self, init_keys=[]):
super().__init__()
# initialization: assign None to initial keys
for key in init_keys:
if not isinstance(key, str):
ANSI.wa... | 3,579 | 1,185 |
#!/usr/bin/env python3
"""
Tutorial for processing tabulated tide gauge data
Created on Mon Oct 12 22:30:21 2020
You might scrape tidal highs and lows from a website such as
<a title="NTSLF tidal predictions"
href="https://www.ntslf.org/tides/tidepred?port=Liverpool">
<img alt="NTSLF tidal predictions"
src="https://... | 2,939 | 1,203 |
# Village People, 2017
from argparse import ArgumentParser
def get_args():
args = ArgumentParser('PigChaseExperiment')
args.add_argument('-t', '--type', type=str, default='random',
choices=['dqn', 'empathetic', 'astar', 'random'],
help='The type of baseline to run.'... | 1,373 | 466 |
def product_except_self(A):
'''
238. Product of Array Except Self
=================================
Given an array A of n integers (n > 1), return an array where the i-th
element is the product of all but the i-th element of A.
Restrictions:
-------------
1. Don't use division
2. Us... | 721 | 277 |
import numpy as np
def xavier_uniform_weight(shape, seed=0):
"""
initialize weight matrix with xavier_uniform_initializer.
matrix size will be shape arguments
"""
np.random.seed(seed)
scale = 1 / max(1., np.sum(shape) / 2.)
limit = np.sqrt(scale * 3.)
return np.random.uniform(-limit, l... | 452 | 149 |
# -*- coding: utf-8“ -*-
from django.test import TestCase
from eventtools.tests._inject_app import TestCaseWithApp as AppTestCase
from eventtools.tests.eventtools_testapp.models import *
from datetime import date, time, datetime, timedelta
from eventtools.tests._fixture import bigfixture, reload_films
from eventtools.u... | 5,952 | 1,991 |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'McctStatus.modified_on'
db.add_column(u'm4change_mcctstatus', 'modified_on', self.gf('djan... | 1,756 | 579 |
#!/usr/bin/env python
import argparse
from sqlalchemy.exc import ProgrammingError
from monitoring.constants import ROLE_ADMIN, ROLE_USER
from models import Keypad, KeypadType, Sensor, SensorType, User, Zone
from monitoring.database import Session
from models import metadata
SENSOR_TYPES = [
SensorType(1, name... | 6,231 | 2,268 |
from action import *
from playerState import *
import gameController
import os.path
import json
###
#parses json containing known actions
#produces actions that return a specified PS
###
class ActionFactory:
def __init__(self,costs):
with open('json/actionMemory.json') as jsfl:
actMemory = j... | 1,595 | 472 |
"""
********************************************************************************
interfaces.kinematics
********************************************************************************
.. currentmodule:: pybullet_planning.interfaces.kinematics
Kinematics interface
--------------------
.. autosummary::
:toctre... | 653 | 178 |
import matplotlib.collections
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import scipy.sparse as sp
import numpy as np
def plot_lattice(L, ax=None, dot='.'):
"""Plot a 2D or 3D representation of the lattice on the given
axis, or create one if none is given.
Parameters
----------
... | 2,904 | 1,091 |
from starcluster.clustersetup import ClusterSetup
from starcluster.logger import log
class FakeModInstaller(ClusterSetup):
def run(self, nodes, master, user, user_shell, volumes):
for node in nodes:
log.info("Creating python 2.6.5 module files on %s" % (node.alias))
node.ssh.execute('mkdir /usr/local/Modules/... | 3,143 | 1,275 |
# Enter your password for SQL
sqlpw = "password"
| 49 | 16 |
import argparse
import logging as log
import re
from collections import defaultdict
from difflib import SequenceMatcher
from os.path import commonprefix
import pandas as pd
import torch
from torch.nn.functional import nll_loss, log_softmax
from nltocode.datamodule import NL2CodeTrainDataModule
from nltocode.grammar.g... | 10,696 | 3,871 |
from typing import List, Optional, Type
from tortoise import BackwardFKRelation, ForeignKeyFieldInstance, ManyToManyFieldInstance, Model
from tortoise.fields import (
BigIntField,
BooleanField,
CharField,
DateField,
DatetimeField,
DecimalField,
FloatField,
IntField,
JSONField,
S... | 11,735 | 3,316 |
from collections import defaultdict
import numpy as np
import sys
import cv2
import pandas as pd
label_list = [
'Bird_spp',
'Blue_sheep',
'Glovers_pika',
'Gray_wolf',
'Himalaya_marmot',
'Red_fox',
'Snow_leopard',
'Tibetan_snowcock',
'Upland_Buzzard',
'White-lipped_deer'
]
clas... | 5,943 | 2,209 |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import pandas as pd
import numpy as np
import scipy.misc
import pydicom
import glob
import sys
import os
import pandas as pd
import base64
from IPython.display import HTML
# In[ ]:
from scipy.ndimage.interpolation import zoom
# In[ ]:
get_ipython().system('gi... | 7,348 | 2,900 |
#!/usr/bin/env python
import sys
from qtpy import QtWidgets
def window():
app = QtWidgets.QApplication(sys.argv)
w = QtWidgets.QWidget()
b = QtWidgets.QLabel(w)
b.setText("Hello World!")
w.setGeometry(100,100,200,50)
b.move(50,20)
w.setWindowTitle("hello")
w.show()
sys.exit(app.e... | 369 | 156 |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.utils.html import format_html
from django.db.models import Count
from django.template.defaultfilters import filesizeformat
from django.utils.translation import gettext_lazy as _
from core import models as ratom
@admin.registe... | 7,321 | 2,154 |
# Cython compiler
from distutils.core import setup
from Cython.Build import cythonize
setup(name='CA base class', ext_modules=cythonize("ca.pyx")) | 148 | 48 |
class Solution:
def evalRPN(self, tokens: List[str]) -> int:
stack = []
ops = {'+', '-', '*', '/'}
for token in tokens:
if token not in ops:
stack.append(int(token))
else:
a = stack.pop()
b = stack.pop()
... | 721 | 188 |
import os
import sys
from unittest.mock import patch
from unittest import TestCase
from insightconnect_plugin_runtime.exceptions import (
PluginException,
ConnectionTestException,
)
from icon_ibm_qradar.actions.start_ariel_search import StartArielSearch
from unit_test.helpers.ariel_search import ArielSearchH... | 2,762 | 804 |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from services import build_url
from waterfall.test.wf_testcase import WaterfallTestCase
class FlakeReportUtilTest(WaterfallTestCase):
def testCreateBuild... | 682 | 214 |
from config.cst import EvaluatorMatrixTypes
from tools.evaluators_util import check_valid_eval_note
class EvaluatorMatrix:
def __init__(self, config):
self.config = config
self.matrix = {
EvaluatorMatrixTypes.TA: {},
EvaluatorMatrixTypes.SOCIAL: {},
EvaluatorMat... | 1,677 | 475 |
import os.path as osp
import glob
import h5py
import numpy as np
from tqdm import tqdm
import torch
from torch_geometric.data import Data
from torch_geometric.data import Dataset
class DeepJetCoreV2(Dataset):
r'''
input z0: (FatJat basic stats, 1)
'fj_pt',
'fj_eta',
'f... | 3,615 | 1,313 |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# d... | 1,427 | 439 |
"""
MIT License
Copyright (C) 2021-2022, NkSama
Copyright (C) 2021-2022 Moezilla
Copyright (c) 2021, Sylviorus, <https://github.com/Sylviorus/BlueMoonVampireBot>
This file is part of @BlueMoonVampireBot (Antispam Telegram Bot)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software... | 1,848 | 632 |
# Generated by Django 2.1 on 2018-08-18 15:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0003_auto_20180815_2234'),
]
operations = [
migrations.AddField(
model_name='user',
name='username',
... | 403 | 146 |
# Copyright (c) OpenMMLab. All rights reserved.
from copy import deepcopy
from typing import Sequence
import numpy as np
import torch
import torch.nn as nn
from mmcv.cnn import build_norm_layer
from mmcv.cnn.bricks.transformer import FFN
from mmcv.cnn.utils.weight_init import trunc_normal_
from mmcv.runner.base_module... | 13,024 | 4,221 |
import os
import sys
import numpy as np
import pytest
import unittest
from geopyspark.geotrellis import Tile
from geopyspark.geotrellis.layer import RasterLayer
from geopyspark.geotrellis.constants import LayerType
from geopyspark.tests.base_test_class import BaseTestClass
from pyspark.storagelevel import StorageLevel... | 2,313 | 878 |
# -*- coding: utf-8 -*-
"""
pia.cli
~~~~~~~~~~~~~
A simple command line application for pia.
"""
import click
@click.group()
def cli():
"""
Pia cli group
"""
pass
@cli.command()
def run():
"""
Run remote pia program.
"""
pass
@cli.command()
def dev():
"""
Develop a pia progr... | 432 | 152 |
from django.contrib import admin
# Register your models here.
from .models import core
from .models import build
from .models import play
admin.site.register(core.FireEmblemGame)
admin.site.register(core.Unit)
admin.site.register(core.Class)
admin.site.register(core.Weapon)
admin.site.register(core.Item)
admin.site.r... | 1,222 | 417 |
# Global
KEYWORD_CHAR = "#"
# API Keywords
KEYWORD_ID = "#id"
KEYWORD_START = "#start"
KEYWORD_END = "#end"
# Modules
MODULE_CHAR = "@"
CORE_MODULE_PACKAGE = "pytijo.modules"
DEFAULT_MODULE_NAME = "tijo_re"
| 207 | 91 |
#!/usr/bin/env python3
import RPi.GPIO as GPIO
from rpi_rilla.helpers import update_yaml
GPIO.setmode(GPIO.BOARD)
class Light:
def __init__(self, id, pin, default, state_file):
GPIO.setup(pin, GPIO.OUT)
self.id = id
self.pin = pin
self.state_file = state_file
self.set(def... | 742 | 267 |
import numpy as np
import math
from configuration import IMAGE_HEIGHT, IMAGE_WIDTH, ASPECT_RATIOS, FEATURE_MAPS, \
DEFAULT_BOXES_SIZES, DOWNSAMPLING_RATIOS
from itertools import product
class DefaultBoxes:
def __init__(self):
assert IMAGE_HEIGHT == IMAGE_WIDTH
self.image_size = IMAGE_HEIGHT
... | 1,476 | 545 |
'''
Reinforce function
- Takes a list of targets to be reinforced
- Weighs targets
- Sends reinforcements if available
'''
def reinforce(self, simulStates): #TODO: How to bring troops to the front?
curTroops = min(self.troops, readMaxAvailTroops(simulStates[self.ID])[0])
... | 16,006 | 4,818 |
from pathlib import Path
import numpy as np
from abspy import CellComplex
dir_tests = Path(__file__).parent
def example_cell_complex():
"""
Simple CellComplex construction from specified planes and bounds.
"""
# start from two planes
planes = np.array([[0, 1, 0, -50], [0, 0, 1, -50]])
# spe... | 1,185 | 432 |
#!/usr/bin/env python3
"""
exa-receive.py: Save received routes form ExaBGP into file
"""
import argparse
import os
from sys import stdin
from datetime import datetime
parser = argparse.ArgumentParser()
parser.add_argument(
"--no-timestamp", dest="timestamp", action="store_false", help="Disable timestamps"
)
par... | 1,106 | 346 |
from Cryptodome.Cipher import AES
import struct
# https://tools.ietf.org/html/rfc3610
def aesCCMEncrypt(plaintext, aad, key, nonce, macLen):
blockSize = 16 # For AES...
if macLen not in (4, 6, 8, 10, 12, 14, 16):
raise ValueError("Parameter 'mac_len' must be even and in the range 4..16 (not %d)" % macLen)
if n... | 2,068 | 996 |
import numpy as np
class MutationDecidor:
def __init__(self,
mutation_type,
n_genes,
mutation_propability,
low_boundery=0,
high_boundery=0):
self.n_genes = n_genes
self.mutation_propability = mutation_propability... | 1,878 | 571 |
"""Evaluate a network with Detectron."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import cv2 # NOQA (Must import before importing caffe2 due to bug in cv2)
import os
import pprint
import sys
imp... | 3,480 | 1,123 |
import nose.tools as nt
import numpy as np
import theano
import treeano.nodes as tn
fX = theano.config.floatX
def test_sequential_node_serialization():
tn.check_serialization(tn.SequentialNode("a", []))
tn.check_serialization(tn.SequentialNode(
"a",
[tn.SequentialNode("b", []),
tn.S... | 2,847 | 1,029 |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
('legislative', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='... | 3,231 | 875 |
from urllib.parse import urlparse
import datetime
from decouple import config
from peewee import *
database_proxy = DatabaseProxy()
production = config('PRODUCTION', cast=bool)
class BaseModel(Model):
class Meta:
database = database_proxy
class Estudiante(BaseModel):
nombre_usuario = CharField(m... | 1,112 | 342 |
from scipy.integrate import odeint
import os
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
import sys
hstep = .01
sstep = .01
hmin = 0.
hmax = 2.
smin = 0.
smax = 3.
rmin = .01
rmax = 3.
rstep = .1
rr = np.arange(rmin,rmax+rstep,rstep)
LL3 = 1.2
LL4 = 0.22
dx = .01
s0 = .01
h0 = .01
... | 2,213 | 1,101 |
# CLI application for sentiment analysis of a user's tweets
# Load constants
# Check if saved model exists, if it does not, ask user if ok to train
# Save model for vectorizer as well
# Get user's twitter address
# Ask if he wants a word cloud too
# Start analyzing - Show animation for loading?
# display graph of se... | 4,405 | 1,385 |
import datetime
def get_semester(date: datetime.datetime) -> str:
"""
Semesters are coded B161 (winter 2016/2017), B162 (summer 2016/2017) etc.
They are obtained by comparing dates:
January-February year X -> winter semester of year (X-1)/X
March-September year X -> summer semester of ye... | 1,237 | 491 |
"""
format timedelta object
"""
from string import Formatter
def strFormatTimeDelta(tDelta, fmt=None):
"""
strFormatTimeDelta format time delta string. If fmt is None a format of
'N days N hours N minutes N seconds' will be used starting with the first
non zero N found in the calculations.
Args... | 1,465 | 463 |
import json
from hashlib import sha1
import hmac
from os import path
import pytest
from crocodile.app import create_app
TEST_SECRET = 'test_secret'
@pytest.fixture
def app():
test_config = {
'CROCODILE_SECRET': TEST_SECRET,
'TESTING': True,
'CONSUMERSFILE': path.join(path.dirname(__file_... | 951 | 343 |
from gatelfpytorchjson import CustomModule
from gatelfpytorchjson import EmbeddingsModule
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
import logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
streamhandler = logging.StreamHandler(stream=sys.stderr)
formatter =... | 5,091 | 1,995 |
import flwr as fl
import os
from flwr.server.strategy import FedAvg
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
ENV = os.environ
FRACTION_FIT = float(ENV.get('FRACTION_FIT', "0.5"))
MIN_AVAILABLE_CLIENTS = int(ENV.get('MIN_AVAILABLE_CLIENTS', "5"))
NUM_ROUNDS = int(ENV.get('NUM_ROUNDS', "10"))
SERVER_ADDRESS = ENV.get... | 728 | 294 |
"""Adapt plot functions with seaborn to get more beautiful plots."""
from __future__ import unicode_literals
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import os
import collections
import itertools
import numpy as np
import scipy.stats a... | 10,279 | 3,555 |
import random
from detectron2.utils.visualizer import Visualizer
from detectron2.data.catalog import MetadataCatalog, DatasetCatalog
import mol_data
import cv2
mol_metadata = MetadataCatalog.get("mol")
print(mol_metadata)
dataset_dicts = DatasetCatalog.get("mol")
for d in random.sample(dataset_dicts, ... | 599 | 234 |
# coding: utf-8
import pandas as pd
from glob import glob
from joblib import dump
from imblearn.over_sampling import SMOTE
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
if __name__ == "__main__":
TRAINING_DATA_PATH = "/opt/ml/input/data/train/"
MODE... | 1,916 | 646 |
"""AHOT Spatial Solver tests"""
# TODO:
# Add tests with supported warning configurations?
# a = populate_with_warnings("AHOTN")
# a = populate_with_warnings("DGFEM")
import numpy as np
from numpy.testing import assert_array_almost_equal
import pyne.spatialsolver
from .dictionary_populate_test import (
populate_... | 20,786 | 12,621 |
from .....data.URL import QIWIWalletURLS
from .....data_types.connector.request_type import GET
from .....connector.aiohttp_connector import Connector
class CurrencyRatesAPI:
@classmethod
async def get_currency_rates(cls, wallet_api_key: str) -> dict:
url = QIWIWalletURLS.Payments.currency_rates
... | 646 | 197 |
class MissingKeyException(Exception):
pass
| 47 | 13 |
import os.path
import re
import sys
try:
import sysconfig
except ImportError: # Python 2.6 support
sysconfig = None
import warnings
from okonomiyaki.errors import OkonomiyakiError
from okonomiyaki.platforms import PythonImplementation
from okonomiyaki.utils import py3compat
from ._egg_info import _guess_pytho... | 5,877 | 1,812 |
class Codec:
def encode(self, strs):
"""Encodes a list of strings to a single string.
:type strs: List[str]
:rtype: str
"""
# encode format '<total_length> <seperate length connected with -> <joined str>'
if not strs:
return ''
separate_l... | 1,145 | 355 |
"""Base of all build rules."""
from pathlib import Path
from garage import scripts
from foreman import define_parameter, rule, to_path
(define_parameter.path_typed('root')
.with_doc('Path to the root directory of this repository.')
.with_default(Path(__file__).parent.parent.parent.parent))
(define_parameter.pa... | 3,761 | 1,207 |
from functools import wraps
from models import User
class AuthenticationService:
@classmethod
def get_profile_from_token(cls, token):
user = User.get(where={'auth_token': token})
if not user:
raise Exception("No profile for this token")
return user
@classmethod
d... | 1,099 | 295 |
import urllib, json
import urllib.request,os
import socket
import random
import re
socket.setdefaulttimeout(50)
#https://www.hide-my-ip.com/fr/proxylist.shtml
# .*(\[\{.*\]).*
KEY="A00239D3-45F6-4A0A-810C-54A347F144C2"
KEY="720129CF233B4CA2DF97DAE48C8717E1"
KEY="35d28185-0ca1-47f0-8caf-edc457802c9d"
KEY="B... | 13,938 | 5,312 |
"""
Diamond Cronjob
=================
Event Detection based on data stored in Diamond
:Author: Nik Sumikawa
:Date: Nov 3, 2020
"""
import logging
log = logging.getLogger(__name__)
import pandas as pd
from src.apps.interface import *
from src.git.interface import *
import os
class CLI:
def __init__(self):... | 9,739 | 3,147 |
'''
Author: Hans Erik Heggem
Email: hans.erik.heggem@gmail.com
Project: Master's Thesis - Autonomous Inspection Of Wind Blades
Repository: Master's Thesis - CV (Computer Vision
'''
import timeit
from getpass import getpass
from src.DroneVision.DroneVision_src.hardware.imageTools import MatplotShow
'''
@brief LogT... | 7,636 | 2,620 |
while True:
try:
n = str(input())
print(n)
except EOFError:
break
| 99 | 34 |
from diesel import quickstart, quickstop, sleep, first
from diesel.protocols.zeromq import DieselZMQSocket, zctx, zmq
import time
def get_messages():
outsock = DieselZMQSocket(zctx.socket(zmq.DEALER), bind="tcp://127.0.0.1:5000")
for x in xrange(1000):
t, m = first(sleep=1.0, waits=[outsock])
... | 458 | 168 |
testlist_bubblesort = [40,723, 781, 610, 440, 819, 728,
280, 998, 744, 40, 303, 708, 279, 910]
testlist_decision = [560, 769, 349, 97, 881, 108, 827,
131, 301, 952, 255, 787, 625, 549, 5]
testlist_insertion = [984, 738, 859, 281, 548, 399, 894,
... | 1,652 | 745 |
'''
Created on 14-May-2019
@author: mehulk99
'''
from flask import jsonify
from bookstore.src.config import BookConfig
from bookstore.src.dao.DataAccessor import DataAccessor
from ...category.CategoryService import CategoryService
from ...models.core.business.books.BookRepository import BookRepository
from ...searc... | 4,728 | 1,378 |
from unittest import TestCase
from osbot_utils.utils.Dev import Dev
from osbot_jupyter.api_notebook.Jp_GSheets import Jp_GSheets
class test_Jp_GSheets(TestCase):
def setUp(self):
self.file_id = '1_Bwz6z34wALFGb1ILUXG8CtF1-Km6F9_sGXnAu4gewY'
self.sheet_name = 'Jira Data'
self.sheets ... | 641 | 252 |
def dummy():
return 0;
def test_not_null_count(data, result, axis):
is_notnull_result = data.notnull()
data_not_null = is_notnull_result.sum(axis = axis)
test_ok = all(data_not_null == result)
if test_ok:
msg = "Muy bien!!"
else:
if type(result) == "pandas.core.series.Series":
... | 1,576 | 506 |
"""Maintenance related keyboards."""
from telegram import (
InlineKeyboardMarkup,
InlineKeyboardButton,
)
from stickerfinder.helper.callback import build_user_data, build_data
def get_settings_keyboard(user):
"""Get the inline keyboard for settings."""
international_payload = build_user_data("user_tog... | 3,583 | 1,092 |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import palettable
import pandas as pd
import sys
sys.path.append('..')
from lib import *
plt.style.use('../custom.mplstyle')
names = ['oneInsertion', 'twoInsertion']
agebinsize = 10.0
agebins = np.arange(0.0, 90.0, agebinsize)
bin_ts = agebins[:-1... | 1,931 | 837 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017 F5 Networks Inc.
# Copyright (c) 2016 Michael Perzel
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'... | 2,894 | 904 |
import unittest
import abcgan.constants as const
from abcgan import transforms as trans
import numpy as np
def fake_drivers(n):
return np.exp(np.random.normal(size=(n, const.n_driver)))
def fake_bvs(n):
return np.exp(np.random.normal(size=(n, const.max_alt, const.n_bv)))
class TestTransforms(unittest.Test... | 2,360 | 878 |
from __future__ import annotations
import csv
from typing import TYPE_CHECKING
from PySide2.QtCore import QObject
from PySide2.QtWidgets import QFileDialog, QMessageBox
from bsmu.bone_age.plugins.main_window import TableMenu
from bsmu.vision.core.plugins.base import Plugin
if TYPE_CHECKING:
from bsmu.bone_age.p... | 4,937 | 1,513 |
from ctypes import *
import os
import platform
import sys
# Load library
# use cdecl on unix and stdcall on windows
def ximc_shared_lib():
if platform.system() == "Linux":
return CDLL("libximc.so")
elif platform.system() == "FreeBSD":
return CDLL("libximc.so")
elif platform.system() == "Da... | 21,234 | 10,179 |
import sys
import os
import time
from datetime import datetime
from os.path import isfile, join, splitext, getsize, basename
from shutil import copyfileobj
from zipfile import ZipFile
from bad_request import bad_request
from utils import validate_dt
DEFAULT_DAT = 'last'
DEFAULT_EXT = 'xml'
def report(**kwargs):
... | 4,787 | 1,576 |
from django.shortcuts import render
from django.http import HttpResponse
from parsed_data.models import RatingData
import json
import datetime
import config
import operator
# Create your views here.
def getRating(request):
data = []
season = request.GET.get('season', False)
if season:
for r in Ra... | 16,428 | 5,627 |
# -*- coding: utf-8 -*-
def handler(event, context):
if event.get("name"):
return "Hello {}!".format(event.get("name"))
else:
return "Hello World!"
| 173 | 60 |
def maior(*valores):
if len(valores) >= 1:
maiorv = valores[0]
print(f'Analisando os valores...')
for c in valores:
print(c, end=' ')
if c > maiorv:
maiorv = c
print()
print(f'Foram informados {len(valores)} valores ao todo.')
p... | 507 | 199 |