index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
9,400
451c353a949458f5f71783c4aba1888c40018bfa
from rest_framework import serializers from . import models class RaumSerializer(serializers.ModelSerializer): class Meta: model = models.Raum fields = [ "Raumnummer", "Anzahl_Sitzplaetze", "Beamer", "Whiteboard", ] class ZeitraumSerialize...
9,401
971187dc0e0f02282c8945940d07c011e247667a
""" Kontrollülesanne 7.4c - Elutee number (tähtaeg 28.okt. (incl)) Maksimaalne failide arv: 1 Töö liik: Individuaaltöö Numeroloogias peetakse tähtsaks elutee numbrit, mille arvutamiseks tuleb liita kokku sünnikuupäeva ja -aasta numbrid nii, et jõutakse lõpuks ühe numbrini. Näiteks, oletame, et sünnikuupäev on 15.05....
9,402
6d042a2035eab579193452e4dc44c425125d9515
from flask_restful import Resource, reqparse import nltk from nltk.tokenize import sent_tokenize tokenizer = nltk.RegexpTokenizer(r"\w+") # CLASS DESCRIPTION: # Devides and clears the sentence of punctuation marks and builds a dependency tree on each sentence # Allocates its own names and verbs # added: Te...
9,403
1930aa258ac4fbcdb2972e19bdb2625d2dae4114
from console import Display import time images = ["/img/erni_l.txt", "/img/erni_s.txt", "/img/erni_logo.txt", "/img/github_logo.txt", "/img/upython_logo.txt", "/img/python_logo.txt", "/img/upython_logo_s.txt", "/img/MSC_logo.txt"] def show(): oled = Display() for image in images: ...
9,404
fe73a80b15cad025a33930ddd9abb31524cd0244
# coding: utf-8 from __future__ import ( absolute_import, division, print_function, unicode_literals, ) import time from urllib import urlencode from urlparse import parse_qs, urlparse, urlunparse from flask import current_app as app from flask import url_for from jose import jwt from oauth2client.cl...
9,405
d1a179acfda9e76a11f362671fafb50773e2b9d3
# -- !/python3.10 # Mikhail (myke) Kolodin, 2021 # 2021-10-21 2021-10-21 1.2 # retext.py # Заменить во входном тексте указанное слово на случайный вариант # из предложенного набора заменителей. # Параметры - в командной строке. import re, random, sys fin = 'retext-in.txt' fot = 'retext-out.txt' t1 = """ here we go...
9,406
5c5922fd3a7a5eec121d94e69bc972089e435175
################################################# ### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ### ################################################# # file to edit: dev_nb/10_DogcatcherFlatten.ipynb import pandas as pd import argparse import csv import os import numpy as np import string def FivePrimeArea(df): ...
9,407
1c2967c26c845281ceb46cc1d8c06768298ef6b6
import numpy as np import pandas as pd from unrar import rarfile import numpy as np import pandas as pd import tushare as ts import os year_month='201911' contract_kind='NI' rar_data_file_path='C:/Users/lenovo/Documents/WeChat Files/yiranli13/FileStorage/File/2020-01/' main_code_path='C:/Users/lenovo/Documents/WeCha...
9,408
ba42c6af53329035f7ab72f3f1ac87cd90d9dc7f
# difference between size an shape of an image import cv2 img = cv2.imread('police.jpg') print img.size # byte size; slightly larger than the file size print img.shape # y,x or rows, cols cv2.imshow("My Picture", img) cv2.waitKey(0) cv2.destroyAllWindows()
9,409
9ffe350ff9a568111620ef7dafef83d341f6f01e
# -*- coding: utf-8 -*- # https://github.com/Raschka-research-group/coral-cnn/tree/master/model-code/resnet34 from absl import flags, app from Rank_consistent_model_fix import * from Rank_consistent_model import * from random import shuffle, random import tensorflow as tf import numpy as np # import cv2 import os impo...
9,410
8c7fe90972feec19e280d3bccd39391af666608a
def play(): print("playing tank games...") print("runing tank now!!!")
9,411
f9dd20a3b72c0c8e72029459244486f31eaff536
import dash_html_components as html import dash_core_components as dcc import dash_daq as daq import dash_bootstrap_components as dbc import src.common.common_layout as layout_common def build_navbar(): return html.Div( id="banner", children=[ html.Div( id="banner-text...
9,412
a0d1ef11d00e2ddd65b648a87f493b7adcda5115
class RankedHand(object): def __init__(self, remaining_cards): self._remaining_cards = remaining_cards self.rank = None def remaining_cards(self): return self._remaining_cards # Returns 1 if self is higher, 0 if equal, -1 if self is lower def compare_high_cards(self, other): s_cards = reversed...
9,413
b4454d92ab8380e0eded2f7aed737378e1710c72
#!/usr/bin/env python3 import sys, os import random import numpy as np import matplotlib as mpl if os.environ.get('DISPLAY','') == '': print('no display found. Using non-interactive Agg backend') mpl.use('Agg') import matplotlib.pyplot as plt from mpl_toolkits.axes_grid1 import make_axes_locatable import sha...
9,414
39f1fc04911f8d22d07532add24cd1671a569e72
from airflow.plugins_manager import AirflowPlugin from flask import Blueprint, Flask from rest_api.log.views import views from rest_api.route.log_route import log from rest_api.route.mylog_route import my_log_pb from rest_api.route.native_log_route import native_log_bp class AirflowPlugin(AirflowPlugin): name = "...
9,415
0a459b4aeb2a16c06c1d89dafb656028b235a31e
import math def calcula_distancia_do_projetil(v, O, y0): g = 9.8 return ((v ** 2) / 2 * g) * (1 + math.sqrt(1 + ( 2 * g * y0 / (v ** 2) * (math.sin(O) ** 2)))) * math.sin(2 * O)
9,416
2a799d81d963f73d8018a99cbd963af166681b35
def factorial(num): assert num >= 0 and int(num) == num, 'Only positive integer accept' if num in [0,1]: return 1 else: return num*factorial(num-1) print(factorial(4.4))
9,417
657ac500c40ddbd29f5e3736a78ed43e7d105478
num=int(input("Enter the number: ")) table=[num*i for i in range(1,11)] print(table) with open("table.txt","a") as f: f.write(f"{num} table is: {str(table)}") f.write('\n')
9,418
25595b5f86a41fee1dc43f199f3bcff73f6d256b
import ray import os import sys import random path_join = os.path.join real_path = os.path.realpath perfd_dir = real_path(path_join(os.getcwd())) microps_dir = path_join(perfd_dir, "thirdparty", "microps") sys.path += [perfd_dir, microps_dir] from thirdparty.microps.oracle.experiments.spark_sql_perf.main import Spar...
9,419
0a5baacf17d33dbf6ea69114a8632f7fcef52c3c
import tkinter from tkinter import messagebox from random import randint tplyer = 0 tcomp = 0 player = 0 comp = 0 top = tkinter.Tk() top.resizable(width = False, height =False) top.geometry("200x100") def Yes(): global player global comp tplayer = randint(1,6) tcomp = randint(1,6) message ="" if tplay...
9,420
b569f0a0dda048d6337e1028a240caabf188a174
___author__ = 'acmASCIS' ''' by ahani at {9/24/2016} ''' import time class Freq(object): def __init__(self, array): self.__array = array self.__frequency_dict = {} self.__array_length = len(array) self.__running_time = round(time.time() * 1000) def get_original_array(sel...
9,421
c0b6c0636d1900a31cc455795838eb958d1daf65
# Find a list of patterns in a list of string in python any([ p in s for p in patterns for s in strings ])
9,422
00609c4972269c36bbfcf5bec2a8648f812b6092
# -*- coding: utf-8 -*- """ Created on Fri Oct 5 09:10:03 2018 @author: User """ from urllib.request import urlopen from urllib.error import HTTPError from bs4 import BeautifulSoup import re url = "http://www.pythonscraping.com/pages/page3.html" html = urlopen(url) html_data = BeautifulSoup(html.read(), "lxml") img...
9,423
02a228c479a6c94858f7e8ef73a7c8528def871e
class Solution(object): def plusOne(self, digits): """ :type digits: List[int] :rtype: List[int] """ plus = True # In the last digit, we should add one as the quesiton requries indexList = range(len(digits)) indexList.reverse() for i in indexList: ...
9,424
9cea998d7d5cad3ddc00f667ca06151a938d48a1
# -*- coding: utf-8 -*- # @Author : William # @Project : TextGAN-william # @FileName : gan_loss.py # @Time : Created at 2019-07-11 # @Blog : http://zhiweil.ml/ # @Description : # Copyrights (C) 2018. All Rights Reserved. import torch import torch.nn as nn import config as cfg class ...
9,425
e99ff1c75d5108efc8d587d4533c34eeb15c6978
from django.contrib.staticfiles.storage import CachedFilesMixin from storages.backends.s3boto3 import S3Boto3Storage class CachedS3Storage(CachedFilesMixin, S3Boto3Storage): pass StaticRootS3BotoStorage = lambda: CachedS3Storage(location='static') MediaRootS3BotoStorage = lambda: S3Boto3Storage(location='media'...
9,426
97a362fc65731bb8fc3743c49a669b4cd3f0e155
import collections import numpy import pytest import random import conftest from svviz2.io import readstatistics from svviz2.remap import genotyping from svviz2.utility.intervals import Locus def get_read_stats(isize=400): stats = readstatistics.ReadStatistics(None) stats.insertSizes = numpy.random.normal(400...
9,427
7bb49712c4ef482c64f3c2a457a766de691ba7c3
def bfs(graph, start): queue = [start] queued = list() path = list() while queue: print('Queue is: %s' % queue) vertex = queue.pop(0) print('Processing %s' % vertex) for candidate in graph[vertex]: if candidate not in queued: queued.append(candidate) queue.append(candidat...
9,428
267276eab470b5216a2102f3e7616f7aecadcfe9
# ------------------------------------------- # Created by: jasper # Date: 11/24/19 # -------------------------------------------- from os import path, mkdir class IOHandler: def __init__(self, directory, fName, data_instance): """Save the setup of a class instance or...
9,429
7025cc896035c59e0bbb7943493b6ca24fd9e6ca
from flask import Flask, render_template, request app = Flask(__name__) def convert(decimal_num): roman = {1000:'M', 900:'CM', 500:'D', 400:'CD', 100:'C', 90:'XC', 50:'L', 40:'XL', 10:'X', 9:'IX', 5:'V', 4:'IV', 1:'I'} num_to_roman = '' for i in roman.keys(): num_to_roman += roman[i]*(decimal_num/...
9,430
7e318ae7317eac90d6ce9a6b1d0dcc8ff65abef0
from dataclasses import dataclass, field from typing import List @dataclass class Root: a: List[object] = field( default_factory=list, metadata={ "type": "Element", "namespace": "", "min_occurs": 2, "max_occurs": 4, "sequence": 1, ...
9,431
eb81f1825c4ac8e20dde1daefbdad22f588e696e
#1.문자열에 홑따옴표 포함기키기 : 쌍따옴표 print("Python's Data Type") #2.문자열에 쌍따옴표 포함시키기 : 홑따옴표 print('"Python is very easy" he said.') #멀티라인(여러줄)표현하기 #1. 연속된 쌍따옴표 3개 사용하기 print("""No pain No gain""") #2. 연속된 쌍따옴표 3개 사용하기 print('''No pain No gain''') #3.이스케이프 코드 \n 삽입하기 print("No pain \n No gain") """ 이스케이프(es...
9,432
f5274f5d838d484ca0c1cc5a5192a2fd698cf827
from .. import CURRENT_NAME from ..cmd import call_cmd from .config import Configurator from .config import USER_INI from icemac.install.addressbook._compat import Path import argparse import os import pdb # noqa: T002 import sys def update(stdin=None): """Update the current address book installation.""" cur...
9,433
1e168cf6ba785a08244f47eb490b54605a09e4b0
traditional_investor_stage1 = \ "SELECT investor, investor_id, invest_amount, invest_change, security_id, isin, issue_date, maturity_date "\ "FROM "\ "(SELECT "\ "report_date, "\ "investor_holdings.investor_name AS investor,"\ "investor_id,"\ ...
9,434
8bb67317ede277e03e8cbdefefeffa3d206ece65
from os import listdir import re import numpy as np from sklearn.metrics import f1_score from sklearn.naive_bayes import MultinomialNB from sklearn.feature_extraction.text import CountVectorizer from sklearn.model_selection import LeaveOneOut import matplotlib.pyplot as plt n_gram_range = (1, 1) alpha_smoothing = 1e-1...
9,435
63068a15d750abb29398d687495d6001ba17ab8a
""""""""""""""" Write Data """"""""""""""" import json from city import City def load_json(file_name='data.json'): with open(file_name, 'r') as json_fp: json_data = json_fp.read() data_arr = json.loads(json_data) return data_arr if __name__ == '__main__': json_file = 'data.json' ...
9,436
0d022291f9ace02ef1ee5c462657ea6376a0e6a4
import RPi.GPIO as GPIO import time from datetime import datetime led1 = [('g', 40), ('f', 38), ('a', 36), ('b', 32), ('e', 26), ('d', 24), ('c', 22)] led2 = [('g', 19), ('f', 15), ('a', 13), ('b', 11), ('e', 7), ('d', 5), ('c', 3)] numbers = [ ('a', 'b', 'c', 'd', 'e', 'f'), ('b', 'c'), ('...
9,437
d190eb27ea146cf99ac7f8d29fb5f769121af60e
M, N = 3, 16 prime = set(range(M, N+1)) for i in range(2, N+1): prime -= set(range(i**2, N+1, i)) for number in prime: print(number)
9,438
56afde2a31ad9dddee35e84609dff2eb0fc6fe1a
# Mezzanine Django Framework createdb error on Max OSX 10.9.2 import django django.version
9,439
8beafcd4f9c02657a828d8c37f2aecda325ba180
import pickle from numpy import * import math import matplotlib.pyplot as plt import numpy as np from matplotlib import animation from math import factorial def savitzky_golay(y, window_size, order, deriv=0, rate=1): order_range = range(order+1) half_window = (window_size -1) // 2 b = np.mat([[k**i for i i...
9,440
f91e997b305348485698d180b97138b040285b60
class Line: def __init__(self,coor1,coor2): self.coor1 = coor1 self.coor2 = coor2 def slope(self): pass def distance(self): #x = self.coor1[0]-self.coor2[0] #y = self.coor2[1]-self.coor2[1] #return ((x**2)+(y**2))**0.5 return ((((self.coor2[0]-s...
9,441
8f854f4f2c807f988945af4dc53dba93cfb31168
## Author: Aleem Juma import os from app import app import pandas as pd # read in the quotes database q = pd.read_csv(os.path.join('app','data','quotes_all.csv'), sep=';', skiprows=1, header=0) # there are a few quote genres that don't occur in the model vocab # replace them with appropriate words so the similarity ...
9,442
82c3bde5746d04c126a93851844f775e7ce65f4b
import torch import numpy as np # source: https://github.com/krasserm/bayesian-machine-learning/blob/master/gaussian_processes.ipynb def kernel(X1, X2, l=1.0, sigma_f=1.0): ''' Isotropic squared exponential kernel. Computes a covariance matrix from points in X1 and X2. Args: X1: Array of m points (m x d). X2: Arr...
9,443
b9a262bd6ddbca3b214825a473d870e70e8b5e57
#!/usr/bin/env python import fileinput import sys import os from argparse import ArgumentParser from probin.model.composition import multinomial as mn from probin.dna import DNA from Bio import SeqIO from corrbin.misc import all_but_index, Uniq_id, GenomeGroup from corrbin.multinomial import Experiment from corrbin.co...
9,444
814191a577db279389975e5a02e72cd817254275
""" Version information for NetworkX, created during installation. Do not add this file to the repository. """ import datetime version = '2.3' date = 'Thu Apr 11 20:57:18 2019' # Was NetworkX built from a development version? If so, remember that the major # and minor versions reference the "target" (rather than "...
9,445
920f00632599945397364dd0f52f21234e17f9ef
from context import vicemergencyapi from vicemergencyapi.vicemergency import VicEmergency from geographiclib.geodesic import Geodesic from shapely.geometry import Point def geoDistance(p1, p2): return Geodesic.WGS84.Inverse(p1.y, p1.x, p2.y, p2.x)['s12'] melbourne = Point(144.962272, -37.812274) def compare(f...
9,446
fbd8af4ab3e4ebdcb07509db776d38f9c26fd06a
# # MIT License # # Copyright (c) 2018 Matteo Poggi m.poggi@unibo.it # # 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, c...
9,447
293533d07b530be9e8f97f1720619bf6c3113cca
import os import sys import string from array import * from datetime import datetime #f = open('input_test.txt', 'r') f = open('input_task.txt', 'r') width = 60 height = 5000 sleepingMinutes = [[0 for x in range(width)] for y in range(height)] infos = [] # Change lines to tuples and store to array for sorting for l...
9,448
1304b6373edeca394070b8a3d144608cf07172e3
from datetime import datetime from unittest import mock import pytest from freezegun import freeze_time from datahub.ingestion.api.common import PipelineContext from src.datahub.ingestion.source.aws.s3_util import make_s3_urn FROZEN_TIME = "2020-04-14 07:00:00" @pytest.mark.integration def test_athena_config_query...
9,449
39eecf1c7ec19f7c75721caa092c08569f53d3e5
#Classe do controlador do servidor SEEEEEEERVIDOOOOOOOOOOR from usuarioModel import * class ControllerSC: ''' O controlador define 2 ações: - adicionar_pessoa: para adicionar novas pessoas no banco de dados. - listar_pessoas: retornar a lista das pessoas Note que as 2 ações supracita...
9,450
b748c489b2c63546feada811aa3b66146ad8d28e
#!/usr/bin/python3 import json def from_json_string(my_str): """Function returns a JSON file representation of an object (string)""" return json.loads(my_str)
9,451
369bffa21b5b8c0ca1d93da3aa30a38e2f4c82cc
import scrapy from kingfisher_scrapy.base_spiders import BigFileSpider from kingfisher_scrapy.util import components, handle_http_error class France(BigFileSpider): """ Domain France Swagger API documentation https://doc.data.gouv.fr/api/reference/ """ name = 'france' # SimpleSpi...
9,452
956e63bf06255df4a36b5fa97aa62c0ed805c3f3
#!/bin/python from flask import Flask, jsonify, request import subprocess import os app = Flask(__name__) text = "" greetings = "'/play' and '/replay'\n" @app.route('/') def index(): return greetings @app.route('/play', methods=['POST']) def play(): global text text = request.data.decode('utf-8') o...
9,453
dd06847c3eb9af6e84f247f8f0dd03961d83688e
from battleship.board import Board from battleship.game import Game import string # Board row_num = list(string.ascii_lowercase[:10]) # A-J col_num = 10 board = Board(row_num, col_num) board.display_board() # Game guesses = 25 quit = 'q' game = Game(guesses, quit) game.take_shot("\nChoose a spot to fire at in enemy...
9,454
356c817e254d8885beb447aa10759fff6a45ca25
from microbit import * import music while True: if button_a.is_pressed(): music.pitch(400,500)
9,455
4569413c8ea985a010a1fea4835a5b368a23663a
#import bmm_mysql_connect # Import my connection module import csv import MySQLdb import os #bmm_mysql_connect.connect() # Connecting to mysql test database #mycur = conn.cursor() # Creating my cursor path = os.path.expanduser('~/Projects/bmm_private/login_test.txt') login = csv.reade...
9,456
fdef3e94bbeb29c25bf14e17cd1d013cf848bedc
# from magicbot import AutonomousStateMachine, timed_state, state # from components.drivetrain import Drivetrain, DrivetrainState # from components.intake import Intake # from fieldMeasurements import FieldMeasurements # class PushBotAuto(AutonomousStateMachine): # # this auto is intended to push other robots of...
9,457
8050b757c20da7ad8dd3c12a30b523b752d6a3ff
friends = ["Vino", "Ammu", "Appu"] print(friends) print(friends[0]) # returns the last element in the list print(friends[-1]) # returns the second to last element in the list print(friends[-2])
9,458
937fd6aa7bd21258bd6e0f592d94a966519ef885
''' # AWS::Chatbot Construct Library AWS Chatbot is an AWS service that enables DevOps and software development teams to use Slack chat rooms to monitor and respond to operational events in their AWS Cloud. AWS Chatbot processes AWS service notifications from Amazon Simple Notification Service (Amazon SNS), and forwar...
9,459
262d6722f4c158d0a41b22433792cdc35651d156
# coding=utf-8 """ Given a binary tree, find its maximum depth. The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. Example Given a binary tree as follow: 1 / \ 2 3 / \ 4 5 The maximum depth is 3. """ """ Definition of TreeNode: """ class ...
9,460
26289d88ac51ee359faa81ca70b01879d2b1f840
pairs = ['usdt', 'btc'] warn_msg = '** WARN ** ' info_msg = '** INFO **'
9,461
2cd7d4fe87de66e85bc0d060e2eaa68be39eed02
from tasks import video_compress, video_upload if __name__ == '__main__': video_compress.apply_async(["a"],queue='high') video_compress.apply_async(["b"],queue='low') video_upload.apply_async(["c"], queue='low') video_upload.apply_async(["d"], queue='high')
9,462
bec3d8546cd7d27f7da48f5658480cf17c36a255
import os import re import sys import traceback import readline from typing import NamedTuple, List from PyInquirer import prompt from pygments import highlight from pygments.formatters.terminal import TerminalFormatter from pygments.lexers.python import PythonLexer import argparse parser = argparse.ArgumentParser(d...
9,463
4c483636316dfa660f10b1aba900813bc3e95ebe
from django.http import HttpResponseRedirect from django.shortcuts import render __author__ = 'jhonjairoroa87' from rest_framework.views import APIView from rest_framework.response import Response from rest_framework_jsonp.renderers import JSONPRenderer from django.db import models from .form import NameForm def mu...
9,464
e5abab3f718bbbd25dcfc49290383203d53248c3
import logging from exceptions.invalid_api_usage import InvalidAPIUsage from wgadget.endpoints.ep import EP class EPInfoLight(EP): NAME = 'info_light' URL = '/info' URL_ROUTE_PAR_PAYLOAD = '/' URL_ROUTE_PAR_URL = '/actuatorId/<actuatorId>' METHOD = 'GET' ATTR_ACTUATOR_ID = 'actuatorId' ...
9,465
c2b3594d25e2d1670d9b99e0d3484c680f59421f
import random import tqdm from keras.models import load_model from ModelUtil import precision, recall, f1 from tqdm import tqdm import cv2 as cv import numpy as np import os import pandas as pd from PIL import Image os.environ['CUDA_VISIBLE_DEVICES']='1' model_path = '/home/bo/Project/densenet.hdf5' train_img_path...
9,466
fedec397ac0346bad1790315b4f85fbb1a662a4e
import subprocess from dissamblerAbstract import disassemblerAbstract #lib/ZydisDisasm -64 /home/nislab2/Desktop/DissamblerEffect/metamorphic/00fe0c08024f7db771d6711787d890a3.exe class ZydisDisassembler(disassemblerAbstract): def diassemble(self,filename, bits='32bit'): """ Disassembly executa...
9,467
caf83d35ce6e0bd4e92f3de3a32221705a529ec1
#!/usr/bin/env python3 # --------------------------------------------------- # SSHSploit Framework # --------------------------------------------------- # Copyright (C) <2020> <Entynetproject> # # This program is free soft...
9,468
fb53ea6a7184c0b06fb8a4cbfaf2145cc5c2e8e2
import hlp import pdb class Nnt(list): """ Generic layer of neural network """ def __init__(self): """ Initialize the neural network base object. """ self.tag = None def y(self, x): """ build sybolic expression of output {y} given input {x} t...
9,469
54276074d84e63e6418f8738bb7f910424f1c94d
import sys import os PROJ_DIR = os.path.dirname(os.path.dirname(__file__)) sys.path.append(PROJ_DIR)
9,470
8173afbd82b8da04db4625ac686c0d052e65a21c
from PyQt4 import QtGui from PyQt4.QtCore import pyqtSignal, pyqtSlot, QObject, Qt from twisted.internet.defer import inlineCallbacks import numpy as np from connection import connection import pyqtgraph as pg from pyqtgraph.SignalProxy import SignalProxy import sys import time global harwareConfiguration class grap...
9,471
6b3f634f3f0108e678d44ef9c89150f9fd116f76
file_id = '0BwwA4oUTeiV1UVNwOHItT0xfa2M' request = drive_service.files().get_media(fileId=file_id) fh = io.BytesIO() downloader = MediaIoBaseDownload(fh, request) done = False while done is False: status, done = downloader.next_chunk() print "Download %d%%." % int(status.progress() * 100)
9,472
210199ed217db0d7a05e280f20e33496c0795f06
from base64 import b64decode import time from lampost.context.resource import m_requires from lampost.datastore.dbo import KeyDBO from lampost.datastore.dbofield import DBOField from lampost.datastore.exceptions import DataError from lampost.model.player import Player from lampost.util.encrypt import make_hash, check_...
9,473
4fba13d051a3aceb393a4473cdbf6d4fc684c7ac
fname = input('Enter the file name to open') fh = open(fname) lst1 = list() data = dict() for ln in fh : if ln.startswith("From"): if ln.startswith('From:'): continue else : word = ln.split() lst1.append(word[1]) for word in lst1: data[word] = dat...
9,474
988e1f0631c434cbbb6d6e973792a65ebbd9405e
print(4 / 2, 4 / 3, 4 / 4) print(5 / 2, 5 / 3, 5 / 4) print(4 // 2, 4 // 3, 4 // 4) print(5 // 2, 5 // 3, 5 // 4) print(4.0 / 2, 4 / 3.0, 4.0 / float(4)) print(5.0 / 2, 5 / 3.0, 5.0 / float(4)) print(4.0 // 2, 4 // 3.0, 4.0 // float(4)) print(5.0 // 2, 5 // 3.0, 5.0 // float(4))
9,475
8ae10aada79b0a687732e341d275eb3823ec0e4a
# Copyright 2021-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 agre...
9,476
8a2fe83ab1adae7de94eb168290ce4843ab39fe1
import numpy import multiprocessing from functools import partial from textutil.text import read_file from textutil.util import B import mmap import tqdm class Growable(object): def __init__(self, capacity=1024, dtype=numpy.uint32, grow=2): self.grow = grow self.capacity=capacity self.dty...
9,477
414cb9a173ac70ad9ad1fc540aec569321fd3f8b
#!/usr/bin/python # -*- coding: utf-8 -*- import sys PY2 = sys.version_info[0] == 2 if PY2: text_type = unicode string_types = basestring, else: text_type = str string_types = str, def with_metaclass(meta, *bases): # This requires a bit of explanation: the basic idea is to make a dummy # met...
9,478
ff6dc347637a81c9f6a541775646b4901d719790
import math def sieve(limit): ans = [] a = [1] * limit a[0] = a[1] = 0 for i in range(2, limit): if a[i] == 0: continue ans.append(i) for j in range(i*i, limit, i): a[j] = 0; return ans is_square = lambda x: int(math.sqrt(x) + 1e-9) ** 2 == x N = 10...
9,479
c076aed1bfff51f8edf5ab4ef029b7fa7ca2422c
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'meet.ui' # # Created by: PyQt5 UI code generator 5.8.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Dialog(object): def setupUi(self, Dialog): Dialog.setObjectName...
9,480
49ae9e90402d784fc3af3b47e96842fbfe842104
from utilities.MatplotlibUtility import * from utilities.PlotDefinitions.DrainSweep.OutputCurve import plot as importedOutputCurvePlot plotDescription = { 'name':'Chip Output Curves', 'plotCategory': 'chip', 'priority': 40, 'dataFileDependencies': ['DrainSweep.json'], 'plotDefaults': { 'figsize':(2,2.5), 'co...
9,481
51b3beee8659bccee0fbb64b80fdce18b693674b
class Solution(object): def twoSum(self, numbers, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ idx1 = 0 idx2 = len(numbers)-1 while(idx1<idx2): # can also use a for-loop: for num in numbers: left = numbers[id...
9,482
f0b5ad49fc47adc54fb16a151b4a0ed563f53a42
from bottle import response,request,route,run from json import dumps import ConfigParser import pickle import pandas as pd import numpy as np from sklearn.pipeline import Pipeline from sklearn.feature_extraction.text import CountVectorizer from sklearn.feature_extraction.text import TfidfTransformer from sklearn.cross_...
9,483
87291d066b94aca1d94cbe5d9281fc72da1b0c35
import numpy as np from StudyCaseUdemy.Graph import Graph class OrderVector: def __init__(self, size): self.size = size self.last_pos = -1 self.values = np.empty(self.size, dtype=object) def insert(self, vertex): if self.last_pos == self.size - 1: print('Capacidad m...
9,484
59170e6b0b0705b9908ed1c32bbea87373126594
#coding:utf-8 #base string opeate #rstrip()删除字符串末尾被指定的字符,默认是空格,如末尾有多个相同的字符,则一并删除 str1="djcc" str2="adcd" print("this's rstrip() function---------") print(str1.rstrip("c")) print(str1.rstrip("d")) #replace()用新字符替换字符串中被指定的字符,str.replace(old, new[, max]),max表示替换多少个,如不指定,全部替换 str3="this is history,it is not fake" prin...
9,485
896d836ede533bad24f4077e5ba964105d96bf7a
list1=[('北京大洋路', '红蛋', '散框批发', '120-125', '44', '落', '8车'), ('北京回龙观', '红蛋', '散框批发', '124', '44', '落', ''), ('北京石门', '红蛋', '散框批发', '124', '44', '落', '') ] mysql_data=[] import numpy as np for l in list1: array = np.array(l) tolist = array.tolist() tolist.insert(0,'ppp') tolist.append('lll') mysql_dat...
9,486
5dcb20f52b5041d5f9ea028b383e0f2f10104af9
from collections import deque s = list(input().upper()) new = list(set(s)) # 중복 제거 한 알파벳 리스트로 카운트 해줘야 시간초과 안남 n = {} for i in new: n[i] = s.count(i) cnt = deque() for k, v in n.items(): cnt.append(v) if cnt.count(max(cnt)) >1: print('?') else: print(max(n, key=n.get))
9,487
7618d7fde3774a04ac2005dad104e54b9988d3e8
def execute(n,dico): """ Prend en argument n, la position de la requête dans le dictionaire et dico le nom du dictionnaire. Renvoie une liste dont chaque élément est une réponse de la requête. """ l = [] import sqlite3 conn = sqlite3.connect('imdb.db') c = conn.cursor() c.execute(dic...
9,488
570e0d46aa1ea88d1784447e8f693199e3c3b6ad
from __future__ import print_function from __future__ import absolute_import # # LinkedIn Sales Module # import requests from bs4 import BeautifulSoup import logging from plugins.base import PageGrabber from plugins.colors import BodyColors as bc import json try: import __builtin__ as bi except: import builtins...
9,489
67f09cd8b41c7a4fe457766dfed916aaf71cc20d
# -*- coding: utf-8 -*- """ Created on Thu Jul 27 18:34:40 2017 @author: Peiyong Jiang :jiangpeiyong@impcas.ac.cn Wangsheng Wang : wwshunan@impcas.ac.cn Chi Feng : fengchi@impcas.ac.cn supervised by Zhijun Wang & Yuan He """ import os from ...
9,490
146487738006ce3efb5bd35c425835a1fd8e0145
# -*- coding: utf-8 -*- #some xml helpers from xml.dom.minidom import Document class XMLReport: def __init__(self, name): self.doc = Document() self.main_node = self.add(name, node=self.doc) def add(self, name, node=None): if node is None: node = self.main_node elem = self.doc.createElement(name) ...
9,491
3bec28561c306a46c43dafc8bdc2e01f2ea06180
from mlagents_envs.registry import default_registry from mlagents_envs.envs.pettingzoo_env_factory import logger, PettingZooEnvFactory # Register each environment in default_registry as a PettingZooEnv for key in default_registry: env_name = key if key[0].isdigit(): env_name = key.replace("3", "Three")...
9,492
92dc0bd3cfcddd98f99d8152d0221f047beb4fb0
#! /usr/bin/python # -*- coding: utf8 -*- # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 import unittest from pyama.filereader import FileReader,Segment class TestFileReader(unittest.TestCase): def test_reads_file(self): reader = FileReader( "sample_reader_test.txt", regexe...
9,493
f8a31cdf5f55b5aed33a407d2c008ba9b969d655
import cv2 import glob import numpy as np import csv import matplotlib.pyplot as plt from pydarknet import Detector,Image """ Calculates the average precision based on the precision and recall values, which are essentially the output of getPrecisionRecall Returns the 101pt interpolation curve and a single av...
9,494
9bb1fc4df80d183c70d70653faa3428964b93a94
from django.db import models class FoodCategory(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, default='') class Meta: db_table = 'kitchenrock_category' def __str__(self): return self.name
9,495
f6d7ce2d020d11086640a34aac656098ab0b0f33
from datetime import date atual = date.today().year totmaior = 0 totmenor = 0 for pessoas in range (1, 8): nasc = int(input(f'Qual sua data de nascimento? {pessoas}º: ')) idade = atual - nasc if idade >= 21: totmaior += 1 else: totmenor += 1 print(f'Ao todo tivemos {totmaior} pessoas mai...
9,496
8a54a71b08d10c5da9ca440e8e4f61f908e00d54
A = input("입력해주세요.\n") #입력값을 in_AAA로 칭한다 #\n은 문법의 줄바꾸기 print(A.upper()+" World!") #in_AAA를 출력 + "World!") #upper()는 앞의 값을 대문자화+"
9,497
48755cf48c6696259d0c319d382021f33751ac01
def squirrel_play(temp, is_summer): if is_summer == True : if 60 <= temp <= 100 : return True else : return False if is_summer == False : if 60 <= temp <= 90 : return True else : return False
9,498
752679d2484b6b91a734c7cbe4a99bd5676661eb
import numpy as np def output(i, out): with open('B-large.out', 'a') as outfile: outfile.write("Case #{0}: {1}\n".format(i, out)) def solve(i, stack): cursymbol = stack[0] counter = 0 if stack[-1] == "+" else 1 for symbol in stack: if symbol != cursymbol: ...
9,499
f2d7f0b0d27bd43223d0eb6a6279b67968461dad
# binary search # iterative def Iter_BinarySearch(array,b,e,value): while(b<=e):#pay attention to the judgement! mid=(b+e)/2#floor if (array[mid]<value):#value in [mid,e] b=mid+1 elif (array[mid]>value):#value in [b,mid] e=mid-1 else: print "find ...