index
int64
0
1,000k
blob_id
stringlengths
40
40
code
stringlengths
7
10.4M
8,000
5e86e97281b9d18a06efc62b20f5399611e3510d
from enum import Enum EXIT_CODES = [ "SUCCESS", "BUILD_FAILURE", "PARSING_FAILURE", "COMMAND_LINE_ERROR", "TESTS_FAILED", "PARTIAL_ANALYSIS_FAILURE", "NO_TESTS_FOUND", "RUN_FAILURE", "ANALYSIS_FAILURE", "INTERRUPTED", "LOCK_HEL...
8,001
603cce951dd0f78ef3ca9dce587042b3b7f6b449
"""" You are given a tree-like data structure represented as nested dictionaries. Implement a function collect_leaves that accepts a tree and returns a list of all its leaves. A leaf is a bottom-most node in a tree. Implement a kind of unit tests via assert operator. """ from typing import Union def collect...
8,002
593d3221e34c0eef51228082d767d8516ec93ca2
y_true = [7, 3, 3, 4, 9, 9, 2, 5, 0, 0, 6, 3, 1, 6, 8, 7, 9, 7, 4, 2, 0, 1, 4, 1, 7, 7, 5, 0, 8, 0, 1, 7, 4, 2, 2, 4, 9, 3, 1, 7, 1, 2, 1, 7, 5, 9, 9, 4, 8, 5, 7, 2, 7, 5, 5, 6, 6, 1, 2, 6, 6, 5, 3, 2, 3, 8, 8, 8, 8, 5, 3, 4, 3, 2, 8, 1, 9, 0, 6, 8, 6, 1, 1, 1, 5, 4, 8, 8, 5, 5, 8, 6, 4, 4, 6, 9, 8, 1, 5, 5] y_pred_p...
8,003
f218f47acfb078877645de26c64e57f92dbcd953
import utilities import sys if __name__ == "__main__": print('I am main!') else: print(__name__) for i in range(0,6): print(i) mylist = [12, 13, 14, 13, 12] print(mylist) #Enter iterations to run [0-5] #value = -1 value = 3 while (value not in range(0,6)): try: value =...
8,004
25ee13314c7cf828b8805d9f483bd5ee12073228
from __future__ import absolute_import from __future__ import division from __future__ import print_function from .BLWecc import ( curve, setCurve, getPublicKey, getPrivateKey, getAddress as getAddressByCode, pub2add as getAddressByPublicKey, sign, verifyTx as verify, )
8,005
46f3d3681343d96889ddb073f17ff7f225486f35
my_list = [1, 2, 4, 0, 4, 0, 10, 20, 0, 1] new_list = list(filter(lambda x: x != 0, my_list)) try: new = list(map(lambda x: 2 / x, new_list)) except ZeroDivisionError: pass print(new) # def devis(n, list): # new_list = [] # for i, m_list in enumerate(list): # try: # new_list.a...
8,006
8eb08fa497ccf3ddc8f4d2b886c9e5a9bdb2e052
#!/usr/bin/python import socket, os, datetime, time, re, sys import numpy as np import matplotlib.pyplot as plt from baseband import vdif import astropy.units as u from scipy.signal import resample_poly import matplotlib.patches as patches def fbcmd(message): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM...
8,007
9dfbf14a2005aad87be82e5e482c6b0347f32f2c
# Generated by Django 3.2.9 on 2021-11-10 13:36 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('settings', '0003_auto_20210814_2246'), ] operations = [ migrations.AlterField( model_name='building', name='id', ...
8,008
1825b365032a224ed56a1814d7f6457e2add8fdd
import csv with open('healthviolations.csv', 'w') as fp: with open('Restaurant_Inspections.csv', 'rb') as csvfile: reader = csv.reader(csvfile) header = next(reader, None) writer = csv.writer(fp, delimiter=',') writer.writerow([header[0], "violation"]) for row in reader: if (row[20] != '')...
8,009
7789e54acc02fe0277ff80ce14efbcdc4ee6e7f1
import gym import random import numpy as np import statistics from collections import Counter import tflearn from tflearn.layers.core import input_data, dropout, fully_connected from tflearn.layers.estimator import regression #setup the Cartpole environment env = gym.make("CartPole-v0") env.reset() #----------Expl...
8,010
3e7df9a733c94b89d22d10883844c438444d5e2c
from __future__ import unicode_literals from django.db import models from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver PROFILE_PIC_PATH = 'users/profile_pic' class Profile(models.Model): user = models.OneToOneField(User, on_delete=mod...
8,011
746971cd6c5bf65268e89303c8f4ce98a56eb111
#!/usr/bin/env python2 # -*- coding: utf8 -*- from __future__ import print_function, division, absolute_import from flask.ext.login import current_user from . import cert_record_process as record_process_base from walis.thirdparty import thrift_client, thirdparty_svc from walis.exception.util import raise_user_exc f...
8,012
99b5ac74da95dff399c31d58e19bac65e538a34b
def main(): ' main entry point for module execution\n ' argument_spec = dict(src=dict(type='path'), replace_src=dict(), lines=dict(aliases=['commands'], type='list'), parents=dict(type='list'), before=dict(type='list'), after=dict(type='list'), match=dict(default='line', choices=['line', 'strict', 'exact', '...
8,013
841743d4e9d683827962d83a77a87c6432842add
import tkinter as tk from functools import partial from numpy import random from base import NinePalaceGame class SingleMode(NinePalaceGame): player1 = player = 'O' player2 = computer = 'X' def __init__(self): self.create_choose_one_window() super().__init__() self.main_game_wind...
8,014
c04c38d78144b6f5d3e5af4ebe9ce430e882a367
import numpy as np def get_train_batches(data_dir='/home/yunhan/batchified'): """ return a list or generator of (large) ndarrays, in order to efficiently utilize GPU """ # todo: read in data that is preoprocessed # Use batch 1 - 52 as train (60%), 53 - 71 as validation (20%), 72 - 89 a...
8,015
fe82a46a7965b27729ff5bd61c1059416c96cae7
print("""Hello world""") print("Hello again") print('Hello again')
8,016
108c8bbb4d3dbc6b7f32e084b13009296b3c5a80
import serial import time def main(): # '/dev/tty****' is your port ID con=serial.Serial('/dev/tty****', 9600) print('connected.') while 1: str=con.readline() # byte code print (str.strip().decode('utf-8')) # decoded string if __name__ == '__main__': main()
8,017
62ca95a871c16191fb8f56213646e8173f400630
import streamlit as st st.write('hi')
8,018
a1c5d86a3f042d9e5ba522726191c8aeb9b738ed
import os from dataclasses import dataclass from dotenv import load_dotenv from fastapi.security import OAuth2PasswordBearer from passlib.context import CryptContext load_dotenv() @dataclass class Settings: SECRET_KEY = os.getenv("SECRET_KEY", "mysecret") ALGORITHM = "HS256" ACCESS_TOKEN_EXPIRE_MINUTES ...
8,019
8cfab525ab3a86dd6964475d5621fdc7c6413e38
"""Secret Garden tests.""" from secret_garden import Decoder, SecretGarden import random filename = "pr08_example_data.txt" key = "Fat Chocobo" d = Decoder(filename, key) s = SecretGarden(filename, key) def test_read_from_file(): """ Test of function of reading data from file. :return: """ readi...
8,020
2a3f9c4518df337cfc5e4b1816e7b2b4af62c101
#!/usr/bin/env python3 import unittest import solution class TestMethods(unittest.TestCase): def LinkedListFromArray(self, values): if len(values) > 0: headNode = solution.ListNode(values[0], None) tailPtr = headNode if len(values) > 1: for value in val...
8,021
3f4b05a1d0c4c2a2b085a0265bafbf89b5635e31
import pandas as pd import statistics import csv df = pd.read_csv("height-weight.csv") heightlist = df["Height(Inches)"].to_list() weightlist = df["Weight(Pounds)"].to_list() heightmean = statistics.mean(heightlist) heightmedian = statistics.median(heightlist) heightmode = statistics.mode(heightlist) heigh...
8,022
b137fc40a5b2dec63c7abb6953664a969f5c126f
def equals(left, right, tol=0.001): """ Tests equality of left and right Rosalind allows for a default [absolute] error of 0.001 in decimal answers unless otherwise stated. """ try: left = left.strip() right = right.strip() except AttributeError: pass try: ...
8,023
11e9d25c30c8c9945cfa3c234ffa1aab98d1869e
from math import gcd from random import randint, choice task = """6. Реализовать алгоритм построения ПСП методом Фиббоначи с запаздываниями. Обосновать выбор коэффициентов алгоритма. Для начального заполнения использовать стандартную линейную конгруэнтную ПСП с выбранным периодом. Реализовать возможность для пользоват...
8,024
fbfc1749252cf8cbd9f8f72df268284d3e05d6dc
def regexp_engine(pattern, letter): return pattern in ('', '.', letter) def match_regexp(pattern, substring): if not pattern: # pattern is empty always True return True if substring: # if string is not empty try the regexp engine if regexp_engine(pattern[0], substring[0]): # if reg and ...
8,025
46a3c3777d90976c7d39772d2e94430506d3acd7
""" Day 2 """ with open('input.txt', 'r') as f: lines = f.read() lines = lines.split('\n')[:-1] lines = [l.split(' ') for l in lines] valid = 0 new_valid = 0 for cur_pw in lines: letter = cur_pw[1].strip(':') amount = cur_pw[2].count(letter) rule = cur_pw[0].split('-') rule = [int(r) for r in ru...
8,026
fc89fdf17f887ea398be5b36d4d6f0444d64b3e0
"""script for subpixel experiment (not tested) """ import numpy as np from tqdm import tqdm import logging from pathlib import Path import paddle import paddle.optimizer import paddle.io from utils.loader import dataLoader from utils.loader import modelLoader from utils.loader import pretrainedLoader from utils.tools...
8,027
d4b9403366a16dfbb12a2161a996e641b3a785a5
# __author__: Stanley # date: 2018/10/22 class Foo: def __init__(self, name, age): self.name = name self.age = age def __getitem__(self, item): return item + 10 def __setitem__(self, key, value): print(key, value) def __delitem__(self, key): print(key) obj =...
8,028
779e7cd05edfd74c8e60eaf5ce8443aea5fdaaef
#!/usr/bin/python2.7 # -*- coding: utf-8 -*- """ # @Time : 20-6-9 上午11:47 # @Author : zhufa # @Software: PyCharm """ """ tensorflow version must below 1.15 """ import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", ...
8,029
1221394dfb97cbbfb00b412f60d4df521acc1262
# MODULES import sys sys.path.append('~/Documents/Project_3/REPO') from scipy import * from scipy import linalg import cPickle as pickle import ConfigParser import TobySpectralMethods as tsm config = ConfigParser.RawConfigParser() fp = open('config.cfg') config.readfp(fp) N = config.getint('General', 'N') M = config....
8,030
177401f25471cf1cbd32dd0770acdc12bf271361
import os from NeuralEmulator.Configurators.NormalLeakSourceConfigurator import NormalLeakSourceConfigurator from NeuralEmulator.Configurators.OZNeuronConfigurator import OZNeuronConfigurator from NeuralEmulator.Configurators.PulseSynapseConfigurator import PulseSynapseConfigurator from NeuralEmulator.NormalLeakS...
8,031
c2d6e4286e1b9d6dc852bde994da60d353e03e5c
from youtube_transcript_api import YouTubeTranscriptApi transcript_list = YouTubeTranscriptApi.list_transcripts('i8pOulVUz0A') transcript = transcript_list.find_transcript(['en']) transcript = transcript.fetch() with open("transcript.txt", 'w') as f: for line in transcript: f.write(line['text']+ '\n')
8,032
18c4c1e1ee0df835895397488b270a47b1620c30
with open('dwarfs.txt') as fh: i = 1 for line in fh: print("[%d] %s" % (i, line)) i += 1
8,033
08b57c00beb8dfedfee1bc032b8c281d7a151931
# Copyright (C) 2010 Google Inc. All rights reserved. # Copyright (C) 2010 Gabor Rapcsanyi (rgabor@inf.u-szeged.hu), University of Szeged # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of so...
8,034
40e2b695d8aaaa82cb90694b85d12061b4e6eca8
import matplotlib.pyplot as plt x_int = list(range(1, 5001)) y_int = [i**3 for i in x_int] plt.scatter(x_int, y_int, c=y_int, cmap=plt.cm.Blues, s=40) plt.show()
8,035
8d48b5b831edb62b2d9624bc23cae45d390fd224
# pylint: disable=C0103, C0413, E1101, W0611 """Covid Catcher Backend""" import os from os.path import join, dirname import json import requests import flask from flask import request import flask_sqlalchemy import flask_socketio from dotenv import load_dotenv from covid import get_covid_stats_by_state from covid impor...
8,036
092242cdb231e09ccf3dd4dccfb6d786c3e4aad2
from django.db import models # Create your models here. class GameGenre(models.Model): genreName = models.CharField(max_length=100) genreDescription = models.CharField(max_length=300) def __str__(self): return "%s" % (self.genreName) class Game(models.Model): gameName = models.CharField(...
8,037
9e314cdf4ef09ecf4a4b43358ae32f76c40aaea8
import os import redis import requests import lxml.html ads_api_url = "http://adslabs.org/adsabs/api/search/" ads_html_url = "http://labs.adsabs.harvard.edu/adsabs/abs/" rdb = redis.Redis() def get_dev_key(): # Credit: Andy Casey ads_dev_key_filename = os.path.abspath( os.path.expanduser("~/.ads/dev...
8,038
92bcfff733e5f305ad1276ceb39a72a8f0fcb214
import argparse import tensorboardX as tb import torch as th import torch.nn.functional as F import torch.optim as optim import torch.utils.data as D import data import mlp import resnet import utils parser = argparse.ArgumentParser() parser.add_argument('--bst', nargs='+', type=int, help='Batch Size for Training') pa...
8,039
88390f411af90d494284617ef8f5fb0e9bb8890e
def memo(fn): cache = {} missed = object() def query(*args): result = cache.get(args, missed) if result is missed: result = cache[args] = fn(*args) return result return query @memo def cal_edit_distance(ori, tar): def edit_tuple(old, distance, path): r...
8,040
e6efd2de5f92d66f1b734a2173fc8681af3c4cc8
def myswap(a, b): temp = a a = b b = temp if a < b: print(a, b) else: print(b, a) a, b = map(int,input().split()) myswap(a,b)
8,041
ba85f3c8a9e40f30076c13487a97567f7bc646dc
import numpy as np from scipy import stats a = np.random.normal(25.0, 5.0, 10000) b = np.random.normal(26.0, 5.0, 10000) print(stats.ttest_ind(a, b)) # bad change, with a ery low chance of randomness b = np.random.normal(25.0, 5.0, 10000) print(stats.ttest_ind(a, b)) # no change, outcome is likely random
8,042
2ec8b9a92f8dd42faf99f0cd569ebf356e12c1d6
'''It can be seen that the number, 125874, and its double, 251748, contain exactly the same digits, but in a different order. Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits. ''' import common import itertools def digits(x): return set(int(d) for d in str(x)) commo...
8,043
b3758e42b52bb50d806832c6a3a76ae0537266de
'''harvestPRR: analyze Public Record Requests from CSV data provided by NextRequest Created 27 Aug 20 @author: rik@electronicArtifacts.com ''' from collections import defaultdict import csv import datetime import json import random import re import requests import sys import time import urllib import re PRRDateFm...
8,044
63bd8a15dd489844968f46c4b0ffe157d567537a
# Make coding more python3-ish from __future__ import (absolute_import, division, print_function) __metaclass__ = type import os import pwd import sys from string import ascii_letters, digits from ConfigParser import SafeConfigParser # copied from utils, avoid circular reference fun :) def mk_boolean(value): if...
8,045
647258ee5f2f6f1cb8118bcf146b8959c65b70cd
import numpy as n, pylab as p from scipy import stats as st a=st.norm(0,1) b=st.norm(0.1,1) domain=n.linspace(-4,4,10000) avals=a.cdf(domain) bvals=b.cdf(domain) diffN=n.abs(avals-bvals).max() a=st.norm(0,1) b=st.norm(0,1.2) domain=n.linspace(-4,4,10000) avals=a.cdf(domain) bvals=b.cdf(domain) diffN2=n.abs(avals-bvals...
8,046
94540561ba29d2fc1766dac7b199e0cbbbeecdfc
# name: Ali # date: 7/12/2016 # description: uses openweathermap.org's api to get weather data about # the city that is inputted # unbreakable? = idk import json import urllib2 from collections import OrderedDict from pprint import pprint api_key = "&APPID=507e30d896f751513350c41899382d89" city_name_url = "http://api....
8,047
f633496f1a7cd562fd41d697a2e26831ceaef479
__all__ = ["loading"] from . import loading
8,048
d8df9a9f95a1d4a9aa34987ec1244cc6c0c7c610
# Generated by Django 2.0.3 on 2018-03-24 07:53 import django.core.files.storage from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ('printers', '0001_initial'), ('devices', '0002_url'), ] operations = [ migration...
8,049
0ad71f02e37f2744036b134c33e037a724fd38a6
import numpy as np import matplotlib.pyplot as plt from PIL import Image import cv2 import openslide class QualityPatch(): def __init__(self, original_img_path,label_img_path,patch_level,patch_size): """ parameter: original_img_path(str): the source of image label_img_path(s...
8,050
d520f9d681125937fbd9dff316bdc5f922f25ff3
"""Seed file to make sample data for pets db.""" from models import db, User, Feedback from app import app # Create all tables db.drop_all() db.create_all() # If table isn't empty, empty it User.query.delete() Feedback.query.delete() # Add users and posts john = User(username="John",password="123",email="24",first...
8,051
83815acb0520c1f8186b0b5c69f8597b1b6a552a
#! /usr/bin/env python from game_calc import * def game(screen, clock): running = True time = 0 WHITE = (255,255,255) BLUE = (0,0,205) upper_border = pygame.Rect(12,44,1000,20) right_border = pygame.Rect(992,60,20,648) left_border = pygame.Rect(12,60,20,648) down_border = pygame.Rect(12...
8,052
346df9706dc222f43a77928964cd54e7d999a585
import discord class Leveling: __slots__ = ( 'sid', 'channelID', 'message', 'noxpchannelIDs', 'noxproleID', 'remove', 'bot', 'roles') sid: int channelID: int message: str noxpchannelIDs: list[int] noxproleID: int remove: bool roles: list[list] def __init__(self, bot, sid,...
8,053
14807568af046594644095a2682e0eba4f445b26
# Write a function that receives a string as a parameter and returns a dictionary in which the keys are the characters in the character string and the values are the number of occurrences of that character in the given text. # Example: For string "Ana has apples." given as a parameter the function will return the dicti...
8,054
2fabb03f0f6b0b297245354782e650380509424b
y = 10 x = 'Тишь да гладь' print(f'Текст:{x}') print(f'Число:{y}') a1 = input('Введите первое число: ') a2 = input('Введите второе число: ') b1 = input('Введите первую строку: ') b2 = input('Введите вторую строку: ') print(f'Вы ввели числа: {a1}/{a2}') print(f'Вы ввели строки: {b1} / {b2}')
8,055
d67842c05af9241dbe7e038a9b2dc4223ee7ef4d
# You have an array arr of length n where arr[i] = (2 * i) + 1 for all valid values of i (i.e. 0 <= i < n). # In one operation, you can select two indices x and y where 0 <= x, y < n and subtract 1 from arr[x] and add 1 to arr[y] # (i.e. perform arr[x] -=1 and arr[y] += 1). The goal is to make all the elements of the...
8,056
a91d42764fa14111afca4551edd6c889903ed9bd
# Generated by Django 2.1.3 on 2019-01-06 06:53 import django.db.models.deletion from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
8,057
2d72f063362aaefdc236e1240020c71bacaf51cf
num = 15850 base = 16 # Primera división residuo = num % base cociente = num // base bit1 = str(residuo) bit1 = bit1.replace("10","a") bit1 = bit1.replace("11","b") bit1 = bit1.replace("12","c") bit1 = bit1.replace("13","d") bit1 = bit1.replace("14","e") bit1 = bit1.replace("15","f") # Segunda división residuo = co...
8,058
30df17d636c33d2824aad7d7ef6aae7db83615ec
# Copyright 2021 Google LLC. 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 applicable law or a...
8,059
aace7bc6684f4a9cec2f8fe270b5123a375780af
from string import maketrans def to_rna(str): strtrans = maketrans('ACGT', 'UGCA') return str.translate(strtrans)
8,060
753e062940e0580d7d33c88c1165977142dcd202
#!/usr/bin/env python3 def main(): A1, A2, A3 = map(int, input().split()) A=A1+A2+A3 if A >=22: ans='bust' else: ans='win' print(ans) if __name__ == "__main__": main()
8,061
23a7aa6b9a98bfd4fd43fea1ecfa26cb44969804
from qcg.appscheduler.errors import * class Node: def __init__(self, name=None, totalCores=0, used=0): self.__name = name self.__totalCores = totalCores self.__usedCores = used self.resources = None def __getName(self): return self.__name def __getTotalCores(self)...
8,062
bca0baaffefed6917939614defadf9960ffa4727
class Solution: # @param num, a list of integer # @return an integer def rob(self, num): n = len(num) if n == 0: return 0 if(n == 1): return num[0] f = [0] * n f[0] = num[0] f[1] = max(num[0],num[1]) for i in xrange(2,n): ...
8,063
a21c132ba9f24ff2c695bf66cae074705025d6b1
#-*- coding: utf-8 -*- # Copyright (C) 2011 by # Jordi Torrents <jtorrents@milnou.net> # Aric Hagberg <hagberg@lanl.gov> # All rights reserved. # BSD license. import itertools import networkx as nx __author__ = """\n""".join(['Jordi Torrents <jtorrents@milnou.net>', 'Aric Hagb...
8,064
63cce356b792949b90b215e0a5826f7b33d2d375
# System import import os # Docutils import from docutils import nodes from docutils.parsers.rst.directives.admonitions import BaseAdmonition from docutils.statemachine import ViewList # Add node class link_to_block(nodes.Admonition, nodes.Element): """ Node for inserting a link to button.""" pass # Add di...
8,065
638842cda666100ce197437cb354f66de77eb328
from distutils.core import setup setup( name="zuknuft", version="0.1", author="riotbib", author_email="riotbib@github", scripts=["zukunft.py"], install_requires=[ 'bottle', ], )
8,066
0bbc8aa77436193ab47c0fe8cf0d7c6dffcfe097
from marko.parser import Parser # type: ignore from marko.block import Heading, Paragraph, CodeBlock, List # type: ignore from marko.inline import CodeSpan # type: ignore from langcreator.common import Generators, InputOutputGenerator, tag_regex, get_tags, builtin_generators import collections import re def parse(...
8,067
a33abd253288140f8051aced1d0ed1e41b2fc786
from flask import Blueprint application_vue_demo = Blueprint('application_vue_demo', __name__) from. import views
8,068
3c6ef57501e01da79f894b36726a93a3a5e0a8f6
# RUSH HOUR m = int(input('Enter number of males:')) f = int(input('Enter number of females:')) if m%20 == 0: m2 = m//20 c = 20 else: m2 = m//20+1 c = m%20 f2 = f - 10*m2 if f2 <= 0 or f2-(20-c) <=0: print('Number of trains needed: '+str(m2)) else: print('Number of trains ...
8,069
c716f43dbe62f662c60653f09be946a27c3fff66
import Adafruit_BBIO.GPIO as GPIO from pydrs import SerialDRS import time import sys sys.dont_write_bytecode = True class SyncRecv: def __init__(self): self._comport = '/dev/ttyUSB0' self._baudrate = '115200' self._epwm_sync_pin = 'GPIO2_23' # Input in BBB perspective ...
8,070
3e8fa71c4e23348c6f00fe97729b5717bb6245a1
''' held-karp.py Implementation of the Bellman-Held-Karp Algorithm to exactly solve TSPs, requiring no external dependencies. Includes a purely recursive implementation, as well as both top-down and bottom-up dynamic programming approaches. ''' import sys def held_karp_recursive(distance_matrix): ''' Soluti...
8,071
9d4559a363c4fd6f9a22dc493a7aaa0a22386c21
import pandas as pd from pymongo import MongoClient import numpy as np mongo_client = MongoClient('localhost', 27018) mongo_db = mongo_client['ProjetoIN242'] mongo_collection = mongo_db['contadorpessoas'] query = mongo_collection.find({}) df = pd.DataFrame.from_records(query) df_filtro = df[['Entrada','Dia', 'Quant...
8,072
5cd573f2b7f91a8b20e96deb1004c0ef7fc62398
from funct import read_excel import requests import unittest import HTMLTestReportCN class v2exapi(unittest.TestCase): def test_node_api(self): url = "https://www.v2ex.com/api/nodes/show.json" #querystring = {"name":"php"} a=read_excel("xx.xlsx",0,0) for node_name in a: #fo...
8,073
e14c7eb11c06d6de5c2f9f8adfb8b742fcb432e1
#!/usr/bin/env python """ haxor Unofficial Python wrapper for official Hacker News API @author avinash sajjanshetty @email hi@avi.im """ from __future__ import absolute_import from __future__ import unicode_literals import datetime import json import sys import requests from .settings import supported_api_versions...
8,074
02230b44568808757fe45fd18d28881d9bc3e410
#!/usr/bin/env python # encoding: utf-8 import tweepy #https://github.com/tweepy/tweepy import csv import scraperwiki import json #Twitter API credentials - these need adding consumer_key = "" consumer_secret = "" access_key = "" access_secret = "" def get_all_tweets(screen_name): #Twitter only allows access to a ...
8,075
c81889cf4d87933b562aa4618bc5185a8d213107
#! /usr/bin/env python import os import re from codecs import open from setuptools import find_packages, setup here = os.path.abspath(os.path.dirname(__file__)) def get_changelog(): with open(os.path.join(here, 'CHANGELOG'), encoding='utf-8') as f: text = f.read() header_matches = list(re.finditer...
8,076
e4ff6d689a7da5b16786fd59d6a4707b9b6e3e7d
import os error_msg = '''The default transformer cannot handle slashes (subdirectories); try another transformer in vlermv.transformers.''' def to_path(key): if isinstance(key, tuple): if len(key) == 1: key = key[0] else: raise ValueError(error_msg) if '/' in key or '\...
8,077
be63e8e6e98c9afed66cae033a7f41f1be1561a8
#!/usr/bin/python3 import tkinter from PIL import Image, ImageTk import requests from io import BytesIO from threading import Timer rootWindow = tkinter.Tk() # the following makes the program full-screen RWidth = rootWindow.winfo_screenwidth() RHeight = rootWindow.winfo_screenheight() # rootWindow.overrideredirect(...
8,078
0ef03ed455938bd2001581986c38104bfac395ce
# leetcode 836 # determine if two rectangles overlap # input is two lists [x1,y1,x2,y2] coordinates # where x1,y1 are coordinates of bottom left corner # and x2,y2 are coordinates of top right corner def overlap_rect(rec1, rec2): """Determine if rectangles overlap.""" # true if rec2 is left of rec1 a = rec...
8,079
bf9e83591f737caec3060b72d86d56faec9bb23b
# 5. Усовершенствовать программу «Банковский депозит». Третьим аргументом в функцию должна # передаваться фиксированная ежемесячная сумма пополнения вклада. Необходимо в главной # функции реализовать вложенную функцию подсчета процентов для пополняемой суммы. # Примем, что клиент вносит средства в последний день каж...
8,080
59b2d0ff3296c9d9a76b8b69a784d5a0c46128be
''' XFA/XDP DOM in Javascript This file is part of the phoneyPDF Framework This module provides methods for transforming both PDF objects and XML (xfa/xdp) into a single structure of linked objects in javascript. The idea is that any *DOM interation will play out in javascript land, where the DOMs are created and main...
8,081
9d772d5500593583907b65bc2c81490e61375e8b
class TimeInterval(object): def __init__(self, start_time, end_time): self.start_time = start_time self.end_time = end_time
8,082
9bb15842b39c7fd3e6f6c0048a51c2b2112ddb94
from django.db import models from django.contrib.auth.models import User from django.utils.encoding import smart_unicode from django.core.validators import MinValueValidator from django.utils import timezone from concurrency.fields import IntegerVersionField class ProductCategory(models.Model): name = models.Char...
8,083
592f29f08637e511bd7d49a3b58f69b700721d89
def alt(h, dt): t=0 while True: t=t+1 a=(-6)*(t**4)+ h*(t**3)+2*(t**2)+t if a<=0: print('The balloon first touches ground at hour:') print(t) break elif t==dt: print('The balloon does not touch ground in the given tim...
8,084
312a95c9514722157653365104d8cd0ada760ce8
"""URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.10/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based ...
8,085
fdae984f7cf5e1c20dee197d3f2518a0c7c38bdc
from time import sleep from uuid import uuid1 from pprint import pprint from shutil import copy2 from multiprocessing import Process, Queue, Pool, Manager from ad_grabber_classes import * from adregex import * from pygraph.classes.digraph import digraph import os import json import jsonpickle import subprocess import ...
8,086
cf5062c999c6c29f103428c247d8d1a4550f9d75
file = open('thegazelle.wordpress.2016-06-22.xml', 'r') text = file.read() authors = [] start = text.find("<wp:author_display_name>") length = len("<wp:author_display_name>") end = text.find("</wp:author_display_name") authors.append(text[start+length+len("<![CDATA["):end-len("]]>")]) while text.find("<wp:author_displa...
8,087
7d173b0571c20dc8fcae884451e8f69ba3a05763
from __future__ import print_function import os import re import xml.etree.ElementTree as ET def read_vivado_report(hls_dir, full_report=False): if not os.path.exists(hls_dir): print('Path {} does not exist. Exiting.'.format(hls_dir)) return prj_dir = None top_func_name = None if os.p...
8,088
c7c405535b2ca656d4d5f18013e3e2fdef70efea
""" 1. Если в строке больше символов в нижнем регистре - вывести все в нижнем, если больше в верхнем - вывести все в верхнем, если поровну - вывести в противоположных регистрах. 2. Если в строке каждое слово начинается с заглавной буквы, тогда добавить в начало строки 'done. '. И...
8,089
d726e468a9df26f1bcb8a016812b87fad7b41aa8
from brie.config import ldap_config from brie.model.ldap import * from brie.lib.log_helper import BrieLogging import datetime import smtplib class Residences: @staticmethod def get_dn_by_name(user_session, name): result = user_session.ldap_bind.search_first(ldap_config.liste_residence_dn, "(cn=" +...
8,090
3752b68e151379c57e1494715a45172607f4aead
# file = open('suifeng.txt') # # text = file.read() # # print(text) # # file.close() # with open('suifeng.txt') as f: # print(f.read()) newList=[] for i in range(11): newList.append(i*2) print(newList) newList2=[i*2 for i in range(11)] print(newList2) list = ["小米","王银龙","王思"] emptyList=[] for name in list...
8,091
ca551d8e55ebb15a03077af5695782c6d72ff2fd
"""Command line interface to the OSF These functions implement the functionality of the command-line interface. """ from __future__ import print_function from functools import wraps import getpass import os import sys from six.moves import configparser from six.moves import input from tqdm import tqdm from .api im...
8,092
3f20438b0dd2ae8de470e5456dbb764eabf69645
import types import qt cfg = qt.cfgman cfg.remove_cfg('protocols') cfg.remove_cfg('samples') cfg.remove_cfg('setup') cfg.add_cfg('protocols') cfg.add_cfg('samples') cfg.add_cfg('setup') cfg['samples']['current'] = 'hans-sil13' cfg['protocols']['current'] = 'hans-sil13-default' print 'updating msmt params for {}'.for...
8,093
e239c2089fc6d4ab646c490b6e3de8953cec5634
from typing import Sequence, Union, Tuple import kdtree from colour import Color AnsiCodeType = Union[str, int, Tuple[int, int, int]] class ColorPoint(object): def __init__(self, source: Color, target: Color, ansi: AnsiCodeType) -> None: """ Map source color to target color, st...
8,094
e57109f1c5c2e1468ef1cf9f10fba743633ca150
from discord.ext import commands, tasks from discord.utils import get import discord import re import json import time import random import asyncio import os import datetime from live_ticker_scrape import wrangle_data from tokens import dev, dev1, es, nas, dow, us10y, dollar, vix, btc, eth, silver , link es_bot = d...
8,095
4ce1e802831f09e503d18fd287cb35400986e3c8
#! /usr/bin/env python # -*- coding: utf-8 -*- # auther : xiaojinsong(61627515@qq.com) parts = ['Is', 'Chicago', 'Not', 'Chicago?'] data = ['ACME', 50, 91.1] print(' '.join(parts)) def generate_str(): print(','.join(str(d) for d in data)) def sample(): yield 'Is' yield 'Chicago' yield 'Not' yi...
8,096
8439972b4458ba66d98f6a80a82a35576df472a4
from channels.routing import route from .consumers import message_consumer channel_routing = [ route("slack.rtm.message", message_consumer) ]
8,097
11e9e4dd5c9c6158fed40080d4cc221f28a0eba0
#!/usr/bin/python import sys import os class ParseError(Exception): pass def remove_inline_comments(text): ret = [] in_comment_block = False p = 0 while True: if (op := text.find('/*', p)) > 0: in_comment_block = True if op != p: ret.append(text[p...
8,098
5f4abc7e9397034737ee214b0d0aae39ebf1548b
#!/usr/bin/env python # pylama:ignore=E221,E251 from setuptools import find_packages, setup setup( name = 'coding_exercises', version = '1.0', description = 'Coding Exercises in Python', author = 'Gustavo Gama', author_email = 'gustavo.gama@gmail.com', url = 'https...
8,099
3f92bf194058c97a40cd5728cfc7c9d1be6b2548
import os import sys import time from collections import deque import pickle import random import string from tensorflow.python.framework.errors import InvalidArgumentError from baselines.ddpg.ddpg import DDPG import baselines.common.tf_util as U from baselines.ddpg import prosthetics_env from baselines import logger...