text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python
import sys
import essentia
from essentia.streaming import *
import numpy as np
import math as m
import matplotlib.pyplot as plt
from matplotlib.colors import *
import matplotlib
def cos_sim(A,B):
"measures the cosine similarity of 2 vectors of equal dimension"
dot_product = np.vdot(A,B)
... |
#
# Copyright (C) 2005, Giovanni Bajo
#
# Based on previous work under copyright (c) 2002 McMillan Enterprises, Inc.
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the L... |
import jinja2
import webapp2
import os
import time
from ClothesModel import Clothes
from CSSIUser import CssiUser
from google.appengine.api import users
from google.appengine.ext import ndb
the_jinja_env = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions=['jinja2.ext.... |
import numpy as np
import math
class Env(object):
def __init__(self, env_params):
self.days = env_params['days']
self.num_interval = env_params['num_interval'] # number of intervals per day
self.action_size = env_params['action_size']
self.action_interval = env_params['ac... |
import math
#Read file
input_file = open(r'patht to file..')
mass_s = input_file.readlines()
mass = list(map(int, mass_s))
total_fuel = 0
new_fuel = 0
new_total = 0
for i in range(len(mass)):
fuel = mass[i]
while fuel > 0:
new_fuel = math.floor(fuel / 3 - 2)
fuel = new_fuel
if(fuel ... |
"""
8.11 Coins
Given an infinite number of quarters (25 cents), dimes (10 cents), nickels
(5 cents), and pennies (1 cent), write code to calculate the number of ways
of representing n cents.
"""
def make_change(n):
denoms = [25, 10, 5, 1]
map = [[0 for i in range(len(denoms))] for j in range(n+1)]
return ... |
# Created by SNEHAL at 25-04-2020
Feature: #Enter feature name here
# Enter feature description here
Scenario: # Enter scenario name here
# Enter steps here
|
# import modules
import math
#def solveEquation
def solveEquation():
'''
solveEquation is to solve quadratic equation.
this always has 2 roots given by
x1 =... and x2 = ...
'''
# input a, b, c
a= float(input('a='))
b= float(input('b='))
c= float(input('b='))... |
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 08 21:31:49 2017
@author: rkprajap
"""
import random
def hex_code_color():
a = hex(random.randrange(0,256))
b = hex(random.randrange(0,256))
c = hex(random.randrange(0,256))
a = a[2:]
b = b[2:]
c = c[2:]
if len(a)<2:
a = "0" + a
if... |
from LinkedList import *
import msvcrt as m
l = LinkedList()
while True:
print(chr(27) + "[2J") # << CLEAR SCREEN
print('[ Linked->List ]\n')
print(l, end='\n\n')
print('❤ 1.Add Head')
print('✨ 2.Add Tail')
print('🗑 3.Remove Head ')
print('❄ 4.Remove Tail')
print('❌ 5.Remove...')
print('⚠ ... |
from django.shortcuts import render, get_object_or_404, render_to_response
def home(request):
return render(request, 'index.html')
|
import os
import webbrowser
from tkinter import *
from tkinter import filedialog
import win32com.client
import winshell
from PIL import Image
from PyInstaller.utils.hooks import collect_data_files
from tkinterdnd2 import *
datas = collect_data_files('tkinterdnd2')
iconPath = r"%systemroot%\system32\imag... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
#!/usr/bin/env python
import numpy as np;
from maps import *
from actions import *
class Simulation():
#-----------------------Constructeur--------------------
def __init__(self,typeMap,posX,posY):
"""
typeMap : parametre de type Enum_Maps
"""
self.usedMap = Maps.sel... |
from datetime import datetime
from datetime import date
import json, os, sys
from django.shortcuts import render
from django.http import HttpResponseRedirect
from django.core.mail import EmailMessage
from django.conf import settings
from django.http import Http404, HttpResponse
from scripts import combo_finder
... |
# Copyright 2012-2015 Canonical Ltd. This software is licensed under the
# GNU Affero General Public License version 3 (see the file LICENSE).
"""Tests for handling of MAAS API credentials."""
from __future__ import (
absolute_import,
print_function,
unicode_literals,
)
str = None
__metaclass__ = t... |
import re
with open('day_four.txt') as f:
data = f.read().split('\n\n')
data = [dict(entry.split(':') for entry in item.split()) for item in data]
def day4a(passwords):
keys = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'}
print(sum(not keys - i.keys() for i in passwords))
def day4b(passwords):
... |
import numpy as np
import pandas as pd
import praw
import tweepy
from keys import *
class Reddit:
'''
Class used to scrape top posts from specified subreddits.
'''
def __init__(self, username, password, client_id, secret_key, user_agent):
'''
-Initialize username, pa... |
import tensorflow as tf
import os,sys
CURRENT_DIR = os.path.dirname(__file__)
sys.path.append(os.path.join(CURRENT_DIR, '..'))
from utils.train_utils import show_pred_bbox
from utils.model_utils import BinWindows
from model.generate_anchors import get_rpn_label
from utils.bbox_ops_utils import np_bbox_transform_inv
f... |
[general]
name = string()
modulefile = string()
usesconfig = boolean(default=False)
usesconfspec = boolean(default=False)
enableddefault = boolean(default=True)
|
import unittest
from rb_tree import rb_tree_map
class test(unittest.TestCase):
def test1(self):
m = rb_tree_map()
m.put(10, 'marth')
m.put(0, 'fox')
m.put(50, 'peach')
m.put(40, 'samus')
m.put(70, 'falco')
# 10
# 0 50
# 40 70
... |
################################################################################
##
## BY: thaianhtaivn
## PROJECT MADE WITH: Qt Designer and PySide2
## V: 1.0.0
##
################################################################################
import datetime
import psutil
from psutil._common import bytes2human
impor... |
import random
def toss(i):
head_count = 0
tail_count = 0
for x in range(1, i):
new_toss = random.randint(0,1)
if new_toss == 1:
head_count += 1
result = "head"
else:
tail_count += 1
result = "tail"
print "Attempt #", x, ": Thr... |
def solution(stock, dates, supplies, k):
answer = 0
heap = [] # 우선순위 큐를 만들어준다.
idx = 0 # 시작지점을 0으로 설정해준다.
while stock < k:
for i in range(idx, len(dates)):
if stock < dates[i]: # stock이 dates[i]보다 작으면 break해준다.
break
heapq.heappush(heap,-supplies[i]) # ... |
import base64
import requests
import json
class FarmAPI():
headers = {
'Content-Type': 'application/json',
}
# change this
URI = "http://localhost:8000"
def __init__(self, username, password):
print("[+] Initializing credentials")
auth_str = ('%s:%s' % (username, password)).encode("utf-8")
self.headers... |
# Generated by Django 3.0 on 2021-01-28 08:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0003_destinations'),
]
operations = [
migrations.AddField(
model_name='destinations',
name='destinations_imag... |
# encoding = utf-8
import os
import sys
base_dir = os.path.dirname(__file__)
sys.path.append(base_dir)
from functools import reduce
import tensorflow as tf
from data_helper import load_data, batch_iter, pad_sequence_batch
from basic_seq2seq import BasicSeq2Seq
flags = tf.app.flags
flags.DEFINE_float("val_batch_num"... |
# -*- coding: utf-8 -*-
from django.test import TestCase
from django.conf import settings
from proxy_storage.meta_backends.base import MetaBackendObject, MetaBackendObjectDoesNotExist
from proxy_storage.meta_backends.mongo import MongoMetaBackend
from proxy_storage.testutils import override_proxy_storage_settings
fro... |
num1 = int(input("enter first number= "))
num2 = int(input("enter second number= "))
# 5 + 2 = 7
print(num1,"+",num2,"=",(num1+num2))
# 5 - 2 = 3
print(num1,"-",num2,"=",(num1-num2))
# 5 / 2 = 2.5
print(num1,"/",num2,"=",(num1/num2))
# 5 * 2 = 10
print(num1,"*",num2,"=",(num1*num2))
# 5 % 2 = 1
print(num1,"%",num2,"=... |
import glob
from AutoMLVisionClient import AutoMLVisionClient
def train_project():
# # Init class
client = AutoMLVisionClient(api_key='<your_api_key>')
print('Project creation...')
project_id = client.create_project(project_name='Floor plans classifier', project_description='Automaticaly count ... |
class generador(object):
def __init__(self,maximo):
self.maximo = maximo
def numeroImpar(self):
x=1;
while x < self.maximo:
yield x+2
x+=2
genera = generador(20)
numero = genera.numeroImpar()
while True:
n = next(numero)
if(n > 10):
print(n)
break
else:
print("Menor:",n)
|
#Functions to implement the Integer-to-Integer MDCT filter bank. File based, it first reads in the complete audio file and then computes the MDCT filter bank output.
#Only works with stereo input!
#Gerald Schuller, July 2018.
from MDCTfb import *
#from Dmatrix import *
#from Dinvmatrix import *
from LiftingFmat import... |
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 3 16:07:53 2016
@author: Stanley
"""
wt = float(input("Please enter your weight in kilograms:"))
ht = float(input("Please enter your height in meters:"))
BMI = wt/(ht*ht)
if (BMI < 18.5):
print (BMI, "Weight Status: Underweight")
if (18.5 <= BMI <= 24.9):
print... |
''' Question 3.1:
Write a find_lucky_number function. Your lucky number is equal to the length of your name times 8.
The function receives a name as parameter. And return a message.
Fill in the blanks to complete the code to make it work.
Note: Instead of printing the message, we will return the message.
This way, ... |
from django.shortcuts import render, redirect
from django.http import HttpResponse, HttpResponseRedirect, Http404
from wxpy import *
from threading import Thread, Event
from wxRobot import consumers
import os
import base64
import json
import time
from initialize import helper
from helper.channels_manager import cm
from... |
import sys
import time
from worker import Worker
from worker import Exception410
from worker import ExceptionParse
from worker import ExceptionPersiste
from worker import ExceptionAnyUrl
from pymongo.errors import ServerSelectionTimeoutError
from parseurs.factoryParseur import FactoryParseur
from verifications.verifica... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2020-2021 Barcelona Supercomputing Center (BSC), Spain
#
# 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... |
import numpy as np
import pandas as pd
import pandasql as ps
import glob
# proportional value for each category to know how many % of people are this type of ancestry on 2011 and 2016
df = pd.read_csv("combined_csv.csv")
# 1: drop column that has the "total" because those are subtotal
# source: https://stackoverflow... |
import logging
from http.cookies import SimpleCookie
from cryptojwt.exception import UnknownAlgorithm
logger = logging.getLogger(__name__)
OAUTH2_NOCACHE_HEADERS = [
('Pragma', 'no-cache'),
('Cache-Control', 'no-store'),
]
def new_cookie(endpoint_context, user, **kwargs):
if endpoint_context.cookie_dea... |
# File: checkerboard.py
# Date: November 14, 2017
# Author: Adam Abad
# Purpose: To make a checkerboard based on a user's input
def intro():
print()
print("This program will display a checkerboard.")
print("You will enter the number of rows, columns,")
print("block size and the checkerboard charac... |
# Generated by Django 3.0.6 on 2020-06-08 15:43
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('questions', '0002_auto_20200608_1809'),
]
operations = [
migrations.AddField(
model_name='question',
name='explanati... |
from tkinter import *
b=Tk()
def fun1():
val=entry.get()
val1=entry.get()
sum=val+val1
sum.insert()
def fun2():
val=entry.get()
val1=entry.get()
sum=val-val1
sum.insert()
def fun3():
val=entry.get()
val1=entry.get()
sum=val*val1
sum.insert()
def fun4():
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Script to build xG model using logistic regression
# For use with Wyscout data - avialable from
# https://figshare.com/collections/Soccer_match_event_dataset/4415000/2
# Based on code provided by David Sumpter / Friends of Tracking (2020)
# https://www.youtube.com/cha... |
import pygame
import collisions
import event
import gamestate
import graphics
import config
import ball
class Game():
def __init__(self,x,y):
self.was_closed = False
self.play(x,y)
def play(self,x,y):
self.was_closed = False
while not self.was_closed:
game =... |
usuario= str(input('Coloque su usuario'))
contraseña = str(input('Coloque su contraseña'))
x = "Danny"
if usuario == "Danny" and contraseña == "0258":
print ("Inicio de sesion correcto")
else:
print ("Nombre de usuario incorrecto") |
import pygame
import carla
import random
import time
import numpy as np
import cv2
import queue
# custom libraries
from ds2_controller import DS2_Controller # dualshock2 controller module
from lane_image_functions import * # lane detection image processing functions
from laneDetect import * # l... |
# coding: utf-8
# In[1]:
import numpy as np
import textwrap
import cv2
import stepic
import binascii
from Crypto.Cipher import AES
from steganography.steganography import Steganography
def Blocks_16_Bit(plain_text):
if(len(plain_text)==0):
return "Invalid input"
byte_concat = len(plain_text)%16
... |
"""
File: asteroids.py
Original Author: Br. Burton
Designed to be completed by others
This program implements the asteroids game.
"""
import arcade
import math
import random
# These are Global constants to use throughout the game
SCREEN_WIDTH = 800
SCREEN_HEIGHT = 600
BULLET_RADIUS = 30
BULLET_SPEED = 10
BULLET_LIFE... |
from discord.ext import commands
import discord
from botlibrary import constants
class Commands(commands.Cog):
def __init__(self, client):
self.client = client
def ist_gepinnt(self, message):
return not message.pinned
@commands.command(name="ping")
async def ping_command(self, ctx):
... |
def solution(x):
a = []
for i in str(x):
int_i = int(i)
a.append(int_i)
plus = sum(a)
if x%plus == 0:
answer = True
else:
answer = False
return answer |
from django.urls import path, include
from rest_framework import routers
# from .views import RecipeViewSet, RecipeListView, RecipeDetailView, IngredientViewset
from .views import *
from user.views import UserProfileViewset
router = routers.DefaultRouter()
router.register('ingredients', IngredientViewset)
router.regis... |
'''Problem 1: Write an iterator class reverse_iter, that takes a list and iterates it from the reverse direction. ::'''
class rev_range:
def __init__(self, n):
self.n = n
self.i = n
def __iter__(self):
return self
def next(self):
i = self.i
if self.i > 0 :
self.i -= 1
return i
else:
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'lolo.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
... |
# -*- coding: utf-8 -*-
"""Tests for the internal DSL."""
import unittest
import pybel.constants as pc
from pybel import BELGraph
from pybel.constants import NAME
from pybel.dsl import (
Abundance,
ComplexAbundance,
CompositeAbundance,
EnumeratedFusionRange,
Fragment,
Gene,
GeneFusion,
... |
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import add_days, date_diff
from verp.hotels.doctype.hotel_room_reservation.hotel_room_reservation import g... |
import requests
from bs4 import BeautifulSoup
def wordofday(txt_log):
try:
page = requests.get('http://www.wordthink.com/')
soup = BeautifulSoup(page.text,'html.parser')
word = "Word:\n"+soup.find('div',{'class':'singlemeta'}).find('p').text
txt_log.AppendText(word+"\n")
return word
except:
txt_log.Appe... |
from abc import ABCMeta, abstractmethod
class AbstractPortfolioAllocation(object):
"""
"""
__metaclass__ = ABCMeta
@abstractmethod
def calculate_weights(self):
"""
Provides the mechanisms to calculate the list of signals, suggested positional size, the strength of the signal
"""
raise NotImplementedErro... |
import pytest
from utensor_cgen.transformer.pipeline import TransformerPipeline
def factory():
@pytest.mark.deprecated
def test(vgg_ugraph):
trans = TransformerPipeline([
'linear_reorder',
'quantize',
'conv_pool',
])
new_ugraph = trans.transform(vgg... |
import re
def find(s, words):
t = len(words[0])
matches = []
for word in words:
matches += [m.start() for m in re.finditer(word, s)]
matches = sorted(matches)
for i in range(0, len(matches) - len(words) + 1):
if valid(matches[i : i + len(words)], t):
yield matches[i]
de... |
# -*- coding: utf-8 -*
__author__ = 'admin'
import requests
import hashlib
import time
class PlayvisionAPI(object):
__API_URL__ = "http://api.playvision.ru/v1/"
def __init__(self, project_id, api_secret):
self._project_id = project_id
self._api_secret = api_secret
def _send_request_(self... |
# Usage example
from MyRandomResizeTransform import MyRandomResizeTransform
from dataset import MyDataset
from torch.utils.data import DataLoader, random_split
from dataset.my_data_loader import MyDataLoader
image_size = [192, 256, 320, 384, 448]
MyRandomResizedCrop.IMAGE_SIZE_LIST = image_size.copy()
MyRandomResiz... |
from plyer import battery
import time
from sender import Sender
import location
def main():
now = time.time()#seting the start of usin0
while True:
if battery.status['percentage'] <= 1:#checking the battery's level
Sender(open('data.txt', 'r').read(), location.loc())#sending locatio... |
import numpy as np
import matplotlib.pyplot as plt
plt.style.use("ggplot")
fig, axs = plt.subplots(3)
hor = np.loadtxt("horizontal_angle.csv", delimiter=",")
ver = np.loadtxt("vertical_angle.csv", delimiter=",")
middle = np.loadtxt("middle.csv", delimiter=",")
x = np.arange(np.size(ver, 1))
mean_middle = np... |
# Q2a
def getPartsInCode(productCode):
string = 'ABCDEFGHIJKL'
a = ''
x = ''
for i in productCode:
count = productCode.count(i)
if a != i:
x += (str(count) + i + ' ')
a = i
print(x)
return x
x = getPartsInCode('ABBBG')
# Q2b
def fullStock():
startLeve... |
#Heuristicas utilizadas
def Heuristica1(estado, meta):
distancia = 0
for andar in estado:
if andar not in meta:
distancia += 1
return distancia
def Heuristica2(estado, meta):
distancia = 0
for andar in estado:
if andar in meta:
pass
elif (andar + 8 in... |
from django.contrib import admin
from django.urls import path,include
from .views import activity,news,users,place,finance,club,appraisal
urlpatterns = [
# path('admin/', admin.site.urls),
# path(r'club_management/', include('management.urls'))
path(r'index/',club.index),
path(r'activityform_practice/'... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'stopvideowindow.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_StopvideoWindow(object):
def setupUi(self, Sto... |
import matplotlib.pyplot as plt
import numpy as np
class DeformationMap():
""" A class for importing Davis displacement data with
methods for returning deformation maps
Requires: path and filename
Returns: a deformation map object
Usage:
deformation_map=deformation_map('path','filename')
... |
"""
Rate the emotional level of each sentence in a novel.
"""
import re
import sys
from os import listdir
from os.path import isfile, join
from collections import defaultdict
import pandas as pd
import numpy as np
from spacy.lang.en import English
from scipy.signal import argrelextrema
from generate_music_specificat... |
#!/usr/bin/env python
"""
XAFS pre-edge subtraction, normalization algorithms
"""
import numpy as np
from scipy import polyfit
from scipy.signal import find_peaks_cwt
from scipy.integrate import simps
from lmfit import Parameters, Minimizer
from lmfit.models import (LorentzianModel, GaussianModel,
... |
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
import csv
from selenium.common.exceptions import NoSuchElementException
#PATH = '/usr/local/bin/chromedriver'
PATH = 'C:/Users/vtec-mchen/PycharmProjects/chromedriver.exe'
def Get_to_list(driver, url):
driver.get(url)
... |
"""Use this for development"""
from .base import *
from .base import ALLOWED_HOSTS
from .base import BASE_DIR
from .base import INSTALLED_APPS
from .base import MIDDLEWARE
BASE_URL = "http://ecom.local:8000"
ALLOWED_HOSTS += ["127.0.0.1", "ecom.local"]
DEBUG = True
WSGI_APPLICATION = "home.wsgi.dev.application"
INST... |
from datetime import datetime
isinpackage = not __name__ in ['info', '__main__']
if isinpackage:
from .db import get_collection
from . import util
else:
from db import get_collection
import util
def create_md():
md = '<style>.markdown-section{max-width: unset;}</style>\n\n'
md += '# 過去の休講情報一覧\... |
# coding: utf-8
# In[100]:
from PIL import ImageGrab,ImageOps
# In[101]:
import pyautogui
import time
from numpy import *
# In[ ]:
class cordinates():
replay=(338,326) #The coordinates of the replay button
dinosaur=(75,332) #the upper coordinate or the head of the dino
up=(75,323)
... |
'''
This script is used to register new cameras on a fog node in the framework. The folders associated with the camera are
created and the line coordinates for traffic density measurement are set.
'''
import os
def register(fog_node_name, camera_name, coordinates):
'''
Register the camera with the given coordinates... |
from django.db import transaction
from django.conf import settings
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from nudge.server import process_batch, versions
try:
import simplejson as json
except ImportError:
import json
@csrf_exempt
def batch(request):
key... |
import sys
def test(did_pass):
""" Print the result of a test. """
linenum = sys._getframe(1).f_lineno
if did_pass:
msg = 'Test at line {0} ok.'.format(linenum)
else:
msg = 'Test at line {0} FAILED.'.format(linenum)
print(msg)
def test_suite():
""" Run the suite of tests for t... |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 11 20:19:13 2021
@author: wanti
"""
# https://www.datacamp.com/community/tutorials/xgboost-in-python
# https://github.com/r4msi/DrivenData-PumpItUp/blob/master/XGboost_Lumping.md
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import ... |
import math
import aux_funcs as af
import model_funcs as mf
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlockWOutput(nn.Module):
expansion = 1
def __init__(
self, args, in_channels, channels, params,
stride=1, head_variant=None, he... |
#
# Copyright (c) 2022, Gabriel Linder <linder.gabriel@gmail.com>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS"... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class QLTecnica(object):
u"""Técnica para Q-Learning"""
def __init__(self, parametro=None, paso_decremento=0, intervalo_decremento=0):
super(QLTecnica, self).__init__()
self._paso_decremento = paso_decremento
self._intervalo_decremento = in... |
'''
Created on 22.04.2017
@author: pro
'''
from model import User,Message
def get_user_by_id(session,id):
user = session.query(User).get(id)
if user:
return user
def get_user_by_name(session, name):
user = session.query(User).filter_by(name=name).one()
if user:
return user
def regist... |
# Generated by Django 2.2.6 on 2019-11-12 13:07
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operation... |
import pytest
from covid_shared.ihme_deps import _lazy_import_callable
def test_lazy_import_callable_pass():
from itertools import chain
chain2 = _lazy_import_callable("itertools", "chain")
assert chain is chain2
def test_lazy_import_callable_fail():
magic = _lazy_import_callable("fairyland", "mag... |
from random import getrandbits as bits
from zen.render import BrailleArray
def _make_braille() -> BrailleArray:
"""
Randomly generates a single braille character
"""
return (
(bits(1), bits(1)),
(bits(1), bits(1)),
(bits(1), bits(1))
)
def _is_valid(braille: BrailleArray) ... |
import csv
import json
from shapely.geometry import shape
from shapely.wkt import dumps
with open('strassen.json') as fi, open('strassen.csv', 'w') as fo:
writer = csv.DictWriter(fo,
fieldnames=['id', 'json', 'geometrie', 'gemeinde_name', 'strasse_name'])
writer.writeheader()
for featur... |
from Global import *
from Sequence import *
def transformToRobot(scramble):
moves = scramble.split(" ")
size = 7
# if len(moves) < 15:
# size = 2
# elif len(moves) < 30:
# size = 3
# elif len(moves) < 59:
# size = 4
# elif len(moves) < 79:
# size = 5
# elif l... |
import streamlit as st
import qsharp
from HostPython import RandomBit, RandomByte
import plotly.graph_objects as go
import numpy as np
import math
st.set_page_config(page_title='Quantum', layout='wide')
st.markdown('**Random bit**')
number_of_bites = st.number_input('Type the number of bites to simulate', min_value=1... |
import numpy as np
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv2D
from keras.layers.convolutional import MaxPooling2D
from keras.utils import np_ut... |
# Generated by Django 2.0.1 on 2018-02-25 05:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('calculator', '0011_auto_20180131_1055'),
]
operations = [
migrations.AddField(
model_name='research_publications',
n... |
project # unused variable (src/conf.py:28)
copyright # unused variable (src/conf.py:29)
author # unused variable (src/conf.py:30)
extensions # unused variable (src/conf.py:37)
myst_enable_extensions # unused variable (src/conf.py:38)
templates_path # unused variable (src/conf.py:41)
exclude_patterns # unused var... |
# https://atcoder.jp/contests/abc058/tasks/arc071_a
n=int(input())
s=[sorted(input()) for _ in range(n)]
alfa=[float('inf')]*26
for e in s:
for i in range(26):
cnt=e.count(chr(97+i))
alfa[i]=min(alfa[i],cnt)
ans=[]
for i in range(26):
ans.append(chr(97+i)*alfa[i])
print(*ans,sep='... |
###########################################################
class TokenNode(object):
def __init__(self, id, word_form, pos_tag=None, ner_tag=None, dep_label=None, dep_head=None, scene=None, utterance=None):
self.id = int(id)
self.word_form = str(word_form)
self.pos_tag = str(pos_tag)
... |
from xlrd import open_workbook
from pyquery import PyQuery as pq
import urllib2
import csv
from lxml import etree
import sys
def parse_xls(my_workbook_name):
wb = open_workbook(my_workbook_name)
# the workbook must have only one sheet with the data in it
sheet = wb.sheet_by_index(0)
print 'Sheet:',shee... |
"""GA AEM Ross Brodie 20160606 """
####### Do not change anything below this line #######
import os
import subprocess
import sys
import re
# Set parameters
DATA_FILE = 'frome-tempest.dat'
CONTROL_FILE = '2'
STM_FILE = '2'
ALTERATIONS_ = '0'
LINE_NUMBER = '0'
EASTING_ = '0'
NORTHING_ ... |
# coding: utf-8
# In[1]:
get_ipython().magic(u'matplotlib inline')
from sklearn.ensemble import RandomForestRegressor
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import train_test_split
from sklearn.model_selection import cross_val_score
from sklearn.metrics import mean_absolute_erro... |
"""create items table
Revision ID: 6700550b05f9
Revises:
Create Date: 2020-02-26 16:32:57.226752
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy import text
# revision identifiers, used by Alembic.
revision = '6700550b05f9'
down_revision = None
branch_labels = None
depends_on = None
def upgrade... |
# -*- coding: utf-8 -*-
import numpy as np
import tensorflow as tf
from yolo_v3 import _conv2d_fixed_padding, _fixed_padding, _get_size, \
_detection_layer, _upsample
slim = tf.contrib.slim
_BATCH_NORM_DECAY = 0.9
_BATCH_NORM_EPSILON = 1e-05
_LEAKY_RELU = 0.1
def _reorg(inputs, stride):
return f.extract_ima... |
import sys
try:
import logging
import json
import threading
from threading import Semaphore
import colorama
from colorama import Fore
from colorama import init
colorama.init()
init(autoreset=True)
from captchatools import captcha_harvesters
from newegg.create_account import d... |
import random
alpha = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
npt = open('test.txt', 'w')
a = random.randint(100, 999)
b = random.choice(alpha)
c = random.seed()
i = 0
a = input();
while i < int(a):
npt.write (random.choice(alpha) + ' ' + str(random.randint(100, 999)) + ' ' + random.choice(alpha) + random.choice(alpha) + ' '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.