text
string
size
int64
token_count
int64
def main(): with open("number.txt", "r") as file: data = file.read() data = data.split("\n") x = [row.split("\t") for row in data[:5]] print(function(x)) def function(x): sum=0 for el in x[0:]: sum += int(el[0]) return sum if __name__=="__main__": main();
307
133
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import ( BaseModel ) classes = [BaseModel] for c in classes: admin.site.register(c)
207
72
# Copyright 2013 UNED # # 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...
1,118
332
""" MongoEngine dependency provider """ from __future__ import absolute_import from .mongo_engine import MongoEngine __all__ = ["MongoEngine", ] # pragma: no cover
172
53
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' from PyQt5.QtWidgets import QWidget, QFormLayout, QComboBox, QSpinBox, QCheckBox from PyQt5.QtCore import QSettings, pyqtSignal from common import IMAGE_HASH_ALGO, DEFAULT_IMAGE_HASH_ALGO, DEFAULT_IMAGE_HASH_MAX_SCORE class SearchForSimilarSet...
1,717
606
from flask import Blueprint auth_blueprint = Blueprint( 'auth_blueprint', __name__, template_folder='templates' )
128
42
a = input() b= input() print(ord(a) + ord(b))
47
24
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright (c) 2017~2999 - cologler <skyoflw@gmail.com> # ---------- # # ---------- from pytest import raises from singletonify import singleton def test_base(): @singleton() class A: pass assert not A._is_init() assert A() is A() assert A...
1,571
556
from coinmarketcapapi import CoinMarketCapAPI, CoinMarketCapAPIError from pycoingecko import CoinGeckoAPI from vika.config import COIN_MARKET_CAP_API_KEY class Crypto: def __init__(self, api_key=None): self.coin_market_cap = CoinMarketCap(api_key=api_key) self.gecko = Gecko() def price(self,...
2,166
694
#!/usr/bin/env python """ cleanup and refactor -> pretty much a rewrite soundfonts are messy, you gotta kind of figure out where the note names and velocities are in sample name. usually the pitch info is wack """ from chunk import Chunk import logging import os import re import struct import wave logging.basicConfi...
7,440
2,840
import os import json import logging import requests logger = logging.getLogger('slack') logger.setLevel(logging.INFO) def notify(url, account, userName, existingAccessKey, accessKey=None, secretKey=None, instruction=None, deleteAfterDays=None): if accessKey is not None: # New key pair generated l...
4,126
1,008
""" Module defining structures useful to the core class and related methods """ import collections # http://xmpp.org/extensions/xep-0045.html#errorstatus ERROR_AND_STATUS_CODES = { '401': 'A password is required', '403': 'Permission denied', '404': 'The room doesn’t exist', '405': 'Your are not allowed...
1,509
508
from flask import Flask, request, jsonify from ..common import app, db, getJson from .model import User from .method import * @app.route("/api/user/register", methods=["POST"]) def register(): json = getJson() username = json['username'] password = json['password'] userId = addUser(username, password) ...
895
261
# ***** BEGIN LICENSE BLOCK ***** # Version: MPL 1.1/GPL 2.0/LGPL 2.1 # # The contents of this file are subject to the Mozilla Public License Version # 1.1 (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.mozilla.org/MPL/ # # Softwa...
4,326
1,350
from tsheets.model import Model from datetime import date, datetime class UserPermissionsSet(Model): pass UserPermissionsSet.add_field("admin", bool) UserPermissionsSet.add_field("mobile", bool) UserPermissionsSet.add_field("status_box", bool) UserPermissionsSet.add_field("reports", bool) UserPermissionsSet.add...
634
203
from backpack.core.derivatives.conv1d import Conv1DDerivatives from backpack.extensions.secondorder.diag_ggn.convnd import ( BatchDiagGGNConvND, DiagGGNConvND, ) class DiagGGNConv1d(DiagGGNConvND): def __init__(self): super().__init__(derivatives=Conv1DDerivatives(), params=["bias", "weight"]) c...
474
184
import subprocess import pytest import os import json def test_call_generate_promoter_terminator(): print('') process_result = subprocess.run(['python', 'generate_promoter_terminator.py', './test/1.gff.json', '500', '200'], \ capture_output=True) assert process_result.returncode == 0 ...
1,088
365
project_dm = 'dmgcp-ingestion-poc' location = 'US' bq_connection_id= 'my_gcp_connection'
89
39
# This file is part of the Reproducible and Reusable Data Analysis Workflow # Server (flowServ). # # Copyright (C) 2019-2021 NYU. # # flowServ is free software; you can redistribute it and/or modify it under the # terms of the MIT License; see LICENSE file for more details. """Unit tests for reading a workflow templat...
1,478
487
""" VF: Validation Functions (for Python dicts.) Copyright (c) 2020 Polydojo, Inc. SOFTWARE LICENSING ------------------ The software is released "AS IS" under the MIT License, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED. Kindly see LICENSE.txt for more details. NO TRADEMARK RIGHTS ------------------- The above...
4,058
1,245
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, validators from wtforms.fields.html5 import EmailField class RegisterForm(FlaskForm): firstname = StringField(u"Firstname", [validators.Length(min=2, max=256)]) lastname = StringField(u"Lastname", [validators.length(min=2, max=256)...
792
239
from setuptools import setup, find_packages version = '0.0.1' setup(name='mvvm', version=version, description='Model-View-ViewModel framework for Python, based on Wx', long_description=open('README.rst').read(), classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended...
823
243
from os import system, name system('cls' if name == 'nt' else 'clear') dsc = ('''DESAFIO 037: Escreva um programa que leia um número inteiro qualquer e peça para o usuário escolher qual será a base de conversão: - 1 para binário - 2 para octal - 3 para hexadecimal ''') n = int(input('Digite um número: ')) print('1: b...
603
234
# # Copyright (C) 2015, Stanislaw Adaszewski # s.adaszewski@gmail.com # http://algoholic.eu # # License: 2-clause BSD # from markdown import Extension from markdown.blockprocessors import BlockProcessor from markdown.util import etree import numpy as np from collections import defaultdict import numpy.core.defchararr...
4,234
1,440
from django.conf import settings from django.db.models.query import QuerySet from rest_framework import views from rest_framework.response import Response from AgronetApp.serializers import orderDetailSerializer from AgronetApp.serializers.orderDetailSerializer import OrderDetailSerializer from AgronetApp.models.orderD...
1,538
411
import tensorflow as tf import numpy as np from network import make_network from data_provider import DataProvider from tensorflow.core.protobuf import saver_pb2 import time import os from IPython import embed with tf.Session(config=tf.ConfigProto(log_device_placement=True)) as sess: network = make_network() ...
1,012
339
# Generated by Django 3.1.5 on 2021-01-18 01:17 from django.db import migrations, models import gdstorage.storage class Migration(migrations.Migration): dependencies = [ ('App0', '0018_auto_20210117_1820'), ] operations = [ migrations.AlterField( model_name='products', ...
494
176
from .duc_hdc import * from .fcn8s import * from .fcn8s_sphe import * from .u_net import * from .u_net_sphe import *
119
53
import os import unittest import importlib import logging import zipfile from nose.tools import raises from mock import patch, MagicMock import datman import datman.xnat import datman.scanid # Disable all logging for the duration of testing logging.disable(logging.CRITICAL) upload = importlib.import_module('bin.dm_...
4,422
1,807
""" The MIT License Copyright (c) 2017 OpenAI (http://openai.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify...
7,513
2,244
""" Corporation management paths """ from datetime import datetime from typing import Dict, Iterator, List, Optional from fastapi import APIRouter, Depends import pydantic as pdt from sni.esi.scope import EsiScope, esi_scope_set_to_hex from sni.esi.token import tracking_status, TrackingStatus from sni.uac.clearance ...
9,796
3,160
import requests import json from .Graph import Graph from .FactSheets import FactSheets from .Users import Users from .Metrics import Metrics from .Polls import Polls class LeanIX: def __init__(self,api_token="",workspaceid="",baseurl="https://us.leanix.net/"): """ Authenticates to LeanIX with the given A...
2,454
714
import os import numpy as np from constants import DATABASE_FILE_NAME, PLAYER_ONE, PLAYER_TWO, POSITION_TO_DATABASE from Agents.random import Random from othello import Othello import multiprocessing as mp class Database: def __init__(self): """ load database data and store them in self._db_data ...
5,752
1,636
import logging import math import time from typing import Dict, List from servo import Servo class ControllerForPCA9685: def __init__(self, servos: Dict[object, Servo], chs: Dict[object, int], pwm_freq: float, init_angles: Dict[object, float] = None): import Adafruit_PCA9685 as PCA9685 ...
5,114
1,686
def prastevila_do_n(n): pra = [2,3,5,7] for x in range(8,n+1): d = True for y in range(2,int(x ** 0.5) + 1): if d == False: break elif x % y == 0: d = False if d == True: pra.append(x) return pra def ...
990
433
args_global = ['server_addr', 'port', 'timeout', 'verbose', 'dry_run', 'conn_retries', 'is_server', 'rpc_plugin', 'called_rpc_name', 'func', 'client'] def strip_globals(kwargs): for arg in args_global: kwargs.pop(arg, None) def remove_null(kwargs): keys = [] for key, value in kwar...
785
264
from django.db import models from django.utils import timezone from django.contrib.auth.models import User # Create your models here. class Neighbor(models.Model) : n_name = models.CharField(max_length=35) n_location = models.CharField(max_length=35) n_image = models.ImageField(upload_to='n_posts/') n_title...
606
211
# SPDX-FileCopyrightText: 2021 Brent Rubell for Adafruit Industries # # SPDX-License-Identifier: MIT """ 'ir_sensor.py'. ================================================= control a LED with an IR Remote requires: - adafruit_irremote library """ import adafruit_irremote import board import digitalio import pulseio l...
1,237
426
from .heos import * __author__ = 'Nils Vogels' __version__ = '20180701'
71
33
import json; from pprint import pprint Settings = json.load(open('settings.txt')) import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np import sys sys.path.insert(0,'../') from pak.datasets.CMU_MoCap import CMU_MoCap import pak.datasets.CMU_MoCap as cmu data = CMU_MoCap(Settings['...
891
378
#!/usr/bin/env python3 """This python program deploys the files needed by the Hillview service on the machines specified in the configuration file.""" # pylint: disable=invalid-name from argparse import ArgumentParser import tempfile import os.path from hillviewCommon import ClusterConfiguration, get_config, get_l...
6,249
1,977
from distutils.core import setup from Cython.Build import cythonize setup(name="nbody", ext_modules=cythonize("nbody.pyx"))
126
44
from xv_leak_tools.log import L from xv_leak_tools.exception import XVEx from xv_leak_tools.test_components.firewall.firewall import Firewall class WindowsFirewall(Firewall): def __init__(self, device, config): super().__init__(device, config) from xv_leak_tools.network.windows.adv_firewall impor...
837
264
import urllib3 from beautifulsoup4 import beautifulsoup4 as bs def get_historical_data(name, number_of_days): data = [] url = "https://finance.yahoo.com/quote/" + name + "/history/" rows = bs(urllib3.urlopen(url).read()).findAll('table')[0].tbody.findAll('tr') for each_row in rows: divs = each_row.findAll('td')...
1,272
562
#!/usr/bin/python import os, glob, hashlib, pickle, argparse, shutil, ntpath import os, glob, hashlib, pickle, argparse, shutil, multiprocessing, signal, sys from multiprocessing import Pool from functools import partial ######################### Classes ############################## class AndroidDensity: def __i...
13,667
4,220
from django.db import models from django.contrib.postgres.fields import ArrayField # Create your models here. class Movie_Details(models.Model): name = models.CharField(max_length=100) year = models.IntegerField(default=0) boxoffice = models.BigIntegerField(default=0) imdb = models.IntegerField(de...
888
284
import os from djangular import utils from django.test import SimpleTestCase class SiteAndPathUtilsTest(SimpleTestCase): site_utils = utils.SiteAndPathUtils() def test_djangular_root(self): current_dir = os.path.dirname(os.path.abspath(__file__)) djangular_dir = os.path.dirname(current_dir)...
399
130
datasetFile = open("datasets/rosalind_ba1e.txt", "r") genome = datasetFile.readline().strip() otherArgs = datasetFile.readline().strip() k, L, t = map(lambda x: int(x), otherArgs.split(" ")) def findClumps(genome, k, L, t): kmerIndex = {} clumpedKmers = set() for i in range(len(genome) - k + 1): km...
816
291
from django.conf.urls import patterns, include, url from django.contrib import admin from django.conf.urls.static import static from userModule.views import home from userModule.views import userSettings from userModule.views import logout from groupModule.views import createGroup from groupModule.views import group fr...
1,790
650
from encoded.searches.mixins import CartAggsToFacetsMixin from snosearch.responses import BasicQueryResponseWithFacets from snosearch.responses import BasicMatrixResponseWithFacets class CartQueryResponseWithFacets(CartAggsToFacetsMixin, BasicQueryResponseWithFacets): ''' Like BasicQueryResponseWithFacets but...
858
282
# License: Apache 2.0. See LICENSE file in root directory. # Copyright(c) 2021 Intel Corporation. All Rights Reserved. # test:device L500* # test:device D400* import pyrealsense2 as rs from rspy.stopwatch import Stopwatch from rspy import test, log import time import platform # Start depth + color streams and measur...
4,215
1,321
def setenv(config_root, config_name=None, bypass_config_lookup=None): import os, inspect, pathlib, sys if bypass_config_lookup: os.environ['origen_bypass_config_lookup'] = "1" if config_name is None: config_name = inspect.stack()[1].function os.environ['origen_config_paths'] = str( ...
379
127
from rest_framework import serializers from example.models import MyPublicModel, MyPrivateModel, MyPresenceModel class MyPublicModelSerializer(serializers.ModelSerializer): class Meta: model = MyPublicModel fields = ("name",) class MyPrivateModelSerializer(serializers.ModelSerializer): clas...
525
135
class Token: def __init__(self, word, line, start, finish, category, reason=None): self.__word__ = word self.__line__ = line self.__start__ = start self.__finish__ = finish self.__category__ = category self.__reason__ = reason @property def word(self): ...
1,164
343
from tensorflow.keras import activations, initializers, regularizers, constraints from tensorflow.keras import backend as K from tensorflow.keras.layers import Layer from spektral.layers import ops from spektral.utils import localpooling_filter class GraphConv(Layer): r""" A graph convolutional layer (GCN) a...
5,033
1,403
Test Dummy code to make commit
31
10
#!/usr/bin/env python3 """ Description: pyBirdcagebuilder is a program that calculates ideal capacitor values for birdcage coil designs. This program is based on the original Birdcage Builder program provided by PennState Health. (https://research.med.psu.edu/departments/center-for-nmr-research/software/birdca...
28,488
12,619
from poetry.semver.constraints.constraint import Constraint from poetry.semver.constraints.multi_constraint import MultiConstraint def test_multi_version_match_succeeds(): require_start = Constraint('>', '1.0') require_end = Constraint('<', '1.2') provider = Constraint('==', '1.1') multi = MultiConst...
1,057
355
from rest_framework import serializers from teryt_tree.rest_framework_ext.serializers import JednostkaAdministracyjnaSerializer from .models import RESP, REGONError, REGON, JSTConnection, Institution, ESP class RESPSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = RESP field...
1,683
508
import warnings from math import isnan import numpy as np from scipy import integrate from ross.fluid_flow.fluid_flow_geometry import move_rotor_center def calculate_oil_film_force(fluid_flow_object, force_type=None): """This function calculates the forces of the oil film in the N and T directions, ie in the ...
21,950
7,260
from django.contrib import admin from .models import Device,Metric class DeviceAdmin(admin.ModelAdmin): list_display = ["name", "token","user", "created_date"] search_fields = ["name", "token"] list_filter = ("user",) class MetricAdmin(admin.ModelAdmin): list_display = ["device","temperature", "humid...
486
150
import time import numpy as np import gc a=[] start=time.time() for i in range(10000000): a.extend([[i,i+1,i+2]]) end=time.time() print(end-start) a=[] start=time.time() for i in range(10000000): a.append([i,i+1,i+2]) end=time.time() print(end-start) a=[] start=time.time() gc.disable() for i in range(1000000...
1,071
495
"""added upload table Revision ID: a45942d815f Revises: 1de13fd625b1 Create Date: 2016-03-07 12:00:50.283535 """ # revision identifiers, used by Alembic. revision = 'a45942d815f' down_revision = '1de13fd625b1' from alembic import op import sqlalchemy as sa def upgrade(): ### commands auto generated by Alembic...
818
316
from django.urls import reverse from pytest import mark from core.models import * urls = [reverse(name) for name in ["core:index", "core:arts"]] @mark.parametrize("url", urls) @mark.django_db def test_nsfw_filter(url, django_user_model, client): target = django_user_model.objects.create(username="bob", password...
956
335
# Node types TYPE_NODE = b'\x10' TYPE_NODE_NR = b'\x11' # Gateway types TYPE_GATEWAY = b'\x20' TYPE_GATEWAY_TIME = b'\x21' # Special types TYPE_PROVISIONING = b'\xFF'
168
84
"""This script *replaces* the processlog.csh shell script. It has more sophisticated logic to add the etc test name to the pysynphot command as another keyword-value pair. Modified to parse the modified line, then write a dictionary that will be read by the gencases tool. """ import sys,re, pickle from pysynphot impo...
1,232
389
import torch # import time # from torch_scatter import scatter # Maybe see if this is good: https://github.com/rusty1s/pytorch_scatter # My implementation is quite suboptimal # def time_fun(f, iter, *args): # start_time = time.perf_counter() # start = time.time() # for i in range(iter): # f(*args)...
5,561
1,931
import teek def on_click(): print("You clicked me!") window = teek.Window() button = teek.Button(window, "Click me", command=on_click) button.pack() window.on_delete_window.connect(teek.quit) teek.run()
211
79
import abc from typing import overload, Optional, Union, Dict, List, Tuple, Callable, TYPE_CHECKING import numpy as np from ...math import ndarray from ...score import NamedScore if TYPE_CHECKING: from ...types import T, ArrayType from ... import Document, DocumentArray class FindMixin: """A mixin tha...
5,378
1,470
import os from subprocess import check_call, call def write_service(service_name, contents): """Write a service file in a "safe" manner. If the contents of the file are the same as what is desired to be written, do nothing. First writes to a temporary file in the same directory as the target, the...
1,569
452
import struct def double_to_raw_long_bits(frame): """ public static native long doubleToRawLongBits(double value); """ value = frame.get_local_double(0) b = struct.pack("d", value) i = struct.unpack("l", b)[0] frame.push_operand_long(i) def long_bits_to_double(frame): """ public ...
512
185
from django.contrib import admin from .models import Post, Material, Video, Section # Register your models here. admin.site.register(Post) admin.site.register(Section) admin.site.register(Material) admin.site.register(Video)
224
62
# -*- coding: utf-8 -*- """ Created on Wed Dec 4 13:54:27 2019 @author: eric.qian """ from collections import Counter from itertools import combinations # Numeric hand rankings, higher integer value is stronger hand HAND_RANKINGS = {0: 'High Card', 1: 'One Pair', 2: 'T...
6,493
2,338
from pytest import fixture, raises from py61850.types import Boolean @fixture def true(): return Boolean(True) # === DECODE === def test_byte_true_min_raw_value(): assert Boolean(b'\x01').raw_value == b'\x01' def test_byte_true_min_value(): assert Boolean(b'\x01').value is True def test_byte_true_...
1,713
642
#!/usr/bin/env python import sys with open(sys.argv[1], 'r') as f: for line in f.readlines(): sys.stdout.write(line)
129
48
import sublime import sublime_plugin import datetime import re from pathlib import Path import os import fnmatch import OrgExtended.orgparse.loader as loader import OrgExtended.orgparse.node as node import OrgExtended.orgparse.date as orgdate from OrgExtended.orgparse.sublimenode import * import OrgExtended.orgutil....
40,539
13,060
from magma import * from magma.verilator.verilator import compile as compileverilator from mantle.verilog.gates import And, XOr def f(a, b, c): return (a & b) ^ c #main = DefineCircuit('main', "a", In(Bit), "b", In(Bit), "c", In(Bit), "d", Out(Bit), 'CLK', In(Bit)) main = DefineCircuit('main', "a", In(Bit), "b", ...
526
225
from nt import DirEntry import os import self as self from keras import Model as KerasModel class Model(object): """ Base class for the different models in this project """ _files: dict = {} """ The files that is used to parse the model """ _raw_content: str = '' """ The files contents ...
3,908
1,071
""" The Fitbit API breaks from the OAuth2 RFC standard by returning an "errors" object list, rather than a single "error" string. This puts hooks in place so that oauthlib can process an error in the results from access token and refresh token responses. This is necessary to prevent getting the generic red herring ...
930
274
#!/usr/bin/env python # encoding: utf-8 """ merge_intervals.py Created by Shengwei on 2014-07-07. """ # https://oj.leetcode.com/problems/merge-intervals/ # tags: medium, array, interval """ Given a collection of intervals, merge all overlapping intervals. For example, Given [1,3],[2,6],[8,10],[15,18], return [1,6],...
1,609
510
# coding=utf-8 import re import traceback from pesto_common.config.configer import Configer from pesto_common.log.logger_factory import LoggerFactory from pesto_orm.core.base import db_config from pesto_orm.core.executor import ExecutorFactory from pesto_orm.core.model import BaseModel from pesto_orm.core.repository i...
3,495
1,036
import os import re import unittest import shutil import subprocess import logging import zipfile from io import BytesIO from ..experiment.file_storage_driver import FileStorageDriver from ..experiment.experiment_reader import ExperimentReader from ..experiment.experiment_writer import ExperimentWriter class Experim...
10,454
3,299
from __future__ import print_function import os from argparse import ArgumentParser, Namespace from zope.interface import implementer from quickmail.commands import ICommand from quickmail.utils.misc import quick_mail_dir, heavy_tick, quick_mail_template_dir @implementer(ICommand) class ClearCommand: def add_arg...
1,806
491
class Node: def __init__(self, value): self.value = value self.next = None # Have no idea how to do this # import sys # sys.path.insert(0, '../../data_structures') # import node def intersection(l1: Node, l2: Node) -> Node: l1_end, len1 = get_tail(l1) l2_end, len2 = get_tail(l2) if l...
1,247
487
import os import pytest from bank_bot.banking_system import Database class MockMessage(object): def __init__(self, from_who, chat_id, message_text): self.json = {"from": {"id": from_who}, "chat": {"id": chat_id}} self.text = message_text @pytest.fixture def database(): test_file_path = "test_d...
550
179
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-04-08 10:32 from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('users', '0003_myuser_has_image'), ] operations = [ ...
673
220
""" Description: - Test Template class. Methods: - test setup - test teardown - test implementation @author: Paul Bodean @date: 26/12/2017 """ import unittest from selenium import webdriver class TestTemplate(unittest.TestCase): def setUp(self): """ Open the page to be tested ...
582
179
"""Tests for profiles module.""" import mock from google.apputils import basetest import profiles class ProfilesModuleTest(basetest.TestCase): def testGenerateUUID(self): self.assertIsInstance(profiles.GenerateUUID('a'), str) self.assertTrue(profiles.GenerateUUID('a').isupper()) self.assertEqual(pro...
14,940
5,138
# NAVI AND MATH def power(base, exp): res = 1 while exp>0: if exp&1: res = (res*base)%1000000007 exp = exp>>1 base = (base*base)%1000000007 return res%1000000007 mod = 1000000007 for i in range(int(input().strip())): ans = "Case #" + str(i+1) + ': ' N = int(inpu...
835
353
from typing import * from dataclasses import asdict from transformers import BertModel from torch.nn.utils.rnn import pad_sequence from stud.models.ner_classifier import NERClassifier from stud.models.polarity_classifier import PolarityClassifier from stud.constants import LOGGER_TRAIN_LOSS, LOGGER_VALID_LOSS, LOGGER_T...
10,241
3,391
import argparse import json import os.path import random import re import time import cv2 import numpy as np import requests from PIL import Image from config import config class GermanLicensePlateImagesGenerator: def __init__(self, output): self.output = output self.COUNTRY_MARKS = np.asarray([...
4,596
1,632
# -*- coding:utf8 -*- import os from eth_account import Account import sha3 import base64 import hashlib from ecdsa import SigningKey, SECP256k1 DID_TYPE = ["weid"] def create_privkey(): return os.urandom(32) def create_ecdsa_privkey(): return SigningKey.generate(curve=SECP256k1) def create_random_weid(): ...
4,697
1,764
import os from .abstract_command import AbstractCommand from ..services.state_utils import StateUtils from ..services.state import StateHolder from ..services.command_handler import CommandHandler from ..services.console_logger import ColorPrint class Start(AbstractCommand): command = ["start", "up"] args = ...
1,969
529
class LastStoneWeight: """ https://leetcode-cn.com/problems/last-stone-weight/ """ def lastStoneWeight(self, stones: List[int]) -> int:
172
62
from netfilterqueue import NetfilterQueue import socket from os import system import scapy.all as scapy import scapy_http.http from urllib.parse import urlparse, parse_qs REQUEST_LOGIN = 0 REQUEST_PROTECT = 1 class NetGuardMITM: def __init__(self, ip, queue_number=1): self.ip = ip self.queue_nu...
8,098
2,226
"""Config options for WDRAX. Gets settings from environment variables or .env/settings.ini file. """ import pathlib from decouple import AutoConfig BASE_DIR = pathlib.Path(__name__).absolute().parent config = AutoConfig(search_path=str(BASE_DIR)) # pylint: disable=invalid-name LOG_LEVEL = config('LOG_LEVEL', defa...
1,660
625
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, t...
3,066
1,068
# coding: utf-8 # /*########################################################################## # # Copyright (c) 2016 European Synchrotron Radiation Facility # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal #...
9,595
2,960
class Manifest: def __init__(self, definition: dict): self._definition = definition def exists(self): return self._definition is not None and self._definition != {} def _resolve_node(self, name: str): key = next((k for k in self._definition["nodes"].keys() if name == k.split(".")[-...
790
223
print('=====================') print(' 10 Termos de um PA') print('=====================') p = int(input('Primeiro Termo: ')) r = int(input('Razão: ')) for loop in range(p, ((r * 10) + p), r): print('{} ->' .format(loop), end=' ') print('Acabou')
252
98