text
string
size
int64
token_count
int64
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class AlipayMerchantAuthDeleteModel(object): def __init__(self): self._channel_code = None self._operator_id = None self._role = None self._scene_code = None sel...
3,303
1,045
import torch from torchaudio_unittest.common_utils import PytorchTestCase from torchaudio_unittest.models.emformer.emformer_test_impl import EmformerTestImpl class EmformerFloat32CPUTest(EmformerTestImpl, PytorchTestCase): dtype = torch.float32 device = torch.device("cpu") class EmformerFloat64CPUTest(Emfor...
410
138
""" Two pipelines: * full history * update latest season * Only updates latest season year """ from functools import partial import itertools from kedro.pipeline import Pipeline, node from nba_analysis.pipelines.data_processing import basketball_reference from . import nodes def create_pipeline(**kwargs): ...
2,206
646
# Created by BaiJiFeiLong@gmail.com at 2022/1/21 17:13 import typing from IceSpringRealOptional.typingUtils import gg from PySide2 import QtWidgets, QtCore from IceSpringMusicPlayer import tt from IceSpringMusicPlayer.common.pluginMixin import PluginMixin from IceSpringMusicPlayer.common.pluginWidgetMixin import Plu...
970
312
""" An implementation on spherical harmonics in python becasue scipy.special.sph_harm in scipy<=0.13 is very slow Originally written by Jozef Vesely https://github.com/scipy/scipy/issues/1280 """ import numpy as np def xfact(m): # computes (2m-1)!!/sqrt((2m)!) res = 1. for i in xrange(1, 2*m+1): ...
3,259
1,451
#!/usr/bin/env python # coding: utf-8 # In[9]: import requests import pandas as pd from lxml import etree from bs4 import BeautifulSoup import datetime import io import numpy as np from alphacast import Alphacast from dotenv import dotenv_values API_KEY = dotenv_values(".env").get("API_KEY") alphacast = Alphacast(A...
1,820
871
# import the GED using the munkres algorithm import gmatch4py as gm import networkx as nx import collections import csv import pickle from collections import OrderedDict import json import concurrent.futures as cf import time iter = 0 def getFinishedStatus(): iter +=1 print('*******\t' + str(iter)+ "\t*****...
5,572
1,920
# -*- coding: utf-8 -*- # Copyright 2011 Takeshi KOMIYA # # 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...
1,940
571
# -*- coding: utf-8 -*- """ Created on Thu Dec 19 20:00:00 2019 @author: Emilia Chojak @e-mail: emilia.chojak@gmail.com """ tax_dict = { 'Pan troglodytes' : 'Hominoidea', 'Pongo abelii' : 'Hominoidea', 'Hominoidea' : 'Simiiformes', 'Simiiformes' : 'Haplorrhini', 'Tarsius tarsier' : 'Tarsiiformes', 'Haplorrhini' : 'Pr...
1,355
540
import csv # with open('./1.csv', newline='', encoding='utf-8') as f: # reader = csv.reader(f) # for row in reader: # print(row) with open('./1.csv', 'a', encoding='utf-8') as f: writer = csv.writer(f) writer.writerow(['4', '猫砂', '25', '1022', '886']) writer.writerow(['5', '猫罐头', '18', '22...
334
151
"""This module contains code for parsing RPC responses.""" from dataclasses import dataclass, field from typing import Union, Tuple, Any, Dict, List, Optional, Literal from apischema import alias from apischema.conversions import as_str from solana.publickey import PublicKey from solana.transaction import Transactio...
5,110
1,452
"""Build a binary min heap object.""" from math import floor class BinaryHeap(object): """Create a Binary Heap object as a Min Heap.""" def __init__(self): """Initialize the heap list to be used by Binary Heap.""" self._heap_list = [] def push(self, val): """Add new value to heap...
1,845
571
""" Vesper archive settings. The Vesper server serves the Vesper archive that is in the directory in which the server starts. The archive settings are the composition of a set of default settings (hard-coded in this module) and settings (optionally) specified in the file "Archive Settings.yaml" in the archive director...
1,547
455
#-*- coding=utf-8 -*- from __future__ import division, print_function, absolute_import from base_model import BaseModel from helper import * import tensorflow as tf import pickle import numpy as np import time class Vgg16(BaseModel): default_param = { "loss" : "square_loss", "metrics" : ["loss"], ...
9,841
3,472
import subprocess from LEGEND import tbot as bot from LEGEND import tbot as borg from LEGEND.events import register from LEGEND import OWNER_ID, SUDO_USERS import asyncio import traceback import io import os import sys import time from telethon.tl import functions from telethon.tl import types from telethon.tl.types im...
3,226
1,124
# Status: Being ported by Steven Watanabe # Base revision: 47077 # # Copyright (c) 2005 Reece H. Dunn. # Copyright 2006 Ilya Sokolov # Copyright (c) 2008 Steven Watanabe # # Use, modification and distribution is subject to the Boost Software # License Version 1.0. (See accompanying file LICENSE_1_0.txt or # http://www....
2,850
904
import re from typing import Dict from aiohttp import web from yarl import URL from simcore_service_webserver.db_models import UserRole, UserStatus from simcore_service_webserver.login.cfg import cfg, get_storage from simcore_service_webserver.login.registration import create_invitation from simcore_service_webserver...
3,274
1,055
from indra import sparser xml_str1 = ''' <article pmid="54321"> <interpretation> <sentence-text>MEK1 phosphorylates ERK1</sentence-text> <sem> <ref category="phosphorylate"> <var name="agent"> <ref category="protein"> <var name="name">MP2K1_HUMAN</var> <var name="uid...
2,806
1,045
""" Simple Example using coreali to access a register model. Needs no h^ardware""" # Import dependencies and compile register model with systemrdl-compiler from systemrdl import RDLCompiler import coreali import numpy as np import os from coreali import RegisterModel rdlc = RDLCompiler() rdlc.compile_file(os.path.di...
685
234
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import os import re from abc import ABC, ABCMeta, abstractmethod from dataclasses import dataclass from typing import ( TYPE_CHECKING, Dict, Iterable, Iterator, List, Optional,...
14,872
4,646
import json import requests from enum import Enum from typing import Dict from ..exceptions import JsonDecodeError, UnexpectedResponse, RequestError, BaseApiRequestError class MockRequesterMixin: """ Набор методов для моков реквестеров """ class ERRORS(Enum): ERROR_TOKEN = 'error' BAD_...
4,140
1,478
# -*- coding: utf-8 -*- # The MIT License (MIT) - Copyright (c) 2016-2021 Dave Vandenbout. import pytest from skidl import netlist_to_skidl from .setup_teardown import get_filename, setup_function, teardown_function def test_parser_1(): netlist_to_skidl(get_filename("Arduino_Uno_R3_From_Scratch.net"))
313
131
#!/usr/bin/env python3 import ST7735 import sys st7735 = ST7735.ST7735( port=0, cs=1, dc=9, backlight=12, rotation=270, spi_speed_hz=10000000 ) # Reset the display st7735.begin() st7735.reset() st7735.set_backlight(0) print "\nDone." # Exit cleanly sys.exit(0)
291
155
from geopy.geocoders import Nominatim from requests.models import LocationParseError geolocator = Nominatim(user_agent="geoapiExercises") Latitude = 25.594095 Longitude = 85.137566 def location(Latitude, Longitude): lat = str(Latitude) long = str(Longitude) print(lat + long) local = lat + "," + long...
709
243
import random from tkinter import PhotoImage """ Esse arquivo define os estados do game """ def ia_chocer(): """IA faz a escolha de um numero aleatório""" posibility = ['rock', 'paper', 'scissor'] value = posibility[random.randint(0, 2)] return value def battle_verification(player_choice, ia_choic...
1,196
412
from filelock import FileLock, Timeout import os import time class ProcessFileLock(FileLock): """ FileLock that is unique per path in each process (for, eg., reentrance) """ locks = {} def __new__(cls, path, *args, **kwargs): if path in ProcessFileLock.locks: return P...
4,710
1,422
class A_NEW_NAME(object): pass
34
13
#from . import context #from . import test_NNModels #from . import test_data_extract #from . import test_speedcom #from . import test_utilities
144
44
# Django REST Framework from rest_framework import serializers # Model from todo.management.models import Task # Utils from todo.utils.tasks import TaskMetrics from todo.utils.serializer_fields import CompleteNameUser class TaskModelSerializer(serializers.ModelSerializer): """Modelo serializer del circulo""" ...
1,637
468
import numpy as np import pandas as pd from sklearn.decomposition import PCA ''' A function that detects outliers, where k is a tandard deviation threshold hyperparameter preferablly (2, 2.5, 3). The algo could handle multivariable data frames with any number of features d. For that manner, it first reduces the dimens...
1,895
632
# included from snippets/main.py def debug(*x, msg=""): import sys print(msg, *x, file=sys.stderr) def solve(SOLVE_PARAMS): pass def main(): A, B, C = map(int, input().split()) doubling = [B % 20] for i in range(32): doubling.append( (doubling[-1] ** 2) % 20 ) ...
1,631
726
ezan = { 'name': 'ezan', 'age': 18, 'hair': 'brown', 'cool': True , } print(ezan) class Person(object): #use class to make object def __init__( self, name, age ,hair, color, hungry) : #initialize #first object inside of a class is self self.name = 'ezan' self.age = 18 ...
892
337
# 62. 不同路径 # 组合数,杨辉三角 yanghui = [[0 for i in range(202)] for j in range(202)] def comb(n, k): if yanghui[n][k] == 0: yanghui[n][k] = (comb(n-1, k-1) + comb(n-1, k)) return yanghui[n][k] class Solution: def uniquePaths(self, m: int, n: int) -> int: for i in range(202): yanghui...
400
202
from Pages import * app = App() app.mainloop()
48
19
import flask from cauldron.cli.server import run as server_runner from cauldron.ui import arguments from cauldron.ui import statuses @server_runner.APPLICATION.route('/ui-status', methods=['POST']) def ui_status(): args = arguments.from_request() last_timestamp = args.get('last_timestamp', 0) force = arg...
433
134
import requests from bs4 import BeautifulSoup import re rq = requests.get("https://play.google.com/store/apps/category/GAME_MUSIC?hl=ko") rqctnt = rq.content soup = BeautifulSoup(rqctnt,"html.parser") soup = soup.find_all(attrs={'class':'title'}) blacklsit = ["앱","영화/TV","음악","도서","기기","엔터테인먼트","음악"] for link in sou...
418
178
from unittest import TestCase from pyramid import testing class PhotosTests(TestCase): def setUp(self): self.config = testing.setUp() def tearDown(self): testing.tearDown()
203
66
#Negative Indexes spam = ['cat', 'bat', 'rat', 'elephant'] spam[-1] # elepant spam[-3] # bat # Getting a List from another List with Slices spam = ['cat', 'bat', 'rat', 'elephant'] spam[0:4] # ['cat', 'bat', 'rat', 'elephant'] spam[1:3] # ['bat', 'rat'] spam[0:-1] # ['cat', 'bat', 'rat'] spam[:2] # ['cat', 'bat'] spa...
2,995
1,251
import pandas as pd path = "Resources/cities.csv" data = pd.read_csv(path) data_html = data.to_html("data.html", bold_rows = True)
130
48
# Copyright (C) 2020 Red Hat Inc. # # Authors: # Eduardo Habkost <ehabkost@redhat.com> # # This work is licensed under the terms of the GNU GPL, version 2. See # the COPYING file in the top-level directory. from tempfile import NamedTemporaryFile from .patching import FileInfo, FileMatch, Patch, FileList from .regexp...
3,268
1,128
# # Simple Tuple # fruits = ('Apple', 'Orange', 'Mango') # # Using Constructor # fruits = tuple(('Apple', 'Orange', 'Mango')) # # Getting a Single Value # print(fruits[1]) # Trying to change based on position # fruits[1] = 'Grape' # Tuples with one value should have trailing comma # fruits = ('Apple') # fruits = ('...
634
244
from dataclasses import dataclass from dataclasses import asdict from typing import List, Tuple, Callable import numpy as np from sklearn.metrics import accuracy_score as accuracy_sklearn from sklearn.metrics import precision_score as precision_sklearn from sklearn.metrics import recall_score as recall_sklearn from sk...
20,146
5,444
import sys def readInput(): labels, features, all_features, labelCount = [], [], [], {} l = sys.stdin.readline().strip().split(' ') while len(l)> 1: label = l[0] if label not in labelCount: labelCount[label] = 0 labelCount[label] += 1 labels.append(label) ...
2,192
649
# Importamos la librería para leer archivos json import json # Abrimos el archivo master en modo lectura ('r') con todos los id de los archivos descargados with open('master.json', 'r') as f: # Guardamos en la variable lista el contenido de master lista = json.load(f) # En este ejemplo se representa cómo se a...
2,530
688
#!/usr/bin/env python # -*- coding: utf-8 -*- """ This file contains the generators and their inverses for common archimedean copulas. """ import numpy as np def boundsConditions(x): if x < 0 or x > 1: raise ValueError("Unable to compute generator for x equals to {}".format(x)) def claytonGenerator(...
2,860
1,002
""" """ from admin import routes def init_app(app): """ :param app: :return: """ routes.init_app(app)
126
50
from output.models.nist_data.list_pkg.decimal.schema_instance.nistschema_sv_iv_list_decimal_pattern_2_xsd.nistschema_sv_iv_list_decimal_pattern_2 import NistschemaSvIvListDecimalPattern2 __all__ = [ "NistschemaSvIvListDecimalPattern2", ]
243
94
import numpy as np import pyamg from scipy import sparse from scipy.spatial import Delaunay from linsolver import sparse_solver from triangulation.delaunay import delaunay class Element: def __init__(self, points, global_indexes, fem): self.points = np.array(points) self.global_indexes = global_i...
6,642
2,164
"""Support for Atlantic Electrical Heater IO controller.""" import logging from typing import List from homeassistant.components.climate import ClimateEntity from homeassistant.components.climate.const import ( HVAC_MODE_HEAT, HVAC_MODE_OFF, SUPPORT_TARGET_TEMPERATURE, ) from homeassistant.const import ATT...
2,745
903
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2021-03-02 13:32 from typing import Optional, Union, Dict, Any import torch from torch import nn from transformers import PreTrainedTokenizer from elit.components.mtl.attn.attn import TaskAttention from elit.components.mtl.attn.transformer import JointEncoder from elit....
3,271
909
from sensors.sensors import sense_characteristics, sense_pedestrians
68
19
"""Implementations of algorithms for continuous control.""" import functools from typing import Optional, Sequence, Tuple import jax import jax.numpy as jnp import numpy as np import optax from jaxrl.agents.sac import temperature from jaxrl.agents.sac.actor import update as update_actor from jaxrl.agents.sac.critic ...
5,140
1,588
"""Collections of library function names. """ class Library: """Base class for a collection of library function names. """ @staticmethod def get(libname, _cache={}): if libname in _cache: return _cache[libname] if libname == 'stdlib': r = Stdlib() elif ...
14,515
5,073
import pandas as pd print(pd.__version__) city_names = pd.Series(['San Francisco', 'San Jose', 'Sacramento']) population = pd.Series([852469, 1015785, 485199]) #city_population_table = pd.DataFrame(({'City name': city_names, 'Population': population})) california_houseing_dataframe = pd.read_csv("https://storage.google...
1,143
442
from helloworld.app import main if True or __name__ == '__main__': main().main_loop()
91
32
from fastapi import FastAPI from dotenv import load_dotenv from fastapi.middleware.cors import CORSMiddleware from app.api.api_v1.api import api_router from app.core.config import settings app = FastAPI() load_dotenv() app.include_router(api_router, prefix=settings.API_V1_STR) # Set all CORS enabled origins if sett...
797
273
"""Example revision Revision ID: fdf0cf6487a3 Revises: Create Date: 2021-08-09 17:55:19.491713 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = "fdf0cf6487a3" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto ge...
658
242
from __future__ import annotations from typing import Optional # Definition for a binary tree node. class TreeNode: def __init__(self, val: int = 0, left: Optional[TreeNode] = None, right: Optional[TreeNode] = None): self.val = val self.left = left self.right = right class BSTIterator: ...
790
234
# @lc app=leetcode id=506 lang=python3 # # [506] Relative Ranks # # https://leetcode.com/problems/relative-ranks/description/ # # algorithms # Easy (53.46%) # Likes: 188 # Dislikes: 9 # Total Accepted: 71.1K # Total Submissions: 132.4K # Testcase Example: '[5,4,3,2,1]' # # You are given an integer array score of...
2,768
1,117
# -*- Python -*- import os # Setup config name. config.name = 'MemorySanitizer' + getattr(config, 'name_suffix', 'default') # Setup source root. config.test_source_root = os.path.dirname(__file__) # Setup default compiler flags used with -fsanitize=memory option. clang_msan_cflags = (["-fsanitize=memory", ...
1,933
678
# Generated by Django 2.0.6 on 2018-06-17 04:47 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Cliente', fields=[ ('id', models.SmallInteg...
8,084
2,342
# # nuna_sql_tools: Copyright 2022 Nuna 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...
9,606
2,893
"""HERE are the base Points for all valid Tonnetze Systems. A period of all 12 notes divided by mod 3, mod 4 (always stable) """ # x = 4, y = 3 NotePointsT345 = { 0: (0, 0), 1: (1, 3), 2: (2, 2), 3: (0, 1), 4: (1, 0), 5: (2, 3), 6: (0, 2), 7: (1, 1), 8: (2, 0), 9: (0, 3), 1...
1,541
970
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from .aws import Action as BaseAction from .aws import BaseARN service_name = "AWS Proton" prefix = "proton" class Action(BaseAction): def __init__(self, action: str = None) -> None: super(...
3,718
894
class RequirementsNotMetError(Exception): """For SQL INSERT, missing table attributes.""" def __init__(self, message): super().__init__(message) class AuthenticationError(Exception): """Generic authentication error.""" def __init__(self, message): super().__init__(message)
308
79
# Copyright 2020 DeepMind Technologies Limited. 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 ...
10,577
3,724
#!/usr/bin/python # Classification (U) """Program: slaverep_isslverror.py Description: Unit testing of SlaveRep.is_slv_error in mysql_class.py. Usage: test/unit/mysql_class/slaverep_isslverror.py Arguments: """ # Libraries and Global Variables # Standard import sys import os if sys.version...
3,664
1,125
""" 108. 将有序数组转换为二叉搜索树 """ from TreeNode import TreeNode class Solution: def sortedArrayToBST(self, nums: [int]) -> TreeNode: def dfs(left, right): if left > right: return None mid = left + (right - left) // 2 root = TreeNode(nums[mid]) roo...
545
210
## -*- encoding: utf-8 -*- """ This file (./domaines_doctest.sage) was *autogenerated* from ./domaines.tex, with sagetex.sty version 2011/05/27 v2.3.1. It contains the contents of all the sageexample environments from this file. You should be able to doctest this file with: sage -t ./domaines_doctest.sage It is always ...
10,230
5,154
from .Deserializer import Deserializer from .RateLimiter import RateLimiter from .Handlers import ( DeprecationHandler, DeserializerAdapter, DictionaryDeserializer, RateLimiterAdapter, ThrowOnErrorHandler, TypeCorrectorHandler, ) from .Handlers.RateLimit import BasicRateLimiter from ._apis imp...
1,978
531
# Copyright 1996-2021 Cyberbotics 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 in...
4,175
1,294
setlist = [['a','m','n','s','t','g','q','o','x'],['b','e','c'],['h','k','u','v'], ['d','r','p'],['f'],['l'],['i'],['w'],['y']]
127
65
from .player import Player class JeffPlayer(Player): """ JeffPlayer focuses on the odds for continuing turns. To pick which move, calculates a move value based on odds of continued turns, moving forward less likely columns when possible, and winning columns over opponents. """ ODDS = 'odds...
24,241
9,075
#!/usr/bin/env python # Nathan Rhoades 10/13/2017 import serial import serialport import bgapi import gui import digicueblue import traceback import time import threading import sys if sys.version_info[0] < 3: import Tkinter as Tk else: import tkinter as Tk class App(threading.Thread): # thread GUI to tha...
1,767
550
import requests #newspi key c2d941c74c144421945618d97a458144 class Article: link:str headline:str summary:str body:str
138
70
import logging import os import json from multiprocessing import Process, Queue, Lock import numpy as np from PyMaSC.core.mappability import MappableLengthCalculator from PyMaSC.utils.progress import ProgressHook, MultiLineProgressManager from PyMaSC.utils.compatible import tostr, xrange from PyMaSC.utils.output impo...
8,471
2,531
from django.shortcuts import render from django.views import View # Create your views here. def simple(request): return render(request, 'tmpl/simple.html') def guess(request) : context = {'zap' : '42' } return render(request, 'tmpl/guess.html', context) def special(request) : context = {'txt' : '<b>...
1,190
437
from flask import escape '''with open('ex') as full: for line in full: print(line,end='**') ''' ''' a=[] with open('ex') as full: for line in full: a.append(line.split('|')) print(a) ''' ''' with open('ex') as full: for line in full.readline(): print(line) ''' contents=[] with o...
477
164
import requests import jsonpickle from requests_oauthlib import OAuth1 from urllib.parse import parse_qs, urlencode import cherrypy from collections import defaultdict import json import os import re from collections import defaultdict # For readable serializations jsonpickle.set_encoder_options('json', sort_keys=Tr...
15,310
4,788
import json from enum import Enum from decimal import Decimal def convert_serializable_special_cases(o): """ Convert an object to a type that is fairly generally serializable (e.g. json serializable). This only handles the cases that need converting. The json module handles all the rest. For JSON, ...
1,399
384
import sys import os import argparse import numpy as np import paddle.v2 as paddle import reader import utils import network import config from utils import logger def save_model(trainer, model_save_dir, parameters, pass_id): f = os.path.join(model_save_dir, "params_pass_%05d.tar.gz" % pass_id) logger.info(...
5,249
1,654
import subprocess import uuid as uuid_gen import logging from datetime import datetime import os import psutil import warnings import weakref from yggdrasil import backwards, tools, platform, serialize from yggdrasil.languages import get_language_dir from yggdrasil.config import ygg_cfg from yggdrasil.drivers.Interpret...
36,880
10,478
# Generated by Django 3.1.3 on 2021-04-09 04:03 import django.db.models.deletion from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('snpdb', '0030_one_off_fix_cohort_sample_order'), ('analysis', '0031_auto_20210331_1826'), ] operations = [ ...
1,049
351
import pathlib from typing import Iterator import pandas as pd from ted_sws.resources.prefixes import PREFIXES_DEFINITIONS import re CONCEPTUAL_MAPPINGS_RULES_SHEET_NAME = "Rules" RULES_SF_FIELD_ID = 'Standard Form Field ID (M)' RULES_SF_FIELD_NAME = 'Standard Form Field Name (M)' RULES_E_FORM_BT_ID = 'eForm BT-ID (O)...
3,453
1,244
import sys from os.path import dirname, abspath, join cur_folder = dirname(abspath(__file__)) sys.path.insert(0, join(dirname(cur_folder), 'src')) sys.path.insert(0, dirname(cur_folder)) print(cur_folder)
205
76
# https://stackoverflow.com/questions/3300464/how-can-i-get-dict-from-sqlite-query # from flask import Flask from flask_restful import Resource, reqparse from src.model.serie import SerieModel from src.server.instance import server from db import db # books_db = [{"id": 0, "title": "War and Peace"}, {"id": 1, "title"...
3,892
1,178
import copy import pickle import tcod def test_tcod_random() -> None: rand = tcod.random.Random(tcod.random.COMPLEMENTARY_MULTIPLY_WITH_CARRY) assert 0 <= rand.randint(0, 100) <= 100 assert 0 <= rand.uniform(0, 100) <= 100 rand.guass(0, 1) rand.inverse_guass(0, 1) def test_tcod_random_copy() ->...
879
382
############################################################################## # # Copyright (c) 2006 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
2,538
763
#Let d(n) be defined as the sum of proper divisors of n (numbers less than n which divide evenly into n). #If d(a) = b and d(b) = a, where a b, then a and b are an amicable pair and each of a and b are called amicable numbers. #For example, the proper divisors of 220 are 1, 2, 4, 5, 10, 11, 20, 22, 44, 55 and 110; th...
920
447
#!/usr/bin/env python3 """Unpack a MIME message into a directory of files.""" import os import email import mimetypes from email.policy import default from argparse import ArgumentParser def main(): parser = ArgumentParser(description="""\ Unpack a MIME message into a directory of files. """) parser.add_a...
1,590
449
import sys, os import logging import datetime module_name = 'Streetview_Module' debug_mode = True class LoggingWrapper(object): def __init__(self, log_folder_path=None): self.debug_mode = debug_mode # Create logger with module name logger = logging.getLogger(module_name) logger.s...
1,400
397
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' from tkinter import * root = Tk() root.title('Chess board') canvas = Canvas(root, width=700, height=700, bg='#fff') canvas.pack() fill = '#fff' outline = '#000' size = 88 for i in range(8): for j in range(8): x1, y1, x2, y2 = i * ...
536
219
# asandbox.py # # Authors: # - Coumes Quentin <coumes.quentin@gmail.com> """An asynchronous implementation of the Sandbox API.""" import io import json import os from contextlib import AbstractAsyncContextManager from typing import BinaryIO, Optional, Union import aiohttp from .exceptions import status_exception...
7,827
2,030
import datetime from uuid import UUID from api.actions import storage from fastapi import HTTPException from api.models.usuario import Usuario from starlette.requests import Request from api.dependencies import validar_email, validar_formato_fecha,validar_edad FORMATO_FECHA = "%Y-%m-%d" EDAD_MINIMA = 18 EDAD_MAXIMA = ...
4,928
1,460
import os import logging import dateutil import pickle from six.moves.urllib.parse import urlparse from libtaxii import get_message_from_http_response, VID_TAXII_XML_11 from libtaxii.messages_11 import PollRequest, PollFulfillmentRequest from libtaxii.messages_11 import PollResponse, generate_message_id from libtaxii...
10,204
2,632
import os import zipfile import requests DATA_PATH = './data' RESULT_PATH = './result' if not os.path.exists(DATA_PATH): os.makedirs(DATA_PATH) print('Downloading and extracting data...') url = 'https://weisslab.cs.ucl.ac.uk/WEISSTeaching/datasets/-/archive/hn2dct/datasets-hn2dct.zip' r = requests.get(url,all...
768
307
import doctest from insights.parsers import freeipa_healthcheck_log from insights.parsers.freeipa_healthcheck_log import FreeIPAHealthCheckLog from insights.tests import context_wrap LONG_FREEIPA_HEALTHCHECK_LOG_OK = """ [{"source": "ipahealthcheck.ipa.roles", "check": "IPACRLManagerCheck", "result": "SUCCESS", "uuid"...
3,774
1,567
# Copyright 2021 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 recipe_engine import post_process from PB.recipes.infra.windows_image_builder import windows_image_builder as wib from PB.recipes.infra.windows_image_b...
3,484
1,225
from lollangCompiler.compiler import Compiler import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--file", required=True, help="컴파일할 파일을 선택해주세요.") parser.add_argument("--out", default="out.py", help="목적 파이썬 파일경로를 선택해주세요") args = parser.parse_args() cmp...
374
165
import logging import subprocess import xml.etree.ElementTree as ET from tqdm import tqdm logger = logging.getLogger('root') POST_TYPE_QUESTION = '1' POST_TYPE_ANSWER = '2' class SEDataReader(object): """ NOTE: - a typical xml string for question in original data looks like <row Id="4"...
4,103
1,385