text
string
size
int64
token_count
int64
# Standard Library import logging import os import socket import sys from collections import defaultdict # First Party from smdebug.core.config_constants import LOG_DUPLICATION_THRESHOLD _logger_initialized = False class MaxLevelFilter(logging.Filter): """Filters (lets through) all messages with level < LEVEL""...
3,562
1,064
# -*- coding: utf-8 -*- # Scrapy settings for scrapper project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/lates...
15,883
6,732
# # This file is part of datacube-classification # Copyright (C) 2021 INPE. # # datacube-classification Library is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # """classification models module""" import pandas as pd def train_sklear...
1,292
368
#!/usr/bin/env python # -*- coding: utf-8 -*- from redis import StrictRedis from HeartbeatMaker import HeartbeatMaker import arrow def test(it): print('%s:%s:心跳' % (arrow.now(), it)) maker = HeartbeatMaker('redis://localhost:6379/0', 'test-beat', test) # maker.clean() # maker.beat_it('bac', 6,'bac-par') # mak...
421
190
# Copyright 2021 RushanNotOfficial#1146. All Rights Reserved. # # 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 applica...
2,304
564
"""File containing a class for the main gauge.""" from tkinter import font, Label, Frame from classes.widgets.main_gauge import MainGauge from classes.pub_sub import Subscriber class EngineGauge(MainGauge, Subscriber): """ A gauge that displays the speed, acceleration and average speed. """ def __...
1,076
318
from .core import ( mean, sum, exp, sin, cos, tan, log, tensor, grad_tensor, zeros, ones, randn, rand, Tensor, argmax, ) from .linear import Linear from .model import Module, Sequential from .sampler import TensorSample
280
99
from eth_tester.exceptions import TransactionFailed from utils import captureFilteredLogs, AssertLog, nullAddress, TokenDelta, PrintGasUsed from pytest import raises, mark pytestmark = mark.skip(reason="We might not even need governance and currently dont account for transfering ownership") def test_gov(contractsFixt...
4,358
1,572
# terrascript/resource/hashicorp/ad.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:10:57 UTC) import terrascript class ad_computer(terrascript.Resource): pass class ad_gplink(terrascript.Resource): pass class ad_gpo(terrascript.Resource): pass class ad_gpo_security(terrascript.Res...
700
279
import sys from utils import my_train, flickr_train_params, flickr_params, my_test, copy_networks if __name__ == "__main__": do_import = True first_arg = sys.argv[0] if do_import: copy_networks(model_to_import="celeba_cycle", iter="2") flickr_train_params["continue_train"] = True ...
557
204
#!/usr/bin/env python import sys import platform from setuptools import setup # from Cython.Build import cythonize def get_version(): with open("pymorphy2/version.py", "rt") as f: return f.readline().split("=")[1].strip(' "\n') # TODO: use environment markres instead of Python code in order to # allow b...
3,153
1,081
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import hashlib import os import os.path as osp import pickle import time import attr import gym import magnum as mn imp...
8,031
2,812
############### ## LIBRARIES ## ############### import click from copy import deepcopy from pprint import pprint from arcgis.gis import GIS from arcgis import features import geopandas as gpd ################## ## FUNCTION(S) ## ################## def agol_to_gdf(fset): gdf = gpd.read_file(fset.to_geojson) g...
3,614
1,258
# PyOS # Made for Python 2.7 # programs/mv.py # Import Libraries # PyOS Scripts import internal.extra import os from programs.cp import displayCwdFiles, getFileOrigin def app(): print(internal.extra.colors.OKGREEN + "Moving (renaming) files: " + internal.extra.colors.ENDC) print(internal.extra.colors.BOLD + ...
1,646
525
""" 382. Linked List Random Node Given a singly linked list, return a random node's value from the linked list. Each node must have the same probability of being chosen. Implement the Solution class: Solution(ListNode head) Initializes the object with the integer array nums. int getRandom() Chooses a node ran...
1,867
580
from datetime import timedelta from uuid import uuid1 from snuba.redis import redis_client from snuba.subscriptions.data import SubscriptionData from snuba.subscriptions.store import RedisSubscriptionDataStore from tests.subscriptions import BaseSubscriptionTest class TestRedisSubscriptionStore(BaseSubscriptionTest)...
3,003
877
import pytest from app.broadcast_areas.models import CustomBroadcastAreas from app.models.broadcast_message import BroadcastMessage from tests import broadcast_message_json @pytest.mark.parametrize('areas, expected_area_ids', [ ({'simple_polygons': []}, []), ({'ids': ['123'], 'simple_polygons': []}, ['123'])...
3,833
1,391
#coding:utf-8 """ 对处理数据域的抽象 """ from torchtext.data.field import RawField, Field, LabelField class WordField(Field): """ 数据词域的抽象 """ def __init__(self, **kwarg): print(kwarg) super(WordField, self).__init__(**kwarg) class CharField(Field): """ 数据字符域的抽象 """ def __init__...
521
221
from __future__ import print_function, division from warnings import warn from nilmtk.disaggregate import Disaggregator import pandas as pd import numpy as np from collections import OrderedDict import matplotlib.pyplot as plt from sklearn.decomposition import MiniBatchDictionaryLearning, SparseCoder from sklearn.met...
9,460
2,901
def test_with_missing_fixture(not_existing_fixture): pass
62
23
from plugins import PluginUtil from plugins.task_affinity import TaskAffinityPlugin plugin = TaskAffinityPlugin() def test_regex(): text ='intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);' assert PluginUtil.contains(plugin.NEW_TASK, text) def test_regex1(): text = 'intent.setFlags(Intent.FLAGACTIVITYNEWTA...
1,099
413
from __future__ import print_function import pyzbar.pyzbar as pyzbar import numpy as np import cv2 class QRdetect: def __init__(self, QRcode_image, k=np.array([[376.0, 0, 376], [0, 376.0, 240.0], [0, 0, 1]])): if QRcode_image is None: return self.query_image = QRcode_image s...
7,033
2,328
import unittest from app.models import User,Role,Post,Comment class CommentModelTest(unittest.TestCase): def setUp(self): self.new_user=User(name="Francis Githae",username='fgithae',password='password',email="francis@gmail.com",role=Role.query.filter_by(id=1).first()) self.new_post=Post(user=self.new_user,t...
1,124
377
import logging import os class Logger(object): """ set logger """ def __init__(self, logger_path): self.logger = logging.getLogger() self.logger.setLevel(logging.DEBUG) self.logfile = logging.FileHandler(logger_path) # self.logfile.setLevel(logging.DEBUG) ...
881
276
from state import print_solution_path from search import BBS, A_star_search from puzzle import generate from write_to_file import write_to_csv, write_to_txt ''' CS461 - Artificial Intelligence Homework 3 Group members: * Fuad Aghazada * Can Özgürel * Çağatay Sel * Utku Mert Top...
1,429
522
import ccxt from datetime import datetime from datetime import timedelta import calendar import time from enum import Enum import ccxtWrapper import math import LineNotify import orderInfo class orderManagementEnum(Enum): NO_POSITION = 0 HAVE_POSITION = 1 class orderManager(ccxtWrapper.ccxtWrapper): or...
6,224
2,172
import os from lxml import html import requests def get_dir_list(path): return [p for p in os.listdir(path) if os.path.isdir(p)] def get_file_list(path): return [p for p in os.listdir(path) if os.path.isfile(p)] def get_number(str): res = ''.join(list(filter(lambda x: '0'<=x<='9', str))) if res: ...
1,917
714
from utilidadesCeV import moeda preco = float(input('Digite o preço: R$')) porcentagem = float(input('Digite a aliquota:')) print(f'A metade de {moeda.moeda(preco)} é {moeda.metade(preco, True)}') print(f'O dobro de {moeda.moeda(preco)} é {moeda.dobro(preco, True)}') print(f'Aumentando {moeda.moeda(preco)} em {porcen...
488
202
# Generated by Django 3.0.3 on 2021-05-07 01:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('leagues', '0014_rotomultileagues_is_active'), ] operations = [ migrations.AddField( model_name='rotomultileagues', n...
449
154
# Copyright (c) 2020 Chris ter Beke. # Thingiverse plugin is released under the terms of the LGPLv3 or higher. import logging from typing import List, Callable, Any, Tuple, Optional from abc import ABC, abstractmethod from PyQt5.QtCore import QUrl from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkReply, QNetw...
7,329
1,969
from . import test_conversion from . import test_generic from . import test_idxgz from . import test_settings
110
31
import subprocess import time import os import sys def generate_el_commands(kernel): commands = [] if (kernel == "TC"): sym_test = [True] else: sym_test = [True, False] for symmetrize in sym_test: for npes in range(2,6): for v in [9,14]: for e in [8,9,11,...
2,545
899
import numpy as np from kneeOsteoarthritisDataset.KneeOsteoarthritsDataset import KneeOsteoarthritsDataset data_path = '/home/biomech/Documents/OsteoData/KneeXrayData/ClsKLData/kneeKL299' kneeosteo = KneeOsteoarthritsDataset(data_path = data_path) imgs, labels = kneeosteo.load_imgs() rand_idx = np.random.randint(lo...
504
219
print("SD bootloader") import pycom import time import machine import sys import uos #paths for the code/lib/mount locations SD_MOUNTPOINT = '/sd' CODE_PATH = '/sd/src' LIB_PATH = '/sd/src/lib' #LED colors #for errors (full brightness) C_YELLOW = 0xffff00 C_RED = 0xff0000 C_PURPLE = 0xff00ff C_BLUE = 0x0000ff #for n...
1,551
622
import os import sys import copy from math import gcd from driver_config_macros import * from data_capture_macros import * from signal_generator_macros import * from power_operation_macros import * from capture_config_macros import * from trig_config_macros import * from data_processing_macros import * from PyQt5 impor...
122,321
38,537
import cgroup_parser def test_interface(): cgroup_parser.get_max_procs() cgroup_parser.get_cpu_usage() cgroup_parser.get_memory_limit() cgroup_parser.get_memory_usage()
187
68
# Copyright 2022 Huawei Technologies Co., Ltd # # 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...
5,123
1,678
# -*- coding: utf-8 -*- # ******************************************************** # Author and developer: Aleksandr Suvorov # -------------------------------------------------------- # Licensed: BSD 3-Clause License (see LICENSE for details) # -------------------------------------------------------- # Url: https://git...
1,295
387
from hallo.events import EventMessage, EventMode from hallo.server import Server from hallo.test.server_mock import ServerMock def test_deop_not_irc(hallo_getter): test_hallo = hallo_getter({"channel_control"}) serv1 = ServerMock(test_hallo) serv1.name = "test_serv1" serv1.type = "NOT_IRC" test_ha...
39,647
15,821
from base64 import b64encode from flask import Flask, jsonify, request from functools import reduce from gevent import subprocess, pywsgi, queue, socket, spawn, lock from gevent.subprocess import CalledProcessError from hashlib import sha512 from pathlib import Path from tempfile import mkstemp import json import os im...
7,685
2,583
import datetime import math import random import time from ..users.models import User def generate_random_time(): min_time = datetime.datetime(year=2021, month=1, day=1) max_time = datetime.datetime(year=2021, month=3, day=31) min_time_ts = int(time.mktime(min_time.timetuple())) max_time_ts = int(ti...
1,050
446
import dataclasses import enum import typing from vkmodels.bases.object import ObjectBase class Fields(str, enum.Enum): ID = "id" TITLE = "title" ADDRESS = "address" ADDITIONAL_ADDRESS = "additional_address" COUNTRY_ID = "country_id" CITY_ID = "city_id" METRO_STATION_ID = "metro_station_i...
525
204
import curifactory as cf import json import os import pytest from stages.cache_stages import filerefcacher_stage, filerefcacher_stage_multifile # TODO: necessary? configured_test_manager already does this @pytest.fixture() def clear_stage_run(configured_test_manager): ran_path = os.path.join(configured_test_mana...
3,413
1,147
import urllib import time from multiprocessing.dummy import Pool as ThreadPool excelFolder = 'F://SecExcelDownload2/' compListUrl = 'C://Users/l1111/Desktop/AlphaCapture/downloadFileUrl.txt' successFile = excelFolder+'/success.txt' failFile = excelFolder+'/fail.txt' logFile = excelFolder+'/log.txt' def getAlreadyDo...
2,471
786
#/* # * Copyright 2016 -- 2021 IBM Corporation # * # * 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 applic...
20,495
6,188
import json import re import random def stopfilter(word): if word[0] == '@' or word.startswith('http'): return False return True class NGram(object): __slots__ = ['wordindex', 'size', 'punct', 'chain'] def __init__(self, size=2): self.wordindex = {} self.chain = {} ...
2,961
1,008
import os from mir.scm.cmd import CmdScm from mir.tools.code import MirCode from mir.tools.errors import MirRuntimeError def Scm(root_dir: str, scm_executable: str = None) -> CmdScm: """Returns SCM instance that corresponds to a repo at the specified path. Args: root_dir (str): path t...
967
316
""" Software: LingFeat - Comprehensive Linguistic Features for Readability Assessment Page: utils.py License: CC-BY-SA 4.0 Original Author: Bruce W. Lee (이웅성) @brucewlee Affiliation 1: LXPER AI, Seoul, South Korea Affiliation 2: University of Pennsylvania, PA, USA Contributing Author: - Affiliation : - """ import re i...
724
269
# Generated by Django 3.2.8 on 2021-10-31 23:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("pretix_eventparts", "0006_alter_eventpart_name"), ] operations = [ migrations.AlterField( model_name="eventpart", na...
416
141
# Usage: # python bwfilter.py --input=./data/test1.jpg import cv2 import numpy as np import argparse def parse_args(): parser = argparse.ArgumentParser(add_help=True, description='testing B&W filter') required_named = parser.add_argument_group('required named arguments') required_named.add_argument('-...
1,173
492
from networkx import DiGraph from pytest import fixture from resotolib.graph.graph_extensions import dependent_node_iterator @fixture def graph() -> DiGraph: g = DiGraph() for i in range(1, 14): g.add_node(i) g.add_edges_from([(1, 2), (1, 3), (2, 3)]) # island 1 g.add_edges_from([(4, 5), (4,...
1,065
439
from django.contrib.auth.models import AbstractUser from django.db import models from django.urls import reverse class User(AbstractUser): location = models.CharField(max_length=100, null=True) NOT_CHOSEN = 'N' MALE = 'M' FEMALE = 'F' GENDERS = ( (NOT_CHOSEN, 'Not Chosen'), (MALE,...
693
241
#!/usr/bin/env python3.4 import functools @functools.total_ordering class CrossSum: def __init__(self, digits, total=0, addends=''): self._digits = digits self._base = len(digits) self.total = total self.addends = addends def _convert_total(self): num_total = self.tot...
3,806
1,297
import base64 import re def encode(text): return base64.b64encode(text.encode("ASCII")).decode() def enhanceText(text): text = text.replace('.', '.', text.count('.')).replace(',', ', ', text.count(',')) text = " ".join(text.split()).replace(" . ", ". ") return text def stylish_text(text): text...
1,177
561
# may 30 20 def max_sub_array_of_size_k(k, arr): # TODO: Write your code here windowStart, currSum, maxSum = 0,0,0 for endIndex in range(len(arr)): currSum += arr[endIndex] if endIndex - windowStart + 1 > k: currSum -= arr[windowStart] windowStart+=1 # had this in while...most cases its...
377
139
import xlwings as xw import random import pandas as pd @xw.func @xw.arg('num_periods', numbers=int) @xw.ret(expand='table') def n_random_normal(mean, stdev, num_periods, horizontal=False): random_values = [] for i in range(num_periods): num = random.normalvariate(mean, stdev) if not ...
1,697
656
# -*- coding: UTF-8 -*- import ConfigParser import os import inspect class Settings(): __default_conf_name = 'example.conf' __conf = {} def __init__(self, filename=False): """ Create config object, read config data from file and make friendly format ot access to config d...
1,547
440
from .detection import FDetector from .haar_detector import HaarDetector from .hog_detector import Hog_detector from .mtcnn_detector import MTCNNDetector from .dnn_detector import DnnDetector
192
66
import torchvision.datasets as datasets from torch.utils.data import Dataset from itertools import combinations import math import psutil class CombinationDataset(Dataset): def __init__(self, dataset): self.dataset = dataset self.comb = list(combinations(dataset, 2)) def __getitem__(self, ind...
4,635
1,423
# iaga.utils # Utility functions and helpers # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: Wed Aug 08 12:00:44 2018 -0400 # # ID: utils.py [] benjamin@bengfort.com $ """ Utility functions and helpers """ ########################################################################## ## Imports ########...
2,160
638
'''Faça um programa que receba dois números, compare e diga quem é maior. Mostrando a msn qual valor é maior ou menor. OU diga que os valores são iguais.''' print('=+=+=+=+=+=+=+=+='*3) titulo = 'COMPARANDO NÚMEROS MAIOR, MENOR E IGUAL' print('{:^51}'.format(titulo)) print('-----------------'*3) num1 = float(input('Dig...
760
313
def spam(): global eggs eggs = "spam" # this is the global var def bacon(): eggs = "bacon" # this is a local var def ham(): print(eggs) # this is the global var eggs = 42 # this is the global var spam() print(eggs)
234
86
# Copyright © 2017-2019 Cedric Legrand # # 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, merge, publish, d...
19,761
6,227
# -*- coding: utf-8 -*- """ 04_Tutorial_Boolean """ # In this tutorial we learn how to do boolean operations between groups of # polygons # Let's import basic stuff import samplemaker.layout as smlay # used for layout import samplemaker.makers as sm # used for drawing # Create a simple mask layout themask = smlay...
1,859
743
from tabulate import tabulate def make_table(series_data): table = tabulate(series_data, headers='keys', tablefmt='github') return table def make_data_table_footer(series_metadata): table = tabulate(series_metadata, headers='keys') return table
265
79
"""Test cvejob.version.BenevolentVersion.""" from cvejob.version import BenevolentVersion def test_version_basic(): """Test basic behavior.""" assert BenevolentVersion('1') == BenevolentVersion('1') assert BenevolentVersion('1') != BenevolentVersion('2') assert BenevolentVersion('1') < BenevolentVersi...
2,472
912
#!/bin/python3 import math import os import random import re import sys import string if __name__ == '__main__': try: t = int(input().strip()) except: print('Invalid input.') if t>=1 and t<=10: for a0 in range(t): s = input().strip() index = 0 ...
1,211
326
import sublime, sublime_plugin import os import json class FindAndReplaceByProjectWithExclusions(sublime_plugin.TextCommand): print('reloading FindAndReplaceByProjectWithExclusions') def run(self, edit, from_current_file_path=None): # Текущее окно сублайма window = self.view.window() # В окне - прое...
2,377
781
# Schnell Nautilus Extension # # Place me in ~/.local/share/nautilus-python/extensions/, # ensure you have python-nautilus package, restrart Nautilus, and enjoy :) from gi import require_version require_version('Gtk', '3.0') require_version('Nautilus', '3.0') from gi.repository import Nautilus, GObject from subprocess...
1,566
474
# Generated by the pRPC protocol buffer compiler plugin. DO NOT EDIT! # source: service.proto import base64 from google.protobuf import descriptor_pb2 # Includes description of the service.proto and all of its transitive # dependencies. Includes source code info. FILE_DESCRIPTOR_SET = descriptor_pb2.FileDescriptorS...
74,548
54,993
from pymongo import MongoClient import random as r import os client = MongoClient(os.environ["MONGO_LAB"]) db = client.get_database("hetmanbot") collection = db['data_base'] class StaticMethods(): @staticmethod def push_record(name, txt, number): records = collection.find_one({"document_id": number}) ...
1,891
566
from django.contrib import admin # Register your models here. from . import models from .models import Article, Comment class ArticleAdmin(admin.ModelAdmin): fieldsets = [ (None, {'fields': ['id']}), (None, {'fields': ['title', 'content', 'status']}) ] list_display = ( ['expire_time',...
702
234
# - * - coding: utf-8 - * - import numpy as np import pandas as pd import matplotlib.pyplot as plt import scipy.signal from ..signal import signal_smooth from ..signal import signal_zerocrossings def ecg_findpeaks(ecg_cleaned, sampling_rate=1000, method="neurokit", show=False): """Find R-peaks in an ECG signal...
32,545
12,299
import inspect import sys from enum import IntEnum from tflite.ActivationFunctionType import ActivationFunctionType from tflite.BuiltinOperator import BuiltinOperator # In Python 3.6, we cannot make ExtendedOperator derive from IntEnum if sys.version_info >= (3, 7): bases = (IntEnum, ) else: bases = () cla...
1,157
387
PACKAGE_NAME = 'mkdocs_markmap' PROJECT_NAME = PACKAGE_NAME.replace('_', '-') PROJECT_VERSION = '2.1.3' OWNER = 'neatc0der' REPOSITORY_NAME = f'{OWNER}/{PROJECT_NAME}'
169
78
from django.conf.urls import url from rest_framework.routers import DefaultRouter from apps.homes import views urlpatterns = [ url(r'^areas/$', views.AreaAPIView.as_view()), # url(r'^houses/$', views.HouseAPIView.as_view()), # 我的房屋列表 url(r'^user/houses/$', views.HouseListView.as_view()), # 首页房屋模块 ...
852
352
class Rules: def __init__(self): self.ONE_ONE_SCORE = 100 self.ONE_FIVE_SCORE = 50 self.STRAIGHT_SCORE = 1500 self.THREE_PAIR_SCORE = 1000 class Alternate(Rules): def __init__(self): self.STRAIGHT_SCORE = 2500 self.THREE_PAIR_SCORE = 2000
294
148
import socket import ssl import sys hostname = '127.0.0.1' if len(sys.argv) < 2: exit(0) inputfile = sys.argv[1] print('\tRead file %s' % inputfile) # msg = b"HEAD / HTTP /1.0\r\nHost: linuxfr.org\r\n\r\n" msg = open(inputfile).read() msg = bytes(msg.encode()) context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) con...
646
261
class Solution: def removeDuplicates(self, s: str, k: int) -> str: """Stack. Running time: O(n) where n is the length of s. """ st = [['#', 0]] for c in s: if st[-1][0] == c: st[-1][1] += 1 if st[-1][1] == k: st...
429
148
from typing import Callable class Item(Action): """ Items are Actions that can be transferred to another Player """ def __init__(self, name, function: Callable[[Player], None]): super().__init__(name, function) class Knife(Item): def __init__(self): super().__init__("Knife", lam...
345
101
import numpy as np from scipy.misc import imread, imsave from scipy import ndimage img = imread('doc1.bmp') def f(x): ret = x * 255 / 150 if ret > 255: ret = 255 return ret F = np.vectorize(f) treated_img = F(img) imsave('treated_doc.bmp', treated_img) mask = treated_img < treated_img.mean() ...
528
235
def connect(node1, node2): node1.connect(node2) node2.connect(node1)
72
30
import os from dotenv import load_dotenv import sqlite3 import psycopg2 from psycopg2.extras import execute_values load_dotenv() # looks inside the .env file for some env vars # passes env var values to python var DB_HOST = os.getenv("DB_HOST", default="OOPS") DB_NAME = os.getenv("DB_NAME", default="OOPS") DB_USER = ...
2,617
825
#: L23 Port Transceiver Commands from dataclasses import dataclass import typing from ..protocol.command_builders import ( build_get_request, build_set_request ) from .. import interfaces from ..transporter.token import Token from ..protocol.fields.data_types import * from ..protocol.fields.field import XmpFi...
4,161
1,316
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # 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 ...
12,991
5,072
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy class YunqiBookListItem(scrapy.Item): novelId = scrapy.Field() novelName = scrapy.Field() novelLink = scrapy.Field() novelAuthor = scra...
964
321
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.model_selection import StratifiedKFold, KFold def cv_index(n_fold, feature, label): skf = KFold(n_fold, shuffle=True, random_state=7840) index_list = [] for i, j in skf.split(feature, label): i...
4,626
1,723
# coding: utf-8 from flask.ext import wtf import flask import wtforms import auth import config import model import util from main import app ############################################################################### # Admin Stuff ###############################################################################...
502
128
from datetime import datetime from django.views.generic.base import TemplateView from django.shortcuts import get_object_or_404, render from django.urls import reverse from .models import MONTH_DICT, MONTH_LIST, YEARS,CARRIER_LIST from .forms import BSfilterForm from .main import _init_SCRAPER class HomePageView(T...
1,564
520
import argparse import importlib import logging import sys logger = logging.getLogger() COMMAND_MODULES = ( 'ncdoublescrape.scrape', ) def main(): parser = argparse.ArgumentParser('ncds', description='A janky NCAA scraper') subparsers = parser.add_subparsers(dest='subcommand') subcommands = {} ...
935
288
class ElektraConstants: pass
33
11
#!/usr/bin/env python ############################################################################ # # # Copyright 2014 Prelert Ltd # # ...
2,971
738
# Python3 from solution1 import twoTeams as f qa = [ ([1, 11, 13, 6, 14], 11), ([3, 4], -1), ([16, 14, 79, 8, 71, 72, 71, 10, 80, 76, 83, 70, 57, 29, 31], 209), ([23, 72, 54, 4, 88, 91, 8, 44], -38), ([23, 74, 57, 33, 61, 99, 19, 12, 19, 38, 77, 70, 20], -50) ] for *q, a ...
614
340
from __future__ import print_function import boto3 from decimal import Decimal import json import urllib from botocore.vendored import requests print('Loading function') rekognition = boto3.client('rekognition') s3 = boto3.resource("s3") # --------------- Helper Functions to call Rekognition APIs -----------------...
5,037
1,464
import socket import sqlite3 def Main(): port = 4000 s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM) print(socket.gethostbyaddr(socket.gethostname())) s.bind((socket.gethostbyaddr(),port)) print("Server started") while True: reg_db = sqlite3.connect("reg_db.db") reg_d...
3,836
1,232
from typing import Any class Stack: def __init__(self) -> None: self.stack = [] def stack_size(self) -> int: return len(self.stack) def is_empty(self) -> bool: return self.stack == [] # O(1) running time def push(self, data: Any) -> None: self.stack.append(data) ...
759
242
import collections import os from pathlib import Path def setter(f): return property(None, f) enum = enumerate def esorted(l): return enum(sorted(l)) def cn(o): return o.__class__.__name__ def strcmp(s1, s2, ignore_case=False): if ignore_case: return s1.lower() == s2.lower() return s1 == s2 ...
2,967
1,090
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from .common import Base, session_scope from .team import Team class Division(Base): __tablename__ = 'divisions' __autoload__ = True HUMAN_READABLE = 'division' def __init__(self, name, season, teams, conference=None): self.divi...
2,274
664
import pytest from ruamel import yaml from runthis.server.config import Config, get_config_from_yaml @pytest.fixture def config_obj(tmpdir): return Config( tty_server="ttyd", command="xonsh", docker=False, docker_image="myimage", keyfile="/path/to/privkey.pem", ) def...
1,338
472
# DISCLAIMER TO CONTEST TEAMS : DO NOT MAKE CHANGES IN THIS FILE. classes = { "Tasit": 0, "Insan": 1, "UAP": 2, "UAI": 3, } landing_statuses = { "Inilebilir": "1", "Inilemez": "0", "Inis Alani Degil": "-1" } base_url = "http://192.168.1.10:3000"
290
143