index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
3,600 | fb92912e1a752f3766f9439f75ca28379e23823f | REDIRECT_MAP = {
'90':'19904201',
'91':'19903329',
'92':'19899125',
'93':'19901043',
'94':'19903192',
'95':'19899788',
'97':'19904423',
'98':'19906163',
'99':'19905540',
'100':'19907871',
'101':'19908147',
'102':'19910103',
'103':'19909980',
'104':'19911813',
... |
3,601 | f29d377e8a8fd6d2e156da665478d7a4c167f7d5 | import gdalnumeric
#Input File
src = "../dati/islands/islands.tif"
#Output
tgt = "../dati/islands/islands_classified.jpg"
srcArr = gdalnumeric.LoadFile(src)
classes = gdalnumeric.numpy.histogram(srcArr,bins=2)[1]
print classes
#Color look-up table (LUT) - must be len(classes)+1.
#Specified as R,G,B tuples
lut = [[... |
3,602 | 2d4b0e7b430ffb5d236300079ded4b848e6c6485 | print raw_input().count(raw_input()) |
3,603 | d7653a205fb8203fed4009846780c63dd1bcb505 | import csv
import sys
if len(sys.argv[1:]) == 5 :
(name_pos, start_pos, length_pos,
first_note_pos, second_note_pos) = [int(pos) for pos in sys.argv[1:]]
elif len(sys.argv[1:]) == 4 :
(name_pos, start_pos, length_pos,
first_note_pos) = [int(pos) for pos in sys.argv[1:]]
second_note_pos = None
e... |
3,604 | 84f6336261e1c276f029822754842514715791df | from unittest import TestCase
from spiral.spiral_matrix import SpiralMatrix
class TestOutwardCounterClockwise(TestCase):
def test_traverse_empty(self):
matrix = []
actual = [i for i in SpiralMatrix(matrix, clockwise=False, inward=False)]
self.assertEqual([], actual)
def test_traverse_... |
3,605 | fc01c6fb812fe78ca04496494d68fcc90ae706f5 | import numpy as np
def shufflelists(lists):
li = np.random.permutation(len(lists[0])
lo = []
for i in range(len(li)):
|
3,606 | 9a7908212bf13565109cd4d9ab6de65909bc6910 | # Copyright 2014 Charles Noneman
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
3,607 | 78c8f953b924f3e664570b844bf736a788e9cfb7 | from distutils.core import setup, Extension
setup(name='supermodule', version='1.0', \
ext_modules=[Extension('supermodule', ['main.c'])])
|
3,608 | 88862d6bee5d83dd5f1c656a06a9dc46a5254b10 | import math
import operator as op
Symbol = str
Number = (int, float)
Atom = (Symbol, Number)
List = list
Exp = (Atom, List)
Env = dict
def standard_env() -> Env:
"An environment with some scheme standard procedures"
env = Env()
env.update(vars(math)) # sin, cos, sqrt, pi ...
env.update({
... |
3,609 | 18be97061c65185fcebf10c628e0e51bb08522cf | import torch
import argparse
from DialogGenerator import DialogGenerator
from DialogDataset import DialogDataset
from DialogDiscriminator import DialogDiscriminator
from transformers import GPT2Tokenizer
import os
def prep_folder(args):
""" Append to slash to filepath if needed, and generate folder if it doesn't e... |
3,610 | 68dcac07bbdb4dde983939be98ece127d963c254 | """Google Scraper
Usage:
web_scraper.py <search> <pages> <processes>
web_scraper.py (-h | --help)
Arguments:
<search> String to be Searched
<pages> Number of pages
<processes> Number of parallel processes
Options:
-h, --help Show this screen.
"""
import re
from functools impo... |
3,611 | 5db450424dc143443839e24801ece444d0d7e162 | # Generated by Django 3.2 on 2021-06-28 04:32
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rrhh', '0014_alter_detallepermiso_fecha_permiso'),
]
operations = [
migrations.AlterField(
model_name='permiso',
name=... |
3,612 | 5b6ed75279b39a1dad1bf92535c4b129bb599350 | class Solution:
"""
https://leetcode.com/problems/game-of-life/
289. Game of Life
Medium
--------------------
According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970."
Given a ... |
3,613 | 3cac7829cf0c07ddc704a25ec3c781c9510a8e0c | __version__ = '18.07.0' |
3,614 | 5efb8151375d705f3591921654f847e45b6927c9 | """
You are given two strings s1 and s2 of equal length. A string swap is an operation where you choose two indices in a string (not necessarily different) and swap the characters at these indices.
Return true if it is possible to make both strings equal by performing at most one string swap on exactly one of the stri... |
3,615 | efa06d929e76a255afd9923b5340252c291a325c | import sys
from collections import defaultdict
sys.setrecursionlimit(1200)
def dfs(G, v, prev):
t = []
s = 0
for x in G[v]:
if x == prev: continue
tmp = dfs(G, x, v)
s += tmp[1]
t.append(tmp[0] - tmp[1])
t.sort()
t = t[:2]
if len(t) < 2:
return (s... |
3,616 | 2962ef1d7ecd4e8d472b9dc36664e4e8745391fd | from keras.preprocessing.text import text_to_word_sequence
from keras.models import Sequential
from keras.layers import Activation, TimeDistributed, Dense, RepeatVector, recurrent, Embedding
from keras.layers.recurrent import LSTM
from keras.optimizers import Adam, RMSprop
#from nltk import FreqDist
import numpy as np
... |
3,617 | be90447eb7c717ae0bae28fd7f10238be733648d | import json
from tqdm import tqdm
from topic.topic import get_topic_scores, get_topic_similarity
user_weights = json.load(open('data/selected_user_weights.json', 'r', encoding='utf8'))
reviews = json.load(open('data/business_reviews_test.json', 'r', encoding='utf8'))
for business, business_reviews in reviews.items(... |
3,618 | 6add599035573842475c7f9155c5dbbea6c96a8a | from pyathena import connect
from Config import config2
from Config import merchants
def get_mapped_sku(sku):
try:
cursor = connect(aws_access_key_id=config2["aws_access_key_id"],
aws_secret_access_key=config2["aws_secret_access_key"],
s3_staging_dir=confi... |
3,619 | 71ffad81bcbc480dc0a750680bc72e1d5c48556a | # Generated by Django 2.1.5 on 2021-06-01 19:16
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('fotbal', '0008_auto_20210601_2109'),
]
operations = [
migrations.RemoveField(
model_name='komenty',
name='jmeno',
),... |
3,620 | b355bd5a519d65ea35d4e8d5e6a384424d79130a | # Write a class to hold player information, e.g. what room they are in
# currently.
class Player():
def __init__(self, name, location, items=[]):
self.name = name
self.location = location
self.items = items
# def try_direction(self, user_action):
# attribute = user_action + '_... |
3,621 | 259a4bb39496bdfc71d60edb4994d26351c6961d | class Patient(object):
def __init__(self, id_number, name, bed_number, *allergies):
self.id_number = id_number
self.name = name
self.allergies = allergies
self.bed_number = bed_number
class Hospital(object):
def __init__(self, name, capacity):
self.patients = []
... |
3,622 | 5c1d1eafb913822be9b6e46b15c6886f8bf3e2e1 | from flask import Flask, json, request, jsonify
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
import warnings
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://root:1234@localhost/escuela'
app.config['SQLALCHEMY_TRACK_MODIFICATIONS']=False
db = SQLAlche... |
3,623 | 7a41826f65f2f55b4c678df2ac06027df6ca50d4 | __author__ = 'piotrek'
import os
import zipfile
import tarfile
from PyQt5 import QtWidgets
from PyQt5 import QtGui
from PyQt5 import QtCore
from Widgets.list_view import ListView
from Threads.PackThread import PackThread
class CreateArchive(QtWidgets.QDialog):
def __init__(self, model, index, path, parent=Non... |
3,624 | 4c59e5fab2469af3f40cafaac226a993f6628290 | import json
import tempfile
import zipfile
from contextlib import contextmanager
from utils import (
codepipeline_lambda_handler,
create_zip_file,
get_artifact_s3_client,
get_cloudformation_template,
get_input_artifact_location,
get_output_artifact_location,
get_session,
get_user_parame... |
3,625 | 4243c863827f1378c364171ca7d8fdabd42be22f | #!/usr/bin/env python
#pylint: skip-file
"""
HostApi.py
Copyright 2016 Cisco Systems
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... |
3,626 | 35288c9ad4d3550003e3c2f9e9034f4bce1df830 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 15 19:27:59 2020
@author: Dan
"""
import numpy as np
def shift(v,i,j):
if i <= j:
return v
store = v[i]
for k in range(0, i-j-1):
v[i-k] = v[i-k-1]
v[j] = store
return v
def insertion(v):
for i in range(1, len(v)):
j = i
... |
3,627 | 5068a78a1aa31a277b3b5854ddd1d8990d07b104 | #roblem: Have the function PrimeTime(num)
# take the num parameter being passed and return
# the string true if the parameter is a prime number, \
# otherwise return the string false.
# The range will be between 1 and 2^16.
def PrimeTime(num):
prime1 = (num-1)%6
prime2 = (num+1)%6
if prime1 * prime2 =... |
3,628 | bcbcb4ea3a3b8b5c11e9b107103418ae79a3921c | # Create your views here.
from django.shortcuts import render_to_response, Http404, render
from django.template import RequestContext
from books.models import Book
from django.http import HttpResponse, HttpResponseRedirect
import urllib, urllib2
import json
def incr_reads(request, book_id):
if request.POST:
... |
3,629 | 1b3891565f776064cfcca02fb22ea65853f7e66f | from matplotlib import pyplot as plt
# Function for testing
# Maps x => x*x
def calculate(x):
return x * x
inputs = [-0.5, -0.4, -0.3, -0.2, -0.1, 0, 0.1, 0.2, 0.3, 0.4, 0.5]
outputs = [calculate(x) for x in inputs]
plt.plot(inputs, outputs)
plt.savefig("plot.png") |
3,630 | 3ccbafbdc84447438c194288b1409e332bb2b479 | import cv2 as cv
import numpy as np
from servo import *
from func import *
#import threading
#import dlib
# import socket
# import struct
# import pickle
def constrain(val, minv, maxv):
return min(maxv, max(minv, val))
KP = 0.22
KI = 0
KD = 0.17
last = 0
integral = 0
# constants
SIZE = (400, 300)
RECT = np.flo... |
3,631 | 98b0e42f3ed1a234f63c4d3aa76ceb9fce7c041d | from time import perf_counter_ns
from anthony.utility.distance import compare, compare_info
from icecream import ic
start = perf_counter_ns()
ic(compare("tranpsosed", "transposed"))
print(f"Example Time: {(perf_counter_ns() - start)/1e+9} Seconds")
ic(compare_info("momther", "mother"))
|
3,632 | 2f5244c6144f5aafce29e5aba32bd7e3fc7ecf5b | # -*- coding: utf-8 -*-
'''
* EAFS
* Copyright (C) 2009-2011 Adam Etienne <eadam@lunasys.fr>
*
* 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 version 3.
*
* This program is distributed i... |
3,633 | 5580e5942370c925b759b09675306cdfbc7dd4f1 | '''
Created on 5 Mar 2010
@author: oppianmatt
'''
# hook to find setup tools if not installed
try:
from ez_setup import use_setuptools
use_setuptools()
except ImportError:
pass
from setuptools import setup, find_packages
setup(
name = "django-defaultsite",
version = "1.1",
packages = find_pac... |
3,634 | 856beaf3b9dad333d5b48c1be3a8ad917f8d020c | from flask import Blueprint, request, make_response
from untils import restful, cacheuntil
from untils.captcha import Captcha
from exts import smsapi
from .forms import SMSCaptchaForm
from io import BytesIO
bp = Blueprint('common', __name__, url_prefix='/c')
# @bp.route('/sms_captcha/', methods=['post'])
# def sms_c... |
3,635 | 05f77472625e902b66c4a97a4c640835826bd494 | from functiona import *
total = totalMarks(85,67,56,45,78)
avg = average(total)
grade = findGrade(avg)
print(grade)
print(total)
print(avg) |
3,636 | 0f4bb65b93df997ca1a9b7945ebcec53a2f43822 | """This module will serve the api request."""
import json
from bson.json_util import dumps
from flask import abort, request, Response, jsonify
from api import app, collection
@app.route("/api/v1/users", methods=['POST'])
def create_user():
"""
Function to create new users.
"""
try:
# Creat... |
3,637 | 6b6397fd18848ffa2ae9c0ec1443d20f2cbeb8b0 | import math
import pandas as pd
from matplotlib import pyplot as plt
tests = [
{ "task": "listsort", "prompt": "examples", "length": 5, "shots": 0, "accuracy": 0.28, "trials": 50},
{ "task": "listsort", "prompt": "examples", "length": 5, "shots": 1, "accuracy": 0.40, "trials": 50},
{ "task": "listsort", "... |
3,638 | 46b1e5adbd956c35820d7d2b17628364388cdcd7 | __author__ = 'tomer'
import sqlite3
from random import randint
import test_data
def init_database(conn):
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS catalogs
(id INTEGER PRIMARY KEY AUTOINCREMENT, catalog_name TEXT)''')
c.execute('''CREATE TABLE IF NOT EXISTS products
... |
3,639 | ff3962d875da8e3f9e6c3178b1a8191ebb8a7b60 | TABLE_NAME = 'active_module'
|
3,640 | 16a77c45a58e31c575511146dfceeaef0a2bc3a7 | def get_partial_matched(n):
pi = [0] * len(n)
begin = 1
matched = 0
while begin + matched < len(n):
if n[begin + matched] == n[matched]:
matched += 1
pi[begin + matched - 1] = matched
else:
if matched == 0:
begin += 1
else:
... |
3,641 | 33c4e0504425c5d22cefb9b4c798c3fd56a63771 | #!/usr/bin/python
import math
def Main():
try:
radius = float(input("Please enter the radius: "))
area = math.pi * radius**2
print("Area =", area)
except:
print("You did not enter a number")
if __name__ == "__main__":
Main()
|
3,642 | 13a2814e8744c6c09906d790185ed44fc2b3f23e | import random
import torch
import numpy as np
from torch.autograd import Variable
class SupportSetManager(object):
FIXED_FIRST = 0
RANDOM = 1
def __init__(self, datasets, config, sample_per_class):
self.config = config
(TEXT, LABEL, train, dev, test) = datasets[0]
self.TEXT = TEXT
... |
3,643 | 9f2a8e78aa2e3eab8f74847443dec9083603da39 | import socket
# Packet Sniffing
# It's All Binary
# Usage: python basic_sniffer.py
# create the sniffer raw socket object
sniffer = socket.socket(socket.AF_INET,socket.SOCK_RAW, socket.IPPROTO_ICMP)
#bind it to localhost
sniffer.bind(('0.0.0.0',0))
# make sure that the IP header is included
sniffer.setsockopt(soc... |
3,644 | b10a50ce649650542d176a2f6fb8c35c500fbc38 | from rest_framework import serializers
from django.contrib.auth import password_validation
from rest_framework.validators import UniqueValidator
from .models import CustomUser, Role, Permission, ActionEntity
from .utils import create_permission
class ActionEntitySerializer(serializers.ModelSerializer):
id = ser... |
3,645 | 919e1f8a4b021d75496f3bcff369261a09362a65 | from typing import Callable, List, Optional
import numpy as np
import lab1.src.grad.grad_step_strategy as st
import lab1.src.grad.stop_criteria as sc
DEFAULT_EPSILON = 1e-9
DEFAULT_MAX_ITERATIONS = 1e5
def gradient_descent(f: Callable[[np.ndarray], float],
f_grad: Callable[[np.ndarray], np.nda... |
3,646 | 8b583ee55df409020a605b467479236e610a2efe | from external.odds.betclic.api import get_odds
# FDJ parsing is broken - their UI has been refactored with JS framework &
# protected async JSON API usage (requires HEADERS) and more complex to isolate & group match odds
# hence move to another betting website - which is still full html rendered
|
3,647 | 0f266db39988cfce475380036f4f4f5b1a1fee1a | """
dansfunctions - various useful functions in python
usage:
>>import dansfunctions
>>dansfunctions.fg # module of general mathematical, vector and string format functions
>>dansfunctions.fp # module of matplotlib shortcuts
>>dansfunctions.widgets # module of tkinter shortcuts
Requirements: numpy
Optional requirem... |
3,648 | 7da274803de80f2864471d00c9d15aff1103372f | from nodes.Value import Value
class Number(Value):
def __init__(self, number: int):
if abs(number) > 2 ** 31:
raise SyntaxError(str(number) + ' number is out of range')
self.number = number
def __str__(self):
return str(self.number)
|
3,649 | 99ecb927e22bc303dd9dffd2793887e7398dbb83 | #Importacion de Dependencias Flask
from flask import Blueprint,Flask, render_template, request,redirect,url_for,flash
#modelado de basedato.
from App import db
# Importacion de modulo de ModeloCliente
from App.Modulos.Proveedor.model import Proveedor
#Inportacion de modulo de formularioCliente
from App.Modulos.Proveedo... |
3,650 | f29fa3d796d9d403d6bf62cb28f5009501c55545 | """You are given a string .
Your task is to find out if the string contains:
alphanumeric characters, alphabetical characters, digits,
lowercase and uppercase characters."""
s = raw_input()
print(any(i.isalnum()for i in s))
print(any(i.isalpha()for i in s))
print(any(i.isdigit()for i in s))
print(any(i.islow... |
3,651 | 3f655a12ac45c152215949d3d8bdb71147eeb849 | from collections import deque
def safeInsert(graph,left,right):
if left not in graph:
graph[left] = {}
graph[left][right] = True
if right not in graph:
graph[right] = {}
graph[right][left] = True
def trace(graph,start,end):
queue = deque([start])
pred = {start:None}
while len(queue)>0:
cur = queue.poplef... |
3,652 | 6ef8a174dcce633b526ce7d6fdb6ceb11089b177 | import sys
def main():
lines = [line.strip() for line in sys.stdin.readlines()]
h = lines.index("")
w = len(lines[0].split()[0])
start = 0
grids = set()
while start < len(lines):
grid = tuple(x.split()[0] for x in lines[start:start + h])
if len(grid) == h:
grids.add(grid)
start += h + 1
... |
3,653 | 47c1746c2edfe4018decd59efbacc8be89a1f49e |
from src.basepages.BreadCrumbTicketInfoBasePage import *
class BreadCrumbHomeBasePage:
def __init__(self):
""
def gotoTicketInfoBasePage(self,ticketInfoPage):
self.driver.get(ticketInfoPage)
breadCrumbTicketInfoBasePage = BreadCrumbTicketInfoBasePage()
breadCrumbTicketInfoBasePage.driver = self.driver
r... |
3,654 | c447d1fe38a4af43de39e05d46dacbe88249d427 | from quantopian.algorithm import order_optimal_portfolio
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import SimpleMovingAverage
from quantopian.pipeline.filters im... |
3,655 | dcfc6d76730ba3b33e64cc8f2c166f739bbde5ff | # This script created by Joseph Aaron Campbell - 10/2020
""" With Help from Agisoft Forum @:
https://www.agisoft.com/forum/index.php?topic=12027.msg53791#msg53791
"""
""" Set up Working Environment """
# import Metashape library module
import Metashape
# create a reference to the current project via Document... |
3,656 | e651edcbe68264e3f25180b10dc8e9d5620ecd6b | import unittest
import requests
class TestAudiobookResponse(unittest.TestCase):
def test_audiobook_can_insert(self):
""" test that audiobook can be inserted into db """
data = {
"audiotype": "Audiobook",
"metadata": {
"duration": 37477,
"ti... |
3,657 | ed65d7e0de3fc792753e34b77254bccc8cee6d66 | # coding=utf-8
# Copyright 2022 The TensorFlow Datasets Authors.
#
# 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 appl... |
3,658 | 76c1929e901fce469661a299184765875d0eb53f | 쫲𪪌𤣬㐭𤙵⃢姅幛𑄹馻돷軔ሠ𡺶ײַ𢊅𠞡鞿𭞎𦠟𦔻뜸𣦏蛫履뜟𢒰疅𗕢𨞧漷𫴫礴𬽣𨚒𠻚゚罉ꉷ🕸𡑁𩂱𑫌抿锃𫕊𦿮橖𓋊𧭠酞Ё햾𞄶𪳧蕱ꗍ𐊯𬏷먽𬻩뱩𗼾𠑧銋𝂥蘒굳뜀𬜀𮧛𡐔𭋇𭘡𬙒蕶믅𬂚𡟐剿𨸒ᄉ𮩨烘𮩽𭚱𗨦ﳇ큿턽쾘𩁻ꫲ𗨿蚀𨊍胗𗔑鼴𨵾㽡𩠌ݜ𪢭𩘼넴𤩭𬩽𢺤𫅬𧁏響𬶉喡𘨘뉵𨲊Ζ𥀐𩨇𠮢⏂𭖳𫓢𧛃𦥮単𦇭𮏨𬋪婓츏𪱔𭄿𦭺𣍵蹖🨞ޝ仂䱔讔ﭑ𨹟𐊁ﱥ𧅔𓇪뽼𗩢픛𖮌䮁ီ邾ࢠ㭨𣯇𩱵𥋭ѽ샑𭹓𫳃𧝽𥲇ᛲ𘁕粣𣑑ᒔ𣥕쯞⒋𩍥纝攂𨄷ͭ𧲵퍃氩𢐅𤵲뎋𥵘黴𤼩𬝉ⶌ𥬥𧺥浞🇴𑨲𠎆筬⌝༤쾘𤌲ы𡚎𑲙㽰𐛱𫛛�... |
3,659 | 127bf47de554dd397d18c6a70616a2a4d93cae80 | """Sophie Tan's special AI."""
from typing import Sequence, Tuple
from battleships import Player, ShotResult
from random import randint
class SophiesAI(Player):
"""Sophie Tan's Random Shot Magic."""
def ship_locations(self) -> Sequence[Tuple[int, int, int, bool]]:
return [(2, 0, 0, True)]
def d... |
3,660 | 22ffda3b2d84218af22bad7835689ec3d4959ab2 | import numpy
import yfinance as yf
import pandas as pd
import path
import math
pd.options.mode.chained_assignment = None # default='warn'
all_tickers = ['2020.OL',
'ABG.OL',
'ADE.OL',
'AFG.OL',
'AKAST.OL',
'AKER.OL',
'AKBM.OL',
... |
3,661 | 1cbc37655e28ab3082fc31baf119cb2bab96379b | def format_amount(a):
return a.replace(",","").strip().replace("%","").replace("$","")
def create_json(gdp, coords):
# ------------ Split gdp data ------------ #
line_list=gdp.split('\n')
column_list = [x.split('\t') for x in line_list if x!=""]
# ------------ Split coord data ------------ #
line_list=coords.s... |
3,662 | c8406db010a506b782030c5d3f84c319851e89d6 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('twitter', '0002_tweet'),
]
operations = [
migrations.CreateModel(
name='TwitterKeys',
fields=[
... |
3,663 | 0681ab83843187701ac72018b6078f5141bf22e0 | import sys
import os
import tensorflow as tf
import keras
from cv2 import *
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from PIL import Image
import numpy as np
import pickle
from sklearn.model_selection import train_test_split
from keras.utils import np_utils
from keras.layers ... |
3,664 | e3386b01bb0bdc7064a2e3e9f3edce8a3231721b | import json
from faker import Faker
import random
fake = Faker()
from faker.providers import date_time
fake.add_provider(date_time)
class Hour(object):
def __init__(self):
self.dayOfTheWeek = fake.day_of_week()
self.openingTime = str(random.randint(1, 12)) + 'AM'
self.closing... |
3,665 | 2d248ac1df1845bc5a2ee62a7171c1c47ca6d0ca | #!/usr/bin/env python3
import sys
sys.path.insert(0, '../../common/python/')
from primality import prime_factors
"""
phi(n) = n*sum_{p|n} (1 - 1/p)
1/phi(n) = (1/n)*sum_{p|n} p/(p - 1)
n/phi(n) = sum_{p|n} p/(p - 1)
"""
def n_over_phi(n):
top = 1
bot = 1
pfactors = prime_factors(n)
for p, count i... |
3,666 | c6d61a0159073304309cd4b1534ed5aed666bab5 | import os, glob, argparse, json, re
from collections import defaultdict
import numpy as np
import pandas as pd
from utils.CONSTANTS import output_dir, all_chromosomes, BINNED_CHRSZ, dataset_expts
def extract_chrom_num(s):
m = re.search('\d+', s)
if m is None:
return 24
else:
return int(m.group(0))
de... |
3,667 | fcfec60a2302ee0c1385add053d4371040a2aff4 | # Generated by Django 2.1.2 on 2018-10-19 22:13
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='mascota',
name='descripcion',
... |
3,668 | 355e3932c8bd9105e0c1ce9259e3b7416997523c | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from operation import *
import math
class InsertWord(Operation):
@classmethod
def getValue(cls, t, h, w, b, arg=None):
return math.log(arg["prob"]) * w[cls]
@classmethod
def getKBest(cls, t, h , args, w, b, k):
valueList = []
for ... |
3,669 | 4daf029c4bc9f0726080bd67f37b1e77c9697d1c | '''
Copyright (C) 2014 mdm
marco[dot]masciola[at]gmail
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
d... |
3,670 | 19d5e9db142237d1cb2276ccaf083ca4a96109fc | from django.conf.urls import url
from basket import views
urlpatterns = [
url(r'^$', views.view_basket, name='basket'),
url(r'^add/(?P<product_pk>\d+)$', views.add_to_basket, name='add_to_basket'),
url(r'^remove/(?P<basketitem_pk>\d+)$', views.remove_from_basket, name='remove_from_basket'),
]
|
3,671 | 71ff8e8a62a3b2731071ed7a039b51c150ebaca4 | import os ,sys
from scrapy.cmdline import execute
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
execute('scrapy crawl laptop'.split())
|
3,672 | 4ecf976a7d655efb5af427083ec1943cae6fe56d | class Restaurant():
"""A restaurant model."""
def __init__(self, restaurant_name, cuisine_type):
"""Initialize name and type."""
self.name = restaurant_name
self.type = cuisine_type
def describe_restaurant(self):
"""Prints restaurant information."""
print("The restaurant's name is " + self.name.title())... |
3,673 | d4cdc4f1995eab7f01c970b43cb0a3c5ed4a2711 | from golem import actions
from projects.golem_gui.pages import common
from projects.golem_gui.pages import api
from projects.golem_gui.pages import test_builder_code
description = 'Verify the user can edit test code and save it'
tags = ['smoke']
def setup(data):
common.access_golem(data.env.url, data.env.admi... |
3,674 | 777c08876a2de803fc95de937d9e921044545ef8 | from bs4 import BeautifulSoup
import requests
res = requests.get('http://quotes.toscrape.com/')
#print(res.content)
#proper ordered printing
#print(res.text)
#lxml -> parser library
soup = BeautifulSoup(res.text , 'lxml')
#print(soup)
quote = soup.find_all('div',{'class' : 'quote'})
with open('Quotes.txt... |
3,675 | 851162e6c40a9f4f82a983a84fd0b4d6a6a57412 |
class Type(object):
"""Type of values."""
def __init__(self, jtype):
self.jtype = jtype
def __repr__(self):
return self.jtype.toString()
def __str__(self):
return self.jtype.toPrettyString(False, False)
|
3,676 | f1475d651c3b52611657a9767ad62796b55d8711 | # obtain the dataset
import pandas as pd
titanic = pd.read_csv('http://biostat.mc.vanderbilt.edu/wiki/pub/Main/DataSets/titanic.txt')
#titanic.info()
print(titanic.head())
# preprocessing
x = titanic.drop(['row.names', 'name', 'survived'], axis=1)
y = titanic['survived']
x['age'].fillna(x['age'].mean(),... |
3,677 | 19bb3cd0c7862f39a78479d9a9703ebef198fc73 | import math
from Config import defaults as df
from Utils.controls import sigmoid_decay
def f1(phi, phi_o, d):
"""sinusoidally growing function between (phi_o-d) to phi_o"""
return 1 - sigmoid_decay(phi, phi_o, d)
def f2(phi, sigma):
"""normal distribution"""
return math.exp(-phi ** 2 / sigma ** 2)
... |
3,678 | e3a984294cad5830358df50fa00111017cbe226d | from django.urls import path
from .views import MainView
app_name = "bio"
# app_name will help us do a reverse look-up latter.
urlpatterns = [
path('get_mtx_data', MainView.as_view()),
]
|
3,679 | ebb4cf1ec2baa7bd0d29e3ae88b16e65cf76a88a | from flask import Flask, render_template, url_for, request, redirect, session, flash
import os, json
from usuarios import crearUsuario, comprobarUsuario
from busqueda import filtrado
from compra import procesarCompra, Dinero
app = Flask(__name__)
catalogo_data = json.loads(open(os.path.join(app.root_path,'json/catalo... |
3,680 | 85974e48c7eafdf39379559820ed7f0bdc07fb7a | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 12 16:38:15 2013
@author: a92549
Fixes lack of / between tzvp and tzvpfit
"""
import sys
def main(argv):
for com in argv:
with open(com, 'rb') as f:
txt = f.read()
if 'tzvp tzvpfit' in txt:
parts = txt.spl... |
3,681 | 991fa5f9c83a1821e62f7baacbc56a4d31982312 | a, b = map(int, input().split())
def mult(a, b):
if a > 9 or b > 9 or a < 1 or b < 1:
print(-1)
else:
print(a * b)
mult(a,b) |
3,682 | 193d48237b4b1e406eb565943cf01f0423449fca | # hw.shin@konantech.com
#leekiljae@ogqcorp.com |
3,683 | 1154fd3883dc8856e24127d56ce6a983308dc1aa | # -*- coding: utf-8 -*-
__author__ = 'wxy'
class ListProcess(object):
def __init__(self, rsp, nickname):
self.rsp = rsp
self.nickname = nickname
def get_friend_uin(self):
try:
for list in self.rsp['result']['info']:
if list['nick'] == self.nickname:
... |
3,684 | 3983f8dfb9c7b7e664af05857a0f6fe380154424 | from django import forms
from . import models
class PhotoForm(forms.Form):
image = forms.ImageField()
|
3,685 | d5d61b23dc14ffdfe7fe6f983164916863928eaf | from django.apps import AppConfig
class AttendaceConfig(AppConfig):
name = 'attendace'
|
3,686 | 5b7c04f23fb674191639e95dff8c530933379d67 | """
Вам дана последовательность строк.
В каждой строке замените все вхождения нескольких одинаковых букв на одну букву.
Буквой считается символ из группы \w.
Sample Input:
attraction
buzzzz
Sample Output:
atraction
buz
"""
from sys import stdin
import re
for word in stdin:
lst_in = word
match = re.finditer(r... |
3,687 | a2292bc9cee57c5d4a7d36c66510ce4b4f3e20da | """
Simulator contains the tools needed to set up a multilayer antireflection
coating simulation.
Based on transfer matrix method outlined in Hou, H.S. 1974.
"""
# Author: Andrew Nadolski (with lots of help from previous work by Colin Merkel,
# Steve Byrnes, and Aritoki Suzuki)
# Filename: simulator.py
impo... |
3,688 | a0dbb374f803cb05a35f823f54ef5f14eaf328b2 | # coding: utf-8
"""
login.py
~~~~~~~~
木犀官网登陆API
"""
from flask import jsonify, request
from . import api
from muxiwebsite.models import User
from muxiwebsite import db
@api.route('/login/', methods=['POST'])
def login():
email = request.get_json().get("email")
pwd = request.get_json().get("pass... |
3,689 | 3fa1736fd87448ec0da4649153521d0aba048ccf | from rest_framework import serializers
from dailytasks.models import Tasks
class TasksSerializer(serializers.ModelSerializer):
user = serializers.ReadOnlyField(source='user.username')
class Meta:
model = Tasks
fields = ['id','created','title','description','status','user']
|
3,690 | c036e6a0a9f06b08ee3eb43655dd833b46fd1e76 |
from .factories import * |
3,691 | 4892d4f364b03b53b1ad6f4c2177bbe2898edbda | #!/usr/bin/env python
import os
import sys
import numpy as np
from sklearn.metrics import roc_curve, auc
def confusion_matrix(Or, Tr, thres):
tpos = np.sum((Or >= thres) * (Tr == 1))
tneg = np.sum((Or < thres) * (Tr == 0))
fpos = np.sum((Or >= thres) * (Tr == 0))
fneg = np.sum((Or < thres) * (Tr == 1... |
3,692 | 51cb750082ce93b6d14fe3aa40711836d493129c | """
Proyecto SA^3
Autor: Mario Lopez
Luis Aviles
Joaquin V
Fecha: Octubre del 2012
versión: 1
"""
#Manejo de temlates en el HTML
import jinja2
from jinja2 import Environment, PackageLoader
import os
import cgi
import datetime
import urllib
# for hashing
import hashlib... |
3,693 | 5cd9d4fe9889c4d53b50d86fa78ae84d0c242536 | import tensorflow as tf
import random
from tqdm import tqdm
import spacy
import ujson as json
from collections import Counter
import numpy as np
import os.path
nlp = spacy.blank("en")
def word_tokenize(sent):
doc = nlp(sent)
return [token.text for token in doc]
def convert_idx(text, tokens):
current = ... |
3,694 | f10e20d5c409930d697c36d1897ebcb648511e27 | from typing import List
from fastapi import Depends, APIRouter
from sqlalchemy.orm import Session
from attendance.database import get_db
from attendance import schemas
from attendance.models import User
from attendance import crud
from attendance.dependency import get_current_user
router = APIRouter()
#BASE_SALARY
#... |
3,695 | e93d5461a2604d3b8015489397c68e16d1cb222e | from manim import *
class SlidingDoorIllustration(Scene):
def construct(self):
waiting_room = Rectangle(color=BLUE, stroke_width=8)
waiting_room.shift(LEFT + DOWN)
workspace = Rectangle(color=BLUE, stroke_width=8)
workspace.next_to(waiting_room, RIGHT + UP, buff=0)
workspac... |
3,696 | cbad5d6f381e788a2f064aac0a5d468f40b39c93 | import os, subprocess
os.environ['FLASK_APP'] = "app/app.py"
os.environ['FLASK_DEBUG'] = "1"
# for LSTM instead: https://storage.googleapis.com/jacobdanovitch/twtc/lstm.tar.gz
# Will have to change app.py to accept only attention_weights
subprocess.call('./serve_model.sh')
subprocess.call(['flask', 'run'])
|
3,697 | 51cdb41836415c08609ee6a6bcc3adbaf2533da4 | """
USERS MODEL
"""
from www import app
import mongoengine
import datetime
class User(mongoengine.Document):
username = mongoengine.StringField(required=True)
password = mongoengine.StringField(required=True)
email = mongoengine.StringField(required=True)
active_hash = mongoengine.StringField(re... |
3,698 | 3d1e6be71f92910cdc9eb2bf60ea7f8f1187f706 | '''
This script will do auto-check in/out for ZMM100 fingerprint access control
device by ZKSoftware.
At my office, the manager uses an application to load data from the
fingerprint device. After he loads data, log in device's database is cleared.
So in my case, I write this script to automate checking in/out everyday... |
3,699 | 10fda09f47c292cb3dc901f42d38ead7757460f5 | import json
import requests
import boto3
import uuid
import time
profile_name = 'mine'
region = 'us-west-2'
session = boto3.Session(profile_name=profile_name)
api = session.client('apigateway', region_name=region)
cf = session.client('cloudformation', region_name=region)
def get_key(name_of_key):
print('Discover... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.