index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
4,700
e12ca2c4592a629ce78cae7211fedaf02352a603
from .lasot import Lasot from .got10k import Got10k from .tracking_net import TrackingNet from .imagenetvid import ImagenetVID from .imagenetdet import ImagenetDET from .coco_seq import MSCOCOSeq from .vot import VOT from .youtube_vos import YoutubeVOS from .youtube_bb import YoutubeBB
4,701
9e793bd0faef65dfe8ac4b722e50d2055837449f
from googleAPI.drive import * class GoogleSheet(GoogleDrive): """ The base class of Google Sheet API. It aims at dealing with the Google Sheet data extract and append. It is not tied to a specific spreadsheet. This class is powered by pandas. Thus, make sure the data in the spreadshe...
4,702
8054ccb07d0130b75927a4bb9b712ce3d564b8fe
""" Test cases for ldaptor.protocols.ldap.delta """ from twisted.trial import unittest from ldaptor import delta, entry, attributeset, inmemory from ldaptor.protocols.ldap import ldapsyntax, distinguishedname, ldaperrors class TestModifications(unittest.TestCase): def setUp(self): self.foo = ldapsyntax.L...
4,703
18366633489d905c96b0c30d65442bc2e2b188ea
from datetime import datetime from iohelpers import lines_to_textfile from typing import Iterator, List, Sequence from zhmodules import ZhTopolectSynonyms, MandarinPronunciations, ZhTopolectPronunciations def missing_philippine_hokkien_words_generator(synonyms: ZhTopolectSynonyms, hokprons: ZhTopolectPronunciations):...
4,704
987579da6b7ae208a66e375e0c9eca32b97199c5
import json from django import template from django.core.serializers.json import DjangoJSONEncoder from django.utils.safestring import mark_safe register = template.Library() @register.filter def jsonify(object): return mark_safe(json.dumps(object, cls=DjangoJSONEncoder)) @register.simple_tag def get_crop_ur...
4,705
ee2cf6c472fa955ba3718bf3a3f60b66811b4907
import logging from blogofile.cache import bf github = bf.config.controllers.github from github2.client import Github github_api = Github() config = { "name": "Github", "description": "Makes a nice github project listing for the sidebar", "priority": 95.0, } def get_list(user): """ Each item...
4,706
6efc7ff304a05dfc5a7bed7d646e5d6ac034ce85
''' 단어 수학 시간 : 68ms (~2초), 메모리 : 29200KB (~256MB) 분류 : greedy ''' import sys input = sys.stdin.readline # 입력 N = int(input()) # 단어의 개수 arr = [list(input().strip()) for _ in range(N)] # 풀이 alphabet = [] for word in arr: for a in word: if a not in alphabet: alphabet.append(a) value_list = [] ...
4,707
15c61dbf51d676b4c339dd4ef86a76696adfc998
class MiniMaxSearch(object): def __init__(self): self.count = 0 self.explored = set() def max_value(self, state, a, b): self.count += 1 value = float('-inf') if state in self.explored: return state.evaluate() if state.terminal(): self....
4,708
791935f63f7a0ab2755ad33369d2afa8c10dffbb
#! /usr/bin/env python import roslib roslib.load_manifest('learning_tf') import rospy import actionlib from geometry_msgs.msg import Twist from turtlesim.msg import Pose from goal.msg import moveAction, moveGoal if __name__ == '__main__': rospy.init_node('move_client') client = actionlib.SimpleActionClient('...
4,709
18f9e55b62b30ce8c9d4a57cd9c159543a738770
from flask import Flask,render_template, redirect, url_for,request, jsonify, abort,request from flask_sqlalchemy import SQLAlchemy from src.flaskbasic import * from src.flaskbasic.form import StudentForm from src.flaskbasic.models import Student import sys import logging # logging.basicConfig(filename='app.log...
4,710
9ca5c052db43c1d8b0cafa18038b3ebcd80067f7
import json import os import ssl from ldap3 import Server, Connection, Tls, SUBTREE, ALL # Include root CA certificate path if you use a self signed AD certificate SSL_CERT_PATH = "path/to/cert.pem" # Include the FQDN of your Domain Controller here FQDN = "ad.example.com" # Search base is the CN of the container w...
4,711
ecc001394c1f3bba78559cba7eeb216dd3a942d8
#(C)Inspire Search 2020/5/31 Coded by Tsubasa Kato (@_stingraze) #Last edited on 2020/6/1 11:36AM JST import sys import spacy import re #gets query from argv[1] text = sys.argv[1] nlp = spacy.load('en_core_web_sm') doc = nlp(text) ahref = "<a href=\"" ahref2 = "\"\>" #arrays for storing subject and object types sub...
4,712
36e5b0f40b8016f39120f839766db0ac518c9bed
# Author: Sam Erickson # Date: 2/23/2016 # # Program Description: This program gives the integer coefficients x,y to the # equation ax+by=gcd(a,b) given by the extended Euclidean Algorithm. def extendedEuclid(a,b): """ Preconditions - a and b are both positive integers. Posconditions - The equation for ax...
4,713
3ce9c0aeb6b4e575fbb3fced52a86a1dcec44706
import datetime from collections import defaultdict from django.db.models import Prefetch from urnik.models import Termin, Rezervacija, Ucilnica, DNEVI, MIN_URA, MAX_URA, Srecanje, Semester, RezervacijaQuerySet class ProsteUcilniceTermin(Termin): HUE_PRAZEN = 120 # zelena HUE_POLN = 0 # rdeca def __i...
4,714
25532102cc36da139a22a61d226dff613f06ab31
import time, json, glob, os, enum import serial import threading import responder # 環境によって書き換える変数 isMCUConnected = True # マイコンがUSBポートに接続されているか SERIALPATH_RASPI = '/dev/ttyACM0' # ラズパイのシリアルポート SERIALPATH_WIN = 'COM16' # Windowsのシリアルポート # 各種定数 PIN_SERVO1 = 12 # GPIO12 PWM0 Pin PIN_SERVO2 = 13 # GP...
4,715
6abc8b97117257e16da1f7b730b09ee0f7bd4c6e
import datetime import traceback import sys import os def getErrorReport(): errorReport = ErrorReport() return errorReport class ErrorReport(): def __init__(self): return def startLog(self): timestamp = str(datetime.datetime.now()) fileName = 'Log_'+timestamp+'.txt....
4,716
b6529dc77d89cdf2d49c689dc583b78c94e31c4d
from django import forms class CriteriaForm(forms.Form): query = forms.CharField(widget=forms.Textarea)
4,717
c9079f27e3c0aca09f99fa381af5f35576b4be75
from __future__ import unicode_literals import json class BaseModel(object): def get_id(self): return unicode(self.id) @classmethod def resolve(cls, id_): return cls.query.filter_by(id=id_).first() @classmethod def resolve_all(cls): return cls.query.all()
4,718
6822a0a194e8b401fecfed2b617ddd5489302389
import numpy as np # Read in training data and labels # Some useful parsing functions # male/female -> 0/1 def parseSexLabel(string): if (string.startswith('male')): return 0 if (string.startswith('female')): return 1 print("ERROR parsing sex from " + string) # child/teen/adult/senior ->...
4,719
e7bb5e9a91ec6a1644ddecd52a676c8136087941
# Generated by Django 3.0.6 on 2020-06-23 10:58 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('printer', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='printers_stat', name='type_printers', ...
4,720
14cac4f11830511923ee1ce0d49ec579aec016fd
#!/usr/bin/python # -*- coding:utf-8 -*- import epd2in7 import time from PIL import Image,ImageDraw,ImageFont import traceback try: epd = epd2in7.EPD() epd.init() epd.Clear(0xFF) time.sleep(2) epd.sleep() except: print 'traceback.format_exc():\n%s' % traceback.format_exc...
4,721
6ac13665c2348bf251482f250c0fcc1fc1a8af75
import torch from torch import nn import torch.nn.functional as F import numpy as np from config_pos import config from backbone.resnet50 import ResNet50 from backbone.fpn import FPN from module.rpn import RPN from layers.pooler import roi_pooler from det_oprs.bbox_opr import bbox_transform_inv_opr from det_oprs.bbox_...
4,722
8271935901896256b860f4e05038763709758296
## CreateDGNode.py # This files creates the boilerplate code for a Dependency Graph Node import FileCreator ## Class to create Maya DG node plugin files class DGNodeFileCreator(FileCreator.FileCreator): ## Constructor def __init__(self): FileCreator.FileCreator.__init__(self, "DGNodePluginData.json") self.writ...
4,723
3775ba538d6fab13e35e2f0761a1cacbe087f339
# This file is Copyright (c) 2020 LambdaConcept <contact@lambdaconcept.com> # License: BSD from math import log2 from nmigen import * from nmigen.utils import log2_int from nmigen_soc import wishbone from nmigen_soc.memory import MemoryMap from lambdasoc.periph import Peripheral class gramWishbone(Peripheral, Elab...
4,724
b2eb2d006d6285947cc5392e290af50f25a9f566
from app_auth.recaptcha.services.recaptcha_service import validate_recaptcha from django.shortcuts import render, redirect from django.contrib import auth from django.views import View from rest_framework.permissions import IsAuthenticated from rest_framework.views import APIView from rest_framework.response import Res...
4,725
b2db622596d0dff970e44759d25360a62f5fea83
ALPHABET = 'abcdefghijklmnopqrstuvwxyz' # Convert the ALPHABET to list ALPHABET = [i for i in ALPHABET] output_string = '' input_string = input('Enter a String : ') key = int(input('Enter the key: ')) for letter in input_string: if letter in input_string: # ALPHABET.index(letter) returns the index of that...
4,726
176120d4f40bc02b69d7283b7853b74adf369141
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2019/6/26 16:11 # @Author : Micky # @Site : # @File : 01_压缩相关知识.py # @Software: PyCharm import numpy as np from PIL import Image from scipy import misc if __name__ == '__main__': # 图像加载 image = Image.open('../datas/xiaoren.png') # 图像转换为num...
4,727
eda8bde048f3d4c4af4bd1c296e4cc02b92eaa17
# Kai Joseph # Loop Practice # Since I worked on my own, I did not have to complete all 25 challenges (with Ms. Healey's permission). I completed a total of 14 challenges. import sys import random ''' 1. Write a for loop that will print out all the integers from 0-4 in ascending order. ''' if sys.argv[1] == '...
4,728
5cec9e82aa994d07e25d8356a8218fc461bb8b4e
#!/usr/bin/python #import Bio def findLCS(read, cassette, rIndex, cIndex,cassettes): LCS='' while True: if read[rIndex] == cassette[cIndex]: LCS+= read[rIndex] rIndex= rIndex +1 cIndex= cIndex +1 #elif checkLCS(cIndex,cassettes)==True: else: break #print(LCS) ret...
4,729
7d4d5ca14c3e1479059f77c6a7f8dcfad599443b
import os import csv from django.core.management.base import BaseCommand, CommandError from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from aec.apps.vocabulary.serializers import DictionarySerializer from aec.apps.vocabulary.models import Word from aec.apps.library.serializers i...
4,730
e97bcf31657317f33f4a138ede80bb9171337f52
import qrcode def generate_qr(query): img = qrcode.make(query)
4,731
f4fca5ce20db0e27da11d76a7a2fd402c33d2e92
# Dependancies import pandas as pd # We can use the read_html function in Pandas # to automatically scrape any tabular data from a page. # URL of website to scrape url = 'https://en.wikipedia.org/wiki/List_of_capitals_in_the_United_States' # Read HTML tables = pd.read_html(url) tables # What we get in return is a ...
4,732
96ef95d8997eeab3d85a1bb6e4f8c86c9bfbb0a2
import sys from PIL import Image from pr_common import * file_name = sys.argv[1] saturation_color = sys.argv[2] saturation_modifier = int(sys.argv[3]) img = getImage(file_name) pixels = pixelValues(img) for i in range(img.height): for j in range(img.width): pixel_val = pixels[i][j] color_idx = No...
4,733
dcc85b143f2394b7839f2fb9c2079a7dd9fa8e88
from binance.client import Client from binance.websockets import BinanceSocketManager from binance.enums import * import time import threading import winsound # Replace your_api_key, your_api_secret with your api_key, api_secret client = Client(your_api_key, your_api_secret) # Calculate list of symbols def calculate...
4,734
a63718ba5f23d6f180bdafcb12b337465d6fa052
from bs4 import BeautifulSoup import os, re, json import pandas as pd from urllib import request from openpyxl import load_workbook from bilibili.append_xlsx import append_df_to_excel # 获取页面的所有的avid, title, url def parse_html(content): arr = [] # 使用beautifulsoup解析html文档 soup = BeautifulSoup(content) ...
4,735
a929bfbe2be6d8f93cafa5b6cc66c7506037ffca
# Sets up directories MusicDir = "AudioFiles\\" ModelsDir = "Models\\" MonstersDir = "Models\\Monsters\\"
4,736
2cb0f2fbf3ceddb2f1ee65614506dbfb3b5c8089
# player input is: Word made, starting tile position of the word made, horizontal or vertical # example: playerinput = ['STRING', (0, 1), 'v'] import numpy as np import string def boundarytester(playerinput): # to check whether the player is placing the tiles within the confines of the board if playerinput[1][0]...
4,737
e403a84ec2a3104cb908933f6949458cccc791c3
# encoding: utf-8 # -*- coding: utf-8 -*- """ The flask application package. """ #parse arguments from flask import Flask from flask_cors import CORS import argparse parser = argparse.ArgumentParser() parser.add_argument('-t', '--testing', action='store_true') #to use the testing database parser.add_argument('-i', ...
4,738
2dcb2d8d41096f0affe569d8ddbdd190885d5f14
"""deserialization tools""" import typing as t from datetime import datetime from functools import partial from toolz import compose, flip, valmap from valuable import load, xml from . import types registry = load.PrimitiveRegistry({ bool: dict(true=True, false=False).__getitem__, datetime: partial(flip(...
4,739
68319663aad13b562e56b8ee25f25c7b548417df
from django.contrib import admin from django.urls import path, include from accounts import views urlpatterns = [ path('google/login', views.google_login), path('google/callback/', views.google_callback), path('accounts/google/login/finish/', views.GoogleLogin.as_view(), name = 'google_login_todjango'), ]...
4,740
1913bbffd8c3c9864a8eeba36c6f06e30d2dd2c8
# phase 3 control unit #Dennis John Salewi,Olaniyi Omiwale, Nobert Kimario from MIPSPhase1 import BoolArray class RegisterFile: def __init__(self): # The register file is a list of 32 32-bit registers (BoolArray) # register 29 is initialized to "000003E0" the rest to "00000000" # an instanc...
4,741
5fc097518b6069131e1ca58fa885c6ad45ae143c
#!/usr/bin/env python #lesson4.py # See original source and C based tutorial at http://nehe.gamedev.net #This code was created by Richard Campbell '99 #(ported to Python/PyOpenGL by John Ferguson 2000) #John Ferguson at hakuin@voicenet.com #Code ported for use with pyglet by Jess Hill (Jestermon) 2009 #jestermon.wee...
4,742
933758002c5851a2655ed4c51b2bed0102165116
def entete(): entete=''' <!DOCTYPE HTML> <html lang=“fr”> <head> <title>AMAP'PATATE</title> <meta charset="UTF-8" /> <link rel="stylesheet" type="text/css" href="/IENAC15/amapatate/css/font-awesome.min.css" /> <link rel="s...
4,743
51f171b3847b3dbf5657625fdf3b7fe771e0e004
from pointsEau.models import PointEau from django.contrib.auth.models import User from rest_framework import serializers class PointEauSerializer(serializers.ModelSerializer): class Meta: model = PointEau fields = [ 'pk', 'nom', 'lat', 'long', ...
4,744
9e77385933cf6e381f25bea9020f909d5dc6817d
# -*- coding: utf-8 -*- """ Description: This modules is used for testing. Testing is performed based on the list of commands given to perform in a website Version : v1.5 History : v1.0 - 08/01/2016 - Initial version v1.1 - 08/05/2016 - Modified to accept List input. ...
4,745
972a063bab35926472be592e6a17d450034fbf37
import graphene from django.core.exceptions import ValidationError from ....app import models from ....app.error_codes import AppErrorCode from ....permission.enums import AppPermission, get_permissions from ....webhook.event_types import WebhookEventAsyncType from ...account.utils import can_manage_app from ...core.m...
4,746
594fdec916520014faff80dd06c7a5553320664d
#recapitulare polimorfism class Caine: def sunet(self): print("ham ham") class Pisica: def sunet(self): print("miau") def asculta_sunet(tipul_animalului):# astapta obiect tipul animalului tipul_animalului.sunet()# CaineObj=Caine()#dau obiect PisicaObj=Pisica() asculta_sunet(Cain...
4,747
2f16c74e51789dd06bfc1fe1c6173fa5b0ac38cd
import numpy as np import heapq class KdNode: """ node of kdtree. """ def __init__(self, depth, splitting_feature, splitting_value, idx, parent): """ :param depth: depth of the node. :param splitting_feature: split samples by which feature. :param splitting_value: split...
4,748
30d891c18f3635b7419fa0d0539b2665ad60b22c
l = input().split("+") l.sort() print('+'.join(l))
4,749
a4f56b1f93f62d80707367eaba0bba7ef4b2caca
import scipy.io as sio import glob import numpy as np import matplotlib.pyplot as plt import math import os,sys BIN = os.path.expanduser("../tools/") sys.path.append(BIN) import myfilemanager as mfm import mystyle as ms import propsort as ps from functools import partial from scipy.ndimage import gaussian_filter1d ...
4,750
45d69194e14e8c20161e979d4ff34d0b90df4672
#!/usr/bin/env python3 import re import subprocess PREFIX = "Enclave/" OBJ_FILES = [ # "Enclave.o", "p_block.o", # "symbols.o", "runtime.o", "primitives.o", "unary_op.o", "unary/isna.o", "unary/mathgen.o", "unary/mathtrig.o", "unary/plusminus.o", "unary/summary.o", "unar...
4,751
0c3947a1699c78080661a55bbaa9215774b4a18e
import argparse from flower_classifier import FlowerClassifier from util import * parser = argparse.ArgumentParser() parser.add_argument("data_dir", help="path to training images") parser.add_argument("--save_dir", default=".", help="path where checkpoint is saved") parser.add_argument("--arch", default="vgg11", help=...
4,752
6767302869d73d041e2d7061722e05484d19f3e0
import datetime,os def GetDatetimeFromMyFormat(l): # l = "2018-5-17 19:18:45" l_words = l.split() l_days = l_words[0].split('-') l_times = l_words[1].split(':') out = datetime.datetime(int(l_days[0]),int(l_days[1]),int(l_days[2]),int(l_times[0]),int(l_times[1]),int(l_times[2])) return out
4,753
2362c9a12f97f32f6136aaf16a55cf4acbaf9294
# coding: utf-8 """ Idomoo API OpenAPI spec version: 2.0 Contact: dev.support@idomoo.com """ import pprint import six class GIFOutput(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: ...
4,754
df92166378c8a8cc0ba02d0ba33d75bbd94510a7
from flask import Flask, render_template , request import joblib # importing all the important libraires import numpy as np import pandas as pd import nltk import string from nltk.corpus import stopwords from sklearn.model_selection import train_test_split from sklearn.feature_extraction.text import TfidfV...
4,755
c0ebf10b8c0cb4af11608cafcdb85dbff4abdf90
""" Find two distinct numbers in values whose sum is equal to 100. Assign one of them to value1 and the other one to value2. If there are several solutions, any one will be marked as correct. Optional step to check your answer: Print the value of value1 and value2. """ values = [72, 50, 48, 50, 7, 66, 62...
4,756
6f53a989ddf179b699186a78b5d8cf6d3d08cbb2
import os import urllib.request import zipfile import tarfile import matplotlib.pyplot as plt %matplotlib inline from PIL import Image import numpy as np # フォルダ「data」が存在しない場合は作成する data_dir = "./data/" if not os.path.exists(data_dir): os.mkdir(data_dir) # MNIStをダウンロードして読み込む from sklearn.datasets import fetch_open...
4,757
b0818b545ab47c27c705f2ccfa3b9edb741602f7
from django.shortcuts import render, render_to_response, get_object_or_404, redirect from .models import Club from .forms import InputForm # Create your views here. def base(request): return render(request, 'VICHealth_app/base.html') def index(request): return render(request, 'VICHealth_app/index.html') def ...
4,758
8e3b26826752b6b3482e8a29b9b58f5025c7ef58
""" File: ex17_map_reduce.py Author: TonyDeep Date: 2020-07-21 """ from functools import reduce print('#1 map') a_list = [2, 18, 9, 22, 17, 24, 8, 12, 27] map_data = map(lambda x: x * 2 + 1, a_list) new_list = list(map_data) print(new_list) print('\n#2 reduce') b_list = [1, 2, 3, 4, 5] reduce_data = reduce(lambda x,...
4,759
8f7b1313ba31d761edcadac7b0d04b62f7af8dff
"""Sherlock Tests This package contains various submodules used to run tests. """ import sys import os import subprocess as sp from time import sleep # uncomment this if using nose sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '../sherlock'))) # import sherlock
4,760
7247ef463998f6738c21ad8efa988a32f7fb99c0
from share_settings import Settings import urllib.request,json import pprint as p s = Settings() prefix = "http://finance.google.com/finance?client=ig&output=json&q=" def get(symbol,exchange): url = prefix+"%s:%s"%(exchange,symbol) u = urllib.request.urlopen(url) #translates url to string c = u.re...
4,761
35921b081e8e8c4da2b16afc20b27b636e9a6676
import numpy from scipy.optimize import OptimizeResult from logging import getLogger logger = getLogger(__name__) def minimize_neldermead(func, x0, args=(), callback=None, maxiter=None, maxfev=None, disp=False, return_all=False, initial_simplex=None, ...
4,762
9d07fd14825ed1e0210fa1f404939f68a3bb039c
import wizard import report
4,763
ea86a2a9068c316d3efcbcb165a8ef3d3516ba1b
from HurdleRace import hurdleRace from ddt import ddt, data, unpack import unittest class test_AppendAndDelete3(unittest.TestCase): def test_hurdleRace(self): height = [1, 6, 3, 5, 2] k = 4 sum_too_high = hurdleRace(k, height) self.assertEqual(2, sum_too_high)
4,764
52bb10e19c7a5645ca3cf91705b9b0affe75f570
# Opus/UrbanSim urban simulation software. # Copyright (C) 2010-2011 University of California, Berkeley, 2005-2009 University of Washington # See opus_core/LICENSE from opus_core.variables.variable import Variable from variable_functions import my_attribute_label class total_land_value_if_in_plan_type_group_SS...
4,765
b240e328ee6c5677991d3166c7b00f1b3a51787e
import numpy as np from matplotlib import pylab as plt from os import listdir,path from os.path import isfile,join,isdir def get_files(directory_path): dirpath=directory_path files=[f for f in listdir(dirpath) if (isfile(join(dirpath, f)) and ".npy" in f)] files=sorted(files) n_files=len(files) pr...
4,766
3f4f396d1d18611e0248a08b42328422ca4b8146
import copy from typing import List, Optional, Tuple, NamedTuple, Union, Callable import torch from torch import Tensor from torch_sparse import SparseTensor import time import torch_quiver as qv from torch.distributed import rpc def subgraph_nodes_n(nodes, i): row, col, edge_index = None, None, None return r...
4,767
e488761c15ee8cddbb7577d5340ee9001193c1a4
print(10-10) print(1000-80) print(10/5) print(10/6) print(10//6) # remoção das casas decimais print(10*800) print(55*5)
4,768
dc9b5fbe082f7cf6cd0a9cb0d1b5a662cf3496f0
from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.models import User from django.shortcuts import render, redirect from django.urls import reverse_lazy from django.views...
4,769
9e2485554a5a8de07dd3df39cc255f2a1ea2f164
import numpy as np x = np.zeros(10) idx = [1,4,5,9] np.put(x,ind=idx,v=1) print(x)
4,770
c81fde7fb5d63233c633b8e5353fe04477fef2af
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import json import urllib2 # Es importante agregar la variable de ambiente: # export PYTHONIOENCODING='UTF-8' # para redireccionar la salida std a un archivo. def call(url): try: request = urllib2.Request(url) response = urllib2.urlopen(req...
4,771
8098b9c27689dd4168ef05c03d4ec00f67f8090e
# using python3 class Rational: def __init__(self, numer, denom): self.numer = numer self.denom = denom def __add__(self, other): return Rational( self.numer * other.denom + other.numer * self.denom, self.denom * other.denom ) def __sub__(self, oth...
4,772
66cdfdfa797c9991e5cb169c4b94a1e7041ca458
from tornado import gen import rethinkdb as r from .connection import connection from .utils import dump_cursor @gen.coroutine def get_promotion_keys(): conn = yield connection() result = yield r.table('promotion_keys').run(conn) result = yield dump_cursor(result) return result @gen.coroutine def p...
4,773
2b8f4e0c86adfbf0d4ae57f32fa244eb088f2cee
from locals import * from random import choice, randint import pygame from gameobjects.vector2 import Vector2 from entity.block import Block def loadImage(filename): return pygame.image.load(filename).convert_alpha() class MapGrid(object): def __init__(self, world): self.grid = [] self.ima...
4,774
ef04e808a2a0e6570b28ef06784322e0b2ca1f8f
import numpy as np from sklearn.decomposition import PCA import pandas as pd from numpy.testing import assert_array_almost_equal import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D from sklearn import decomposition from sklearn import datasets def transform(x): if x == 'Kama': return 0 elif x =...
4,775
ee0cf2325c94821fa9f5115e8848c71143eabdbf
from .plutotv_html import PlutoTV_HTML class Plugin_OBJ(): def __init__(self, fhdhr, plugin_utils): self.fhdhr = fhdhr self.plugin_utils = plugin_utils self.plutotv_html = PlutoTV_HTML(fhdhr, plugin_utils)
4,776
1c8622167240243da05a241e3630f79cdf36d7a8
import pytest import sys sys.path.insert(0, '..') from task_05 import task5 def test_mults(): assert task5.mults(3, 5, 10) == 23 assert task5.mults(5, 3, 10) == 23 assert task5.mults(3, 2, 10) == 32 assert task5.mults(7, 8, 50) == 364
4,777
3d7ca468a1f7aa1602bff22167e9550ad515fa79
run=[] #Creating a empty list no_players=int(input("enter the number of the players in the team :")) for i in range (no_players): run_score=int(input("Enter the runs scored by the player "+str(i+1)+":")) run.append(run_score) #code for the average score of the team def average(run): print("________...
4,778
9aecf297ed36784d69e2be6fada31f7c1ac37500
import nox @nox.session(python=["3.9", "3.8", "3.7", "3.6"], venv_backend="conda", venv_params=["--use-local"]) def test(session): """Add tests """ session.install() session.run("pytest") @nox.session(python=["3.9", "3.8", "3.7", "3.6"]) def lint(session): """Lint the code with flake8. """ ...
4,779
bf7e3ddaf66f4c325d3f36c6b912b47f4ae22cba
""" Exercício 1 - Facebook Você receberá uma lista de palavras e uma string . Escreva uma função que decida quais palavras podem ser formadas com os caracteres da string (cada caractere só pode ser utilizado uma vez). Retorne a soma do comprimento das palavras escolhidas. Exemplo 1: """ # words = ["cat", "bt", "hat", ...
4,780
74ad2ec2cd7cd683a773b0affde4ab0b150d74c5
from rest_framework.generics import ListCreateAPIView, RetrieveUpdateDestroyAPIView from .serializers import ConcertSerializer from .models import Concert from .permissions import IsOwnerOrReadOnly class ConcertList(ListCreateAPIView): queryset = Concert.objects.all() serializer_class = ConcertSerializer cla...
4,781
0b7e858eb6d4a5f3cf6aca4fea994dae9f889caa
from django.urls import path from group import views app_name = 'group' urlpatterns = [ path('group/',views.CreateGroup.as_view(), name='group_create'), path('shift/',views.CreateShift.as_view(), name='shift_create'), path('subject/',views.createSubject.as_view(), name='subject_create'), ]
4,782
1573af9cdf4817acbe80031e22489386ea7899cf
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2017-12-01 16:51 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('monitor', '0001_initial'), ] operations = [ migrations.RemoveField( ...
4,783
ca00091b7ebcb9ee45b77c919c458c75e3db5b1e
#!/usr/bin/python3 """ Test of Rectangle class """ from contextlib import redirect_stdout import io import unittest from random import randrange from models.base import Base from models.rectangle import Rectangle from models.square import Square class TestRectangle(unittest.TestCase): """ Test Rectangle methods "...
4,784
80f9c4b7261a894aad2c738d976cfb8efc4d228c
import pyForp import pprint pp = pprint.PrettyPrinter(indent=4) def fib(n): if n < 2: return n return fib(n-2) + fib(n-1) forp = pyForp.pyForp() forp.start() print fib(2) forp.stop() pp.pprint(forp.dump())
4,785
919239391c6f74d0d8627d3b851beb374eb11d25
import tensorflow as tf from tensorflow.keras import Model from tensorflow.keras.layers import Dense, Flatten, Conv2D, BatchNormalization, LeakyReLU, Reshape, Conv2DTranspose import tensorflow_hub as hub from collections import Counter import numpy as np import sys sys.path.append('../data') from imageio import imwri...
4,786
515c14fcf2c3e9da31f6aba4b49296b18f04f262
#! /usr/bin/env python def see_great_place_about_large_man(str_arg): own_day_and_last_person(str_arg) print('own_case') def own_day_and_last_person(str_arg): print(str_arg) if __name__ == '__main__': see_great_place_about_large_man('use_work_of_next_way')
4,787
496c58e68d3ac78a3eb1272d61ca3603c5d843b6
""" # listbinmin.py # Sam Connolly 04/03/2013 #=============================================================================== # bin data according a given column in an ascii file of column data, such that # each bin has a minimum number of points, giving the bin of each data point as # a LIST. UNEVEN BINS. #========...
4,788
b6b8dfaa9644fa4f4c250358b89f4a30c26c317f
import sqlite3 if __name__ == '__main__': conn = sqlite3.connect('donations.sqlite') c = conn.cursor() query = """DROP TABLE IF EXISTS factions;""" c.execute(query) query = """DROP TABLE IF EXISTS members;""" c.execute(query) query = """DROP TABLE IF EXISTS bank;""" c.execute(query) ...
4,789
576bb15ad081cd368265c98875be5d032cdafd22
#!/usr/bin/env python # -*- coding: utf-8 -*- """ MIT License Copyright (c) 2016 Matt Menzenski 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 ...
4,790
47b2857ac20e46897cc1f64371868ce5174799d6
from flask_wtf import FlaskForm from wtforms import ( StringField, TextAreaField, PasswordField, HiddenField) from wtforms.fields.html5 import URLField, EmailField from flask_wtf.file import FileField from wtforms.validators import ( InputRequired, Length, Email, Optional, URL, ValidationError, Regexp) from...
4,791
f3b194bbc3c174549b64d6e6b1a8f4438a0c9d38
from ctypes import * class GF_AVCConfigSlot(Structure): _fields_=[ ("size", c_uint16), ("data", c_char), ("id", int) ]
4,792
c6b98cf309e2f1a0d279ec8dc728ffd3fe45dfdb
from io import StringIO from pathlib import Path from unittest import TestCase from doculabs.samon import constants from doculabs.samon.elements import BaseElement, AnonymusElement from doculabs.samon.expressions import Condition, ForLoop, Bind class BaseElementTest(TestCase): def assertXmlEqual(self, generated_...
4,793
0a6cb6d3fad09ab7f0e19b6c79965315c0e0d634
import json import sqlite3 import time import shelve import os from constants import * VEC_TYPES = [ ''' CREATE TABLE "{}" (ID TEXT PRIMARY KEY NOT NULL, num TEXT NOT NULL); ''', ''' CREATE TABLE "{}" (ID INT PRIMARY KEY NOT NULL, num TEXT NOT NULL); ''...
4,794
14e336005da1f1f3f54ea5f2892c27b58f2babf0
from flask import Flask import rq from redis import Redis from app.lib.job import Job from app.config import Config app = Flask(__name__) app.config.from_object(Config) app.redis = Redis.from_url('redis://') app.task_queue = rq.Queue('ocr-tasks', connection=app.redis, default_timeout=43200) app.task_queue.empty() app...
4,795
8fac4571a3a1559e297754e89375be06d6c45c2d
#これは明日20200106に走らせましょう! import numpy as np import sys,os import config2 CONSUMER_KEY = config2.CONSUMER_KEY CONSUMER_SECRET = config2.CONSUMER_SECRET ACCESS_TOKEN = config2.ACCESS_TOKEN ACCESS_TOKEN_SECRET = config2.ACCESS_TOKEN_SECRET import tweepy auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_...
4,796
cc5ad95419571d3eb2689b428e5805ad69958806
import os import sys from tensor2tensor.bin import t2t_trainer def problem_args(problem_name): args = [ '--generate_data', '--model=transformer', '--hparams_set=transformer_librispeech_v1', '--problem=%s' % problem_name, '--data_dir=/tmp/refactor_test/problems/%s/data' % problem_name, '--t...
4,797
64b254db6d8f352b2689385e70f2ea7d972c9191
# Copyright (c) 2019 Uber Technologies, 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...
4,798
dc600763b12edda05820721098e7e5bc80f74c89
from typing import List class Solution: def grayCode(self, n: int) -> List[int]: res = [0] * 2 ** n exp = 0 l = r = 1 for i in range(1, 2 ** n): res[i] += res[r - i] + 2 ** exp if i == r: exp += 1 l = r + 1 r =...
4,799
ee272fe1a023d85d818a8532055dcb5dbcb6a707
import numpy as np import tkinter as tk import time HEIGHT = 100 WIDTH = 800 ROBOT_START_X = 700 ROBOT_START_Y = 50 SLEEP_TIME = 0.00001 SLEEP_TIME_RESET = 0.2 class Environment(tk.Tk, object): def __init__(self): super(Environment, self).__init__() self.action_space = ['g', 'b'] # go, break ...