index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
300 | 5ddfeb49c16a7452c99126f1a837f3c0bed0ec10 | import requests
from urllib.parse import urlparse
from bs4 import BeautifulSoup
import re
import datetime
import random
pages = set()
# Retrieve a list of all Internal links foound on a page.
def getInternalLinks(bs, includeUrl):
includeUrl = f'{urlparse(includeUrl).scheme}://{urlparse(includeUrl).netloc}'
in... |
301 | 1e1f918ba24f5a5f13b9b01289ebfda65bae572d | def warshall_floyd(N):
INF = 10**20
path = [[INF for _ in range(N+ 1)] for _ in range(N+1)]
graph = get_graph()
for i in range(N+1):
path[i][i] = 0
for g in graph:
x = g[0]
y = g[1]
l = g[2]
path[x][y] = path[y][x] = l
for start in range(N+1):
for ... |
302 | 04538cc5c9c68582cc9aa2959faae2d7547ab2ee | try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
import data_helpers
def write_to_file(file,line):
file.write(line+"\n")
def cat_map():
catmap={}
id=1
f=open("cat")
cat=set([s.strip() for s in list(f.readlines())])
for i in cat:
catmap[i]=id
id=id+1
return c... |
303 | 631323e79f4fb32611d7094af92cff8f923fa996 | #!/bin/python3
def word_ladder(start_word, end_word, dictionary_file='words5.dict'):
'''
Returns a list satisfying the following properties:
1. the first element is `start_word`
2. the last element is `end_word`
3. elements at index i and i+1 are `_adjacent`
4. all elements are entries in the... |
304 | 0a528fb7fe4a318af8bd3111e8d67f6af6bd7416 | from typing import Tuple
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def lcaDeepestLeaves(self, root: TreeNode) -> TreeNode:
_, lca = self.get_lca(root, 0)
return lca
def get_lca(self, node: TreeNode, dep... |
305 | 371762a6e3f8b8ed14742a70a709da224ae6712b | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random
"""
检查图数据和结构或者链表数据结构中是否存在环
https://www.youtube.com/watch?v=YKE4Vd1ysPI
"""
def get_all_edge(graph):
result = []
for k, v in graph.items():
for i in v:
if sorted((k, i)) not in result:
result.append(sorted((k, ... |
306 | 7f7ebc6d3d69fbb19071c63a9ab235ad01f1d414 | import sys
sys.path.append("..")
import helpers
helpers.mask_busy_gpus(wait=False)
import nltk
import numpy as np
nltk.download('brown')
nltk.download('universal_tagset')
data = nltk.corpus.brown.tagged_sents(tagset='universal')
all_tags = ['#EOS#','#UNK#','ADV', 'NOUN', 'ADP', 'PRON', 'DET', '.', 'PRT', 'VERB', 'X... |
307 | 8698aedc5c8671f46c73898a7188440254b79bbf | from abc import abstractmethod
class Environment:
@abstractmethod
def __init__(self, agent):
pass
@abstractmethod
def execute_step(self, n=1):
pass
@abstractmethod
def execute_all(self):
pass
@abstractmethod
def set_delay(self, delay):
pass
|
308 | 1be510e6715d21e814c48fe05496704e9a65d554 | from end import Client
c = Client()
|
309 | 6b727cdfc684db4ba919cd5390fe45de43a806fe | import glob
import xarray as xr
from model_diagnostics import *
data_root = '../data/synthetic/standard/'
var_list = ['hs', 'dp', 'spr', 'fp', 'dir', 't0m1']
eke = 0.01
##########################
output = []
diagnostic_functions = [basic_stats]
for var in var_list:
grid_files = glob.glob(data_root+'gridded/*%s*%s... |
310 | c66f4ee5719f764c8c713c23815302c00b6fb9af | import os
from cs50 import SQL
from flask import Flask, flash, redirect, render_template, request, session
from flask_session import Session
from tempfile import mkdtemp
from werkzeug.exceptions import default_exceptions, HTTPException, InternalServerError
from werkzeug.security import check_password_hash, generate_pa... |
311 | 097a87f7f1346e5db1599e59680232912348aef7 | # -*- coding:utf-8 -*-
from odoo import api, models, fields, _
class hrsalaryRule(models.Model):
_inherit = "hr.salary.rule"
is_tax_fdfp = fields.Boolean("Est un impôt FDFP") |
312 | a126b1775ffe1ba1aebc288ce17fac8ada0b0756 | import cv2
import numpy as np
import pandas as pd
import tkinter as tk
import random
from tkinter import *
from tkinter import ttk
from tkinter import messagebox
from tkinter import Scale,Tk
from tkinter.ttk import Notebook
refPt = []
PtBGR=[]
r=[]
g=[]
b=[]
refPt = []
Serial=[]
PtBGR=[]
r1=[]
r2=[]
r3=[]
r4=[]
rate=[... |
313 | dca36de5556b120b8b93eac0ad7b971ad735d907 | import numpy as np
def GradientDescent(f, gradf, x0, epsilon, num_iter, line_search,
disp=False, callback=None, **kwargs):
x = x0.copy()
iteration = 0
opt_arg = {"f": f, "grad_f": gradf}
for key in kwargs:
opt_arg[key] = kwargs[key]
while True:
gradient = -gradf(x)
alpha = line_search(x... |
314 | 4711adcc7c95993ec13b9d06fa674aa064f79bfd | import torch
import torch.nn as nn
import torch.nn.functional as F
class Net(torch.nn.Module):
def __init__(self, layer_sizes=[256, 128, 2], dropout_prob=None, device=None):
super(Net, self).__init__()
self.device = device
if dropout_prob is not None and dropout_prob > 0.5:
pr... |
315 | 3479276d4769518aa60dcd4e1bb41a8a1a7d6517 | import os
from multiprocessing import Pool
import glob
import click
import logging
import pandas as pd
from src.resampling.resampling import Resampler
# Default paths
path_in = 'data/hecktor_nii/'
path_out = 'data/resampled/'
path_bb = 'data/bbox.csv'
@click.command()
@click.argument('input_folder', type=click.Pat... |
316 | d5beff74e3746c77cbaf6b8233b822ed1a86701e | # Generated by Django 2.2.2 on 2021-01-23 04:11
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('task', '0022_taskrecycle_create_date'),
]
operations = [
migrations.RemoveField(
model_name='ansibleextravars',
name='playbo... |
317 | 77763f501c6776969d2594f987e5d7ab7d4377fb | import time
from PyQt5.QtCore import (
QThread,
)
from common import attach_common
from database_downloader import DatabaseDownload
from ai_list_memorize import MemorizeList
from ai_list_morpheme import MorphemeList
from ai_list_ngram import NgramList
from ai_list_none import NoneList
from ai_bot_memorize import Me... |
318 | d6a760774b45454c959c2932d7b28deee7f81872 | # SPDX-License-Identifier: Apache-2.0
# Licensed to the Ed-Fi Alliance under one or more agreements.
# The Ed-Fi Alliance licenses this file to you under the Apache License, Version 2.0.
# See the LICENSE and NOTICES files in the project root for more information.
import json
from typing import Dict
from pandas import... |
319 | bd3b1263d7d657fe2edd3c7198f63821a3d1d1e5 | import random
from . import WaiterInterface
class RandomIPv4Waiter(WaiterInterface):
"""
HostPortWaiter which generates random ipv4 adresses
"""
def __init__(self, options):
self.ports = options['ports']
self.limit_generate = options.get('limit_generate', -1)
def generator(self):
... |
320 | 5830a6001d7db50002c44aede6fb10938fa01dd1 | import nltk
class Text(object):
def __init__(self, text):
self.text = text
self.words = nltk.word_tokenize(text)
self.sents = nltk.sent_tokenize(text)
class Passage(Text):
def __init__(self, title, story, questions):
Text.__init__(self,story)
self.title = title
... |
321 | d2c31d9c3cc66b43966cfd852582539d4e4bea17 | from selenium import webdriver
import time
import datetime
import os
import openpyxl as vb
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains
def deconnexion(Chrome):
"""登陆"""
"""初始化"""
global web, actions
web = webdriver.Chrome(Ch... |
322 | 213ab22a269abc8180524462a8966e5d929ef7d1 | import os
import json
import codecs
import markdown
from flask import current_app
def get_json_file(filename, lang='en'):
"""
Get the contents of a JSON file.
"""
filepath = os.path.join(current_app.config['APP_PATH'], 'data', filename)
with open(filepath, 'r') as f:
return json.loads(... |
323 | 398263b65fd98003f27020e46ae38e913dc5dd45 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Brice Chou'
import os
import lib
import sys
import time
import getopt
import training
try:
import cv2
import h5py
except Exception as e:
error_info = 'Please install h5py/cv2 tools first. Error: {}.\n'.format(e)
print('\033[0;31m%s\033[0m' ... |
324 | 606e40dd073c3efc95ef01a08466fd536a28f140 | from slistener import SListener
from slistener import track
import datetime
import time, tweepy, sys
import json
import re
#def tweet_collector():
consumer_key='qpUR91PwjvChszV0VFgrc4Hje'
consumer_secret='q9mPUZE2OsFbaqKUF32ZsY1ry4anZ1k8pNSne56wc3HInmERFu'
access_token='2845943577-R0g6YRlrdEqSFb2mKy5HXuByQPdpq4TLGrPkm... |
325 | 86ca94820c05b3f63f4a733b6d1fa7eb9dea6a5d | # generated from catkin/cmake/template/order_packages.context.py.in
source_root_dir = "/home/songsong/image_transport_ws/src"
whitelisted_packages = "".split(';') if "" != "" else []
blacklisted_packages = "".split(';') if "" != "" else []
underlay_workspaces = "/home/songsong/image_transport_ws/devel;/home/songsong/pi... |
326 | 095d7abfc8297e0bf741a4ebb351a7776055623f | ''' The previous code does not correcly compute the stiffening coefficients
This program uses the clustering data to re-compute the stiffening coefficients '''
import glob
import sys
import time
#-----------------------------------------------------------------------------------#
#-----------------------------------... |
327 | 1f27b697985c7417e6d8d978703175a415c6c57d | import math
r = float(input())
p = int(input())
obim = 2 * r * math.pi
ukupanPut = p * obim
# centimetre pretvaramo u metre
ukupanPut = ukupanPut * 0.01
print("%.2f" % ukupanPut)
|
328 | 71a9c9b8f47dcfbecc154c44d5a72ddbd852145a |
def randomizer(n, garrafa_vidro, lata_metal, copo_plastico, bola_papel, maça_organico):
lixos = [garrafa_vidro, lata_metal, copo_plastico, bola_papel, maça_organico]
return lixos[n]
|
329 | 02e711dfc122007c74949cd9f86e2aeb9d334871 | import numpy as np
class Adaline:
def __init__(self, eta = 0.0001, n_iter = 2000):
self.eta = eta
self.n_iter = n_iter
self.error = []
def fit(self, X, Y):
X = np.hstack((np.ones((X.shape[0],1)), X))
self.w = np.random.uniform(-1, 1, (X.shape[1], 1))
for n in ... |
330 | 6bf1d410a33e3b2535e39e4f8c5c7f8278b3de67 | from PIL import Image
from src import urbandictionary_api
from src.card.cardDrawer import CardDrawer
from src.card.cardModel import CardModel
from src.repository import Repository
from src.urbandictionary_api import get_random_word
def save_card(word, image_path, filepath='data/cards/', filename=None):
'''Функци... |
331 | a096e811e50e25e47a9b76b1f813c51f4307bbfe | import django_filters
from .models import Drinks, Brand
class DrinkFilter(django_filters.FilterSet):
BRAND_CHOICES = tuple(
(brand.name, brand.name) for brand in Brand.objects.all())
name = django_filters.CharFilter(lookup_expr='icontains')
price_lt = django_filters.NumberFilter(field_name='price'... |
332 | 3ea42e7ad5301314a39bf522280c084342cd18c5 | from flask import render_template, request, Response
from flask.views import MethodView, View
from flask.views import View
from repo import ClassifierRepo
from services import PredictDigitService
from settings import CLASSIFIER_STORAGE
class IndexView(View):
def dispatch_request(self):
return render_temp... |
333 | 0c97569c77fb3598d83eba607960328bb2134dd2 | from __future__ import print_function, division
import os
from os.path import exists, join, basename, dirname
from os import makedirs
import numpy as np
import datetime
import time
import argparse
import torch
import torch.nn as nn
import torch.optim as optim
from lib.dataloader import DataLoader
from lib.im_pair_dat... |
334 | a65dfca1773c1e4101ebfb953e0f617a2c345695 | def merge(self, intervals):
intervals.sort()
arr = []
for i in intervals:
if len(arr)==0 or arr[-1][1] < i[0]:
arr.append(i)
else:
arr[-1][1] = max(arr[-1][1], i[1])
return arr
|
335 | 49005500b299ca276f663fe8431bb955e5585bbd | import Net
import mnist_parser
import numpy as np
#To use this model it is required to download the MNIST database
#The donwloaded base is then needet parse to numpy using mnist_parser.parse_to_npy method
#The files genetared using mnist_parser.parse_to_npy are then loaded using np.load
in_values = np.load("MNIST/mnist... |
336 | 219929d52b5f1a0690590e83b41d2b4f0b2b3a51 | list = [3,1,2,5,4,7,6]
def sort(list):
for i in range(len(list)-1):
if list[i] > list[i+1]:
a = list[i]
list[i] = list[i+1]
list[i+1] = a
print(list)
sort(list) |
337 | e884ce5878de75afe93085e2310b4b8d5953963a | '''
Created on 13 Dec 2016
@author: hpcosta
'''
# https://www.hackerrank.com/challenges/backreferences-to-failed-groups
regex = r"^\d{2}(-?)\d{2}\1\d{2}\1\d{2}$" # Do not delete 'r'.
import re
print(str(bool(re.search(regex, raw_input()))).lower())
# Task
#
# You have a test string S.
# Your task is to write... |
338 | 9951588f581c5045154a77535b36d230d586d8a5 | from OpenSSL import SSL, crypto
from twisted.internet import ssl, reactor
from twisted.internet.protocol import Factory, Protocol
import os
from time import time
class Echo(Protocol):
def dataReceived(self, data):
print "Data received: " + data
# define cases
options = {
"gen... |
339 | 302accfd5001a27c7bbe6081856d43dbec704168 | import asyncio
import logging
import random
from aiogram.dispatcher import FSMContext
from aiogram.types import ContentTypes, Message, CallbackQuery
from aiogram.utils.exceptions import BotBlocked
import keyboards
from data.config import ADMINS, ADMIN_CHAT_ID
from keyboards.inline.activate_menu import active_menu_cal... |
340 | de925b8f6bd31bfdfd1f04628659847b0761899d | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
@author: Allen(Zifeng) An
@course:
@contact: anz8@mcmaster.ca
@file: 17. Letter Combinations of a Phone Number.py
@time: 2020/2/2 21:18
'''
from typing import List
class Solution:
def letterCombinations(self, digits: str) -> List[str]:
d={2:'abc',
... |
341 | 6531833a4fe57c15c0668cee9015c7d43491427a | /home/openerp/production/extra-addons/productivity_analysis/report/productivity_analysis.py |
342 | b3d9013ab6facb8dd9361e2a0715a8ed0cdfeaba | from setuptools import setup
import imp
def get_version():
ver_file = None
try:
ver_file, pathname, description = imp.find_module('__version__', ['cmakelint'])
vermod = imp.load_module('__version__', ver_file, pathname, description)
version = vermod.VERSION
return version
... |
343 | 359db73de2c2bb5967723dfb78f98fb84b337b9d | from math import degrees, sqrt, sin, cos, atan, radians
from pygame import Surface, draw
from pygame.sprite import Sprite
from constants import ARROW_MAX_SPEED, FLOOR_Y
from game_types import Radian, Degree
class Arrow(Sprite):
def __init__(self, color, screen, character, click_position):
Sprite.__in... |
344 | 97cc29e0d54e5d5e05dff16c92ecc4046363185f | from django.conf import settings
from django.conf.urls.static import static
from django.contrib import admin
from django.urls import path, include
from home import views
from order import views as OV
urlpatterns = [
path('user', include('user.urls')),
path('order', include('order.urls')),
path('shopcart/',... |
345 | 35b24ffa14f8b3c2040d5becc8a35721e86d8b3d | total = totmil = cont = menor = 0
barato = ' '
print('-'*40)
print('LOJA SUPER BARATÃO')
print('-'*40)
while True:
produto = str(input('Nome do Produto: '))
preco = float(input('Preço: '))
cont += 1
total += preco
if preco > 1000:
totmil +=1
if cont == 1 or preco < menor:
barato ... |
346 | 709271b98fc2b40c763522c54488be36968f02d8 | from base import *
try:
from .prod_local import *
except:
pass
# we currently don't have an interface that allows an administrator
# to create a repository for another user. Until we have added this
# capability, allow users to create repos.
ELEMENTARY_ALLOW_REPO_CREATION = True
|
347 | edcccc673994a8de281a683b747de52d2115f89e | from configparser import ConfigParser
from ef.config.components import *
from ef.config.efconf import EfConf
from ef.config.section import ConfigSection
comp_list = [BoundaryConditions, InnerRegion, OutputFile, ParticleInteractionModel,
ParticleSource, SpatialMesh, TimeGrid, ExternalFieldUniform]
def t... |
348 | 38e167630519b73bffea4ff527bc7b7272a49f1a | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2019-01-13 15:01
import pickle
import numpy as np
from bert_serving.client import BertClient
from pyhanlp import *
CharTable = JClass('com.hankcs.hanlp.dictionary.other.CharTable')
# bc = BertClient(ip='192.168.1.88') # ip address of the server
bc = BertClient(ip='127... |
349 | 816b1a932208a4525230dd886adf8c67dec3af3e | # content of conftest.py
# adapted from http://pytest.org/latest/example/special.html
import pytest
import requests
def tear_down():
''' conftest.py tear_down - the last to go.... '''
print("\nTEARDOWN after all tests")
@pytest.fixture(scope="session", autouse=True)
def set_up(request):
''' conftest... |
350 | 9096ed4b68d2bef92df7db98589e744ddf3efad0 | import matplotlib.pyplot as plt
from shapely.geometry import MultiLineString, Polygon
mls = MultiLineString([[(0, 1), (5, 1)], [(1, 2), (1, 0)]])
p = Polygon([(0.5, 0.5), (0.5, 1.5), (2, 1.5), (2, 0.5)])
results = mls.intersection(p)
plt.subplot(1, 2, 1)
for ls in mls:
plt.plot(*ls.xy)
plt.plot(*p.boundary.xy, "-... |
351 | c99f1333c5ca3221e9932d9a9ba1d95a77924f0d | import sys
import math
def get_max_sum(arr):
max_sum = -math.inf
for i in range(1, 5):
for j in range(1, 5):
temp = arr[i][j]+arr[i-1][j-1]+arr[i-1][j]+arr[i-1][j+1]+arr[i+1][j+1]+arr[i+1][j]+arr[i+1][j-1]
max_sum = max(max_sum, temp)
return max_sum
def main():
sys... |
352 | 78c9f92349ba834bc64dc84f884638c4316a9ea4 | INPUT_MINBIAS = '/build/RAWReference/MinBias_RAW_320_STARTUP.root'
INPUT_TTBAR = '/build/RAWReference/TTbar_RAW_320_STARTUP.root'
puSTARTUP_TTBAR = '/build/RAWReference/TTbar_Tauola_PileUp_RAW_320_STARTUP.root'
relval = {
'step1': { 'step': 'GEN-HLT',
'timesize': (100, ['MinBias','TTbar']),
'igprof': (50... |
353 | c6b261a09b2982e17704f847586bbf38d27cb786 | from ._sinAction import *
from ._sinActionFeedback import *
from ._sinActionGoal import *
from ._sinActionResult import *
from ._sinFeedback import *
from ._sinGoal import *
from ._sinResult import *
|
354 | f4306f80330850415b74d729384f360489644e39 | import unittest
import numpy
import pandas as pd
import fixtures.examples_validate as examples
from cellxgene_schema.validate import Validator
from cellxgene_schema.write_labels import AnnDataLabelAppender
# Tests for schema compliance of an AnnData object
class TestValidAnndata(unittest.TestCase):
"""
T... |
355 | ad3a7221883a847fc9d26097c3801973cbbda38e |
from django.urls import path,include
from Income import views
urlpatterns = [
path('IncomeHome/',views.IncomeHome,name='IncomeHome'),
path('IncomeCreate/',views.IncomeCreate.as_view(),name='IncomeCreate'),
path('IncomeUpdate/<int:pk>',views.IncomeUpdate.as_view(),name='IncomeUpdate'),
path('IncomeDel... |
356 | 9e7dee9c0fd4cd290f4710649ffc4a94fedf0358 | import os
pil = 'y'
while(pil=='y'):
os.system("cls")
print("===============================")
print("== KALKULATOR SEDERHANA ==")
print("===============================")
print("MENU-UTAMA : ")
print("1 Penjumlahan")
print("2 Pengurangan")
print("3 Perkalian")
print("4 Pembagia... |
357 | 180f7f0ade9770c6669680bd13ac8f2fd55cc8c7 | def raizCubica(numero):
r = pow(numero,(1/3))
return r
numeros = []
raices = []
for x in range(5):
numeros.insert(x, float(input("Ingrese Numero: ")))
raices.insert(x, round(raizCubica(numeros[x]),3))
print("Numeros: ", numeros)
print("Raices: ", raices) |
358 | 97ebdeada3d797a971b5c3851b75f9754595f67c | """
Python package setup file.
"""
from setuptools import setup
setup(
name="TF_Speech",
version="0.2.0",
extras_require={'tensorflow': ['tensorflow'],
'tensorflow with gpu': ['tensorflow-gpu']},
)
|
359 | 9f34bf3a0bb24db428b7af1a354aec1d3a72df98 | from random import randrange
from django.core.exceptions import ValidationError
from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from .models import EmailValidation
from ..emails.models import Ema... |
360 | 2ca91c410b8c8d6306d5ed918783a4d77a091ba8 | from typing import List
from re import match
from utility import ButtonGroup
import rumps
class RepeatWorkBreak(rumps.App):
def __init__(self):
rumps.debug_mode(True)
self.config = {
"app_title": "Repeat Work and Break",
"start": "Start",
"pause": "Pause Timer"... |
361 | 8bc40ed4fe1091ecdb40cd55ff9cf53010078823 | import requests
import json
data = json.load(open("dummy_data/data.json"))
for one in data:
print(one)
r = requests.post("http://localhost:8080/sumari", json=one)
print(r.text)
|
362 | 4e9a968842c2b3eca79690f0b56c8e176b203138 | print((9*int(input())/5)+32) |
363 | 7a1bd2b4734527a414c6173ea8edb150221f8042 | import numpy as np
import pandas as pd
from scipy.optimize import minimize
from datetime import datetime
import time
from functions import weather_scraper
def getData():
# # run weather_scraper.py to fetch new weather data
# weather_scraper.getData()
## Read in csv file "weather_data.csv"
weather_data... |
364 | 1bdb19373960e4f63d80d6ab73ec3c0939e40b7f | import contextlib
import dask
import dask.array as da
import packaging.version
import pandas
import six
import sklearn
SK_VERSION = packaging.version.parse(sklearn.__version__)
DASK_VERSION = packaging.version.parse(dask.__version__)
PANDAS_VERSION = packaging.version.parse(pandas.__version__)
@contextlib.contextma... |
365 | a4f932a8566afe0265dc1057d0f6534a608697f7 | """
LeetCode Problem: 242. Valid Anagram
Link: https://leetcode.com/problems/valid-anagram/
Written by: Mostofa Adib Shakib
Language: Python
"""
class Solution(object):
def isAnagram(self, s, t):
"""
:type s: str
:type t: str
:rtype: bool
"""
length1 = len(s... |
366 | 6dd11f71e514a46462bf0b97ddac9ea474e86ad0 | import os, glob
import numpy as np
from ..algorithms.utils import get_file_manager
from ..algorithms.clustered_writes import *
from ..exp_utils import create_empty_dir
def test_get_entity_sizes():
# in C order
bytes_per_voxel = 1
R = (10,9,10)
cs = (5,3,2)
partition = (2,3,5)
bs, brs, bss = g... |
367 | c09c02a36a64e9522cfc8c0951bd6c98f404f09c | # Random number guessing game.
# 10 July 20
# CTI-110 P5HW1 - Random Number
# Thelma Majette
import random
randomNumber = random.randint (1,100)
# main function
def main():
# Create a variable to control the loop.
keep_going = 'y'
while keep_going == 'y':
# Ask user fo... |
368 | 798ddd4a6e4febb4664bf1c973877628d1a45c71 | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('accounts.views',
url(r'^$', 'home', name='home'),
url(r'^login/$', 'login', name='login'),
url(r'^logout/$', 'logout', n... |
369 | 3340277df91f1421dab8d204eddce65b4604432b | from django.shortcuts import render, redirect
from .models import Courses
from django.views.generic import CreateView, ListView, UpdateView, DeleteView
from .forms import CourceCreateForm
from django.urls import reverse_lazy
from django.urls import reverse
class CourceListView(ListView):
model = Courses
templa... |
370 | 66444047f9e5eea845c8ac2dbaaf16fc2914d6ec | if answ[1] == 'дата':
apisay(datetime.date.today(),toho,torep) |
371 | d2f6d7c779d3d6e61d9da7af01a2931fdabec828 | import random
choices = ['X', 'O']
try:
# Choice of X-O given to the player
player_sym = input("Choose 'X' or 'O' : ")
# raising an exception if the variable is not X or O
if player_sym!='X' and player_sym!='O':
raise Exception("Symbol not found")
except Exception as e:
print(e.args)
else:
... |
372 | b4c6075aabe833f6fe23471f608d928edd25ef63 | from .base import paw_test
class warning_test(paw_test):
def test_warning_badchars(self):
self.paw.cset_lookup(self.badchar)
self.assertEqual(1, self.paw.wcount)
|
373 | 24c9b562411a63f0d3f2ee509bb60dafe7fbecd1 | import os
from flask import Flask
# from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
# from flask_bcrypt import Bcrypt
from flask_wtf.csrf import CSRFProtect
app = Flask(__name__)
csrf = CSRFProtect(app)
# bcrypt = Bcrypt(app)
app.config['SECRET_KEY'] = 'v\xf9\xf7\x11\x13\x18\xfaMYp\xed_\x... |
374 | 14a357f3dfb3d59f1d8cfd566edeaf8b0e5bb56d | #!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
from sensor_msgs.msg import Joy
import serial
from sys import platform
if platform == "linux" or platform == "linux2":
ser = serial.Serial('/dev/ttyACM0')
elif platform == "darwin":
pass
elif platform == "win32":
# Windows...
ser = ... |
375 | 1ef9df43725196904ec6c0c881f4a1204174b176 |
import requests, shutil, os, glob
from zipfile import ZipFile
import pandas as pd
from xlrd import open_workbook
import csv
# zipfilename = 'desiya_hotels'
# try:
# # downloading zip file
# r = requests.get('http://staticstore.travelguru.com/testdump/1300001176/Excel.zip', auth=('testdump', 'testdump'), veri... |
376 | 7a59c8c883a9aaa723175783e01aa62e23503fde | #!/C:\Program Files (x86)\Python35-32
#importar librarias necesarias
from urllib.request import urlopen
from bs4 import BeautifulSoup
|
377 | 48d0bfdc607a4605ef82f5c7dc7fd6fc85c4255f |
'''
BMI=weight*0.45259227/(hei*0.0254)**
'''
wht=2
if wht==0:
print("wht is",wht)
else:
print("whtsdsb")
#今天也完成了100波比跳
wei=float(input("wei="))
hei=float(input("hei="))
bmi=(wei*0.45259227)/((hei*0.0254)**2)
print("BMI=",bmi)
if bmi<18.5:
print("too light")
elif bmi<25:
print("normal")
elif bmi<30:
... |
378 | 05e4bcc7323b908a7b45d766ada463ce172e25c4 | import graphene
import f1hub.drivers.schema
import f1hub.results.schema
import f1hub.constructors.schema
import f1hub.races.schema
import f1hub.status.schema
import f1hub.circuits.schema
import f1hub.constructorresults.schema
import f1hub.constructorstandings.schema
import f1hub.driverstandings.schema
import f1hub.lap... |
379 | 7530c2c85f83d1714840ba97c1ec702f063658c5 | from typing import List
import glm
import pxng
import OpenGL.GL as gl
class VertexArrayObject:
def __init__(self, primitive):
self._primitive = primitive
self._buffers: List[pxng.BufferObject] = []
self._indices = pxng.BufferObject(data_type=self.index_data_type,
... |
380 | 39fdb9c586c3cf92d493269ceac419e0058a763a | import pandas as pd
import numpy as np
import pyten.tenclass
import pyten.method
import pyten.tools
def scalable(file_name=None, function_name=None, recover=None, omega=None, r=2, tol=1e-8, maxiter=100, init='random',
printitn=0):
"""
Helios1 API returns CP_ALS, TUCKER_ALS, or NNCP decomposition or... |
381 | 1f7d770106ea8e7d1c0bb90e1fc576b7ee2f0220 | # Generated by Django 3.0.8 on 2020-08-28 17:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0003_auto_20200828_1836'),
]
operations = [
migrations.AddField(
model_name='order',
name='total',
... |
382 | 01847c9e601eae6775cd4324483740c30e344557 | from django.apps import AppConfig
class CfCoreConfig(AppConfig):
name = 'cf_core'
|
383 | ac2d4372f8913ea9ae1066833cca09985e521f99 | #!/usr/bin/env python
"""\
Simple g-code streaming script for grbl
"""
import serial
import time
import csv
import json
import RPi.GPIO as GPIO
from multiprocessing import Process, Queue
class motion():
def __init__(self):
# Open grbl serial port
#self.s = serial.Serial("/dev/ttyUSB0",baudrate=115... |
384 | ca11e9cf0bcfcbd714c45b5c95bd2c2044b65909 | """Woma objects for dealing with HTTP.
Request and Response inherit from webob's Request and Response objects, so see
http://docs.webob.org/en/latest/ for full documentation. The only things
documented here are the customizations.
"""
from webob import Request as BaseRequest
from webob import Response as BaseResponse... |
385 | 2c22f891f30825bcb97987c78a98988ad2a92210 | import os
import sys
import json
import logging
import argparse
from glob import glob
from pricewatcher.tools import ensure_mkdir
from pricewatcher.parser.f21 import ForeverParser
from pricewatcher.parser.jcrew import JcrewParser
from pricewatcher.utils.load_es import bulk_load_es
BRAND_PARSERS={
'forever21': Forever... |
386 | 3cd7abf9659fe1db0ef3aa58df8dd7fd959e10a6 | import os
import csv
import re
totWords = 0
wordLen = 0
totSentWithPunctuation = 0
sourceFile = os.path.join('Resources', 'paragraph_2.txt')
with open(sourceFile, 'r') as paragraph:
paragraph = paragraph.read().split("\n\n")
for sentence in paragraph:
# Remove punctuation from sentences
sentWithPunctua... |
387 | b95619f3f52ff3747e38ecc153123962d0122a4d | # noinspection PyStatementEffect
{
'name': 'ldap_user',
'summary': '',
'description': '域账号用户管理,登录及查询用户信息',
'author': '',
'website': '',
'source': {'git': 'https://github.com/LeiQiao/Parasite-Plugins.git', 'branch': 'master'},
'category': '',
'version': '0.1',
'api': {
'/use... |
388 | c3527363cfc29ab7d598fe232d784b05ec2ef069 | import models
import json
import reports.models
import common.ot_utils
def analyze_raw_reports(clean=True):
if clean:
delete_all_reports()
COUNT = 100
offset = 0
while True:
cont = analyze_raw_reports_subset(offset,COUNT)
offset += COUNT
if not cont:
return
... |
389 | 484d104a8481a707a187d0bcb30898c3459a88be | # -*- coding: utf-8 -*-
from django.conf.urls import patterns, include, url
from apps.virt.views import node, domain,device,cluster,home
urlpatterns = patterns('',
# Home
url(r'^$', home.HomeView.as_view(), name='home'),
# Cluster
url(r'^cluster/status/$', cluster.ClusterStatusView.as_view(), name... |
390 | 545794cf4f0b2ab63b6a90951a78f8bdaca3c9e6 |
from collections import defaultdict as dd
def grouping(w):
d = dd(list)
for k,v in ((len([y for y in x if y.isupper()]), x) for x in sorted(w,key=str.casefold)):
d[k].append(v)
return dict(sorted(d.items()))
|
391 | ab844143ceddf32982682f5092762af0c97db577 | from ..translators.translator import Translator
|
392 | 0762c5bec2d796bb7888e3de45e29fb20f88f491 |
from starter2 import *
from collections import defaultdict
import scipy
import colors
import hair_dryer
reload(hair_dryer)
import three_loopers_u500 as TL
import movie_frames
def GE_pearson(this_looper,core_list=None):
if core_list is None:
core_list = np.unique(this_looper.tr.core_ids)
name = th... |
393 | 7bbbd30ba1578c1165ccf5c2fff22609c16dfd64 | """
Cores no terminal
"""
a = 3
b = 5
print('Os valores são \033[32m{}\033[m e \033[31m{}\033[m !!!'.format(a, b))
# Dicionário de cores:
nome = 'Kátia'
cores = {'limpa':'\033]m',
'azul':'\033[34m',
'amarelo':'\033[33m',
'pretoebranco':'\033[7;30m'}
print('Prazer em te conhe... |
394 | 8ca77ed608108a9aa693acb686156e661794d7ab | # A perfect number is a number for which the sum of its proper divisors is exactly equal to the number.
# For example, the sum of the proper divisors of 28 would be 1 + 2 + 4 + 7 + 14 = 28,
# which means that 28 is a perfect number.
#
# A number whose proper divisors are less than the number is called deficient a... |
395 | b5ac3695a224d531f5baa53a07d3c894d44e8c4c | import matplotlib.pyplot as plt
Ci_MSB = [32,16,8,4,2,1]
Ci_LSB = [16,8,4,2,1]
CB = 1
CP_B = 0
CP_LSB = (32-1)*(CB+CP_B-1)+10
print(CP_LSB)
CP_MSB = 0
Csum_LSB = sum(Ci_LSB)+CP_LSB
Csum_MSB = sum(Ci_MSB)+CP_MSB
Cx = Csum_LSB*Csum_MSB+(CB+CP_B)*Csum_LSB+(CB+CP_B)*Csum_MSB
Wi_MSB = [Ci_MSB[i]*(CB+CP_B+Csum_LSB)/Cx for i... |
396 | c9d12f14fa0e46e4590746d45862fe255b415a1d | # vim: expandtab
# -*- coding: utf-8 -*-
from poleno.utils.template import Library
from chcemvediet.apps.obligees.models import Obligee
register = Library()
@register.simple_tag
def gender(gender, masculine, feminine, neuter, plurale):
if gender == Obligee.GENDERS.MASCULINE:
return masculine
elif gen... |
397 | 58e023c3c453d1e190fdb5bc457358f42d1bd93f | # https://leetcode.com/problems/how-many-numbers-are-smaller-than-the-current-number/
# BruteForce
class BruteForceSolution:
def smallerNumbersThanCurrent(self, nums):
answer = []
for num in nums:
counter = 0
for i in range(len(nums)):
if n... |
398 | b4b7e20c9558bd1b29a1c1fa24bfca8a2d292b27 | import xml.etree.ElementTree as ET
#tree = ET.parse('rutas/rutas_prueba.xml')
#treeToAdd = ET.parse('rutas/rutas_prueba_agregar.xml')
#root = tree.getroot()
#git rootToAdd = treeToAdd.getroot()
#for child in root:
# for test in child:
# print(test.tag, test.attrib)
#for elem in root.iter():
# print(... |
399 | 97bbb181cbc0f5bfbf0b2298133fc226b6217d91 | import tensorflow as tf
from tensorflow.python.framework import graph_util
from net import siameseNet_batchnorm as siameseNet
import dataset
import numpy as np
import cv2
import os
batch_size=64
input_height=32
input_width=32
total_epoch_num=50
snapshot=100
support_image_extensions=[".jpg",".png",".jpeg",".bmp"]
margi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.