index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
991,500 | eb8eeae4e4e15b6ec776099838ffde8c1859859d | """Helper functions."""
from typing import Dict, Callable, List, Any
import pandas as pd
import numpy as np
NON_METRIC_COLS = ["home_team", "away_team", "year", "round_number", "ml_model"]
def _replace_metric_col_names(team_type: str) -> Callable:
return lambda col: col if col in NON_METRIC_COLS else team_type... |
991,501 | 5cd9613e656a1dbea607a5e7f5aa10bdd4cc218d | """
* Assignment: Exception Raise Many
* Required: yes
* Complexity: easy
* Lines of code: 6 lines
* Time: 5 min
English:
1. Validate value passed to a `result` function
2. If `value` is:
a. other type than `int` or `float` raise `TypeError`
a. less than zero, raise `ValueError`
a. belo... |
991,502 | 5d70afaf4bbb96853f04462d57ecdff35d6891e1 | #! /usr/bin/env python
def swap(l,i):
tmp = l[l[i]-1]
l[l[i]-1] = l[i]
l[i]=tmp
def f(l):
if not l:
return 1
length = len(l)
for i in range(len(l)):
while l[i] > 0 and l[i]<=length:
if l[i] != i+1:
swap(l, i)
else:
break
... |
991,503 | 4ba37a0336216414c10c81b2887dcfbbf5448997 | # -*- coding: utf-8 -*-
from typing import List
class Solution:
def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
result = []
text_list = text.split(' ')
for i in range(0, len(text_list)-2):
if text_list[i] == first and text_list[i+1] == second:
... |
991,504 | 3dbf9417099b20fae0331a41dbb3aeab6daabafe | #I'm following this tutorial by Adrian Rosenbrock
#https://www.pyimagesearch.com/2018/02/26/face-detection-with-opencv-and-deep-learning/?__s=k1tfi5xcxncrpsppkeop
#We are going to perform a fast, accurate face detection with open CV using a
#pre trained deep learning face detector model shipped with the library.
#In ... |
991,505 | 822e6df5190010fedccedccd5f8439181f24b8f7 | from flask import Flask
import os
import mysql.connector
app = Flask(__name__)
@app.route('/')
def hello_world():
cnx = mysql.connector.connect(user='root', password='abcdefg', host='mysql-dev') #been defined in docker-compose.yml
cursor = cnx.cursor()
databases = ("show databases")
cursor.execute(da... |
991,506 | ecd3cd38cffd80cc93210a421126ae9b9a7c583d | soma = 0
cont = 0
for c in range(1, 500, 2):
if c % 3 == 0:
soma += c
cont += 1
print(f'Foram encontrados {cont} números ímpares e divisíveis por 3 entre 1 e 500 e seu somatório é {soma}')
|
991,507 | e0753fee08e51580ead3bd619d0ef8c7d131e4a7 | import numpy as np
from ase import units
def cosine_squared_window(n_points):
points = np.arange(n_points)
window = np.cos(np.pi * points / (n_points - 1) / 2) ** 2
return window
def _single_fft_autocorrelation(data, normalize=False):
if normalize:
data = (data - np.mean(data)) / np.std(data... |
991,508 | c2e0728562a55a3d09ed748f6039b39ef081ca70 | import itertools
import math
import os
import loompy
import h5py
import copy
import umap
import numpy as np
import pandas as pd
from collections import Counter
import seaborn as sns; sns.set(style="white", color_codes=True)
import matplotlib
import matplotlib.colors as mcol
from scipy.stats import spearmanr
from scip... |
991,509 | fb0bbede69a8fb5c63784616116a5bd7a73b494b | #!/usr/bin/env python
# sys module
import time
import os
import sys
# third parties module
import torch
from torch import nn
from torch.nn import functional as F
from torch import optim
from torch.utils.data import SubsetRandomSampler
import torchvision
import torchvision.transforms as transforms
import matplotlib.p... |
991,510 | 0f7fd390ce2b2d3226d4580950037ffff8e84733 | import time
from sqlalchemy.orm import aliased
from humaniki_backend.utils import is_property_exclusively_citizenship, transform_ordered_aggregations_with_year_fns, \
transform_ordered_aggregations_with_proj_internal_codes, get_transform_ordered_aggregation_qid_match
from humaniki_schema import utils
from humanik... |
991,511 | 3a15d3d302c590a8ca8ffc759eaceff0ed1aa583 | # -*- coding: utf-8 -*-
# BSD 3-Clause License
#
# Copyright (c) 2019, Elasticsearch BV
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the ... |
991,512 | ac1dc5a38cbed7e8bb87cc880fc0b0fc908e0195 | def cond():
a=6
if a<0:
print("a is negative")
else:
print("a s positive")
cond() |
991,513 | 172752c696de42882926b773173f65702c367023 | import os
import numpy as np
import unittest
import yaml
from greengraph import *
from nose.tools import *
from mock import Mock, patch
def test_geolocate():
with open(os.path.join(os.path.dirname(__file__),'fixtures','mapcoord.yaml')) as fixtures_file:
fixtures = yaml.load(fixtures_file)
for fixt in fi... |
991,514 | d02a93859afc8acaddbfda5b7362ea689113d985 | import pandas as pd
import matplotlib.pyplot as plt
def compute_score_variation(games, color, variation):
games = games[games["variation"]==variation]
if color == "white":
score = (len(games[games["resultat"]=="1-0"]) + 0.5*len(games[games["resultat"]=="1/2-1/2"]))/len(games)
else:
score = ... |
991,515 | 1ca1dec3de79de9bf0f65344fca7b93d2e1c82b8 | from rest_framework import serializers
from comment.models import Comment
from utils.common_utils import get_model_fields
class CommentSerializer(serializers.ModelSerializer):
uid = serializers.IntegerField()
sid = serializers.IntegerField()
cid = serializers.IntegerField()
content = serializers.Char... |
991,516 | 4de779e2159d23de8a98a2ff2a7865a2f9683b11 | import argparse
import os
import re
#filename & open
name = "data/WhatsApp.txt"
fole = open(name, 'r')
# Create empty dictionaries
kady = {}
tommy = {}
Dict = {}
#regex for word
rogex = re.compile('[^a-zA-Z]')
s = raw_input("Lets begin? -- Please press enter")
#read first line
line = fole.readli... |
991,517 | 2559bb50695ec2f39d6fb3e5c66c62b5526683e0 |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
import math
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from sklearn.impute import SimpleImputer
fro... |
991,518 | fb9fa98ef1d36a8c8124ed4fa2a4b66642468e69 | # Produce a plot of the last day of the year at a given temperature
import mx.DateTime
import iemdb
COOP = iemdb.connect('coop', bypass=True)
ccursor = COOP.cursor()
# get climatology
ccursor.execute("""SELECT valid, high from ncdc_climate71 where station = 'ia0200'
ORDER by valid ASC""")
climate = []
cdoy = []
f... |
991,519 | 1e7903d063b68954fef092d7a96f99b59ca00fc7 | import png
import math
import sys
import cmd
from collections import namedtuple
from Pathspec import Pathspec
Pixel = namedtuple('Pixel', 'x y r g b a')
def getPixel(x, y):
xAddr = x * 4
return Pixel(x, y, *pic[y][xAddr:xAddr+4])
def savePixel(p):
xAddr = p.x * 4
pic[p.y][xAddr+0] = p.r
pic[p.y][... |
991,520 | eb441bded980d8d5b60ad1eb9aae1c1da830aa92 | """
This module contains all unit tests for the calculator.
"""
from unittest import TestCase
from unittest.mock import MagicMock
from calculator.adder import Adder
from calculator.subtracter import Subtracter
from calculator.multiplier import Multiplier
from calculator.divider import Divider
from calculator.calculat... |
991,521 | 005e749e116be2658af958c5e4a65c16c850ba69 | from lib.from_scratch.indexer import read_term_counts, read_index
from argparse import ArgumentParser
parser = ArgumentParser(description='Performs queries from a query file using a Vector Space retrieval model.')
parser.add_argument("index_path", help="the path to read the index from")
parser.add_argument("term_coun... |
991,522 | a58a7e2c05853c752021a2ceba984e8510ca6e95 | import torch
class TestingModel:
'''
This class tests our cnn model based on the trained model and the prepared test dataset
'''
def __init__(self, cnn_model, test_dataset_loader, test_dataset):
self.cnn_model = cnn_model
self.test_dataset_loader = test_dataset_loader
self.test_... |
991,523 | 0c4b4ddae0e6839277bf54cc6fe020bb7f4ea7d4 | import socket
from socket import AF_INET, SOCK_STREAM
s = socket.socket(family=AF_INET,type= SOCK_STREAM, proto=0)
print("socket created:{}".format(s)) |
991,524 | 62b0916c660db089e09492540508500a5bef20cc | import pickle
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
import cv2
import glob
import time
from sklearn.svm import LinearSVC
from sklearn.preprocessing import StandardScaler
from skimage.feature import hog
# NOTE: the next import is only valid for scikit-learn version <= 0.17
#... |
991,525 | 20d96113649833c0076b0ef9ce72deacdf6e4408 | """
For two given composers find operas (one of composers is the author)
at which premiere both could have been together (i.e. they both had to be alive).
Just a theoretical possibility of presence is considered
"""
from datetime import datetime
composers = {
"beethoven": ("Ludwig van Beethoven", "17 December 17... |
991,526 | 18f230df6948b988250a3d41057cff4b7e4833d0 | # This creates a custom user that starts out as identical to the default
# user
#
# The sequence is:
#
# (note, we can run the Django server before this process is complete, we
# just mustn't create or run migrations)
#
# 1. Create the Django Project
# 2. Create a `users` app
# 3. Decide whether to subclass `AbstractU... |
991,527 | ba96af48f266c7b5810de32aa6346ec5837b6503 | # coding=UTF_8
#
# problem_056.py
# ProjectEuler
#
# This file was created by Jens Kwasniok on 15.08.16.
# Copyright (c) 2016 Jens Kwasniok. All rights reserved.
#
from problem_000 import *
class Problem_056(Problem):
def __init__(self):
self.problem_nr = 56
self.input_format = (InputTy... |
991,528 | 8c4ec96992e534f5618657ffb228fa0998efd9b1 |
from bob import make_bob, otp_encrypt
import random
import bob
FILTERS="x+"
DIAGONAL="↗↖"
RECTILINEAR="↑→"
ALL=DIAGONAL+RECTILINEAR
def getKey(photons, disposalInstructions, messageLen):
# this function takes in a list of photons and a list of boolean values for bobs correct filters
# returns a key of those ... |
991,529 | cdc9d81c2a7f21bc9a839f96f2c22eb63258ad39 | """
main.py
"""
from parser import get_from_url
def main():
views, likes, dislikes = get_from_url("https://www.youtube.com/watch?v=yUtB4Zg_ioc")
print(views, likes, dislikes)
if __name__ == "__main__":
main() |
991,530 | cdf70dc787daeb69f5cc36d59c72ca8a5d9860ba | number = int(input("Which number do you want\n"),)
if(number % 2 == 0):
print("This is Even Number")
else:
print("This is Odd Number")
|
991,531 | 286e5eb4ba64a63efad6b73da57f9ef8d923c482 | def insertionSort(arr):
for i in range(1, len(arr)):
temp = arr[i]
while arr[i-1] > temp and i > 0:
arr[i], arr[i-1] = arr[i-1], arr[i]
i = i-1
return arr
print(insertionSort([6, 8, 1, 4, 5, 3, 7, 2]))
|
991,532 | 45e887f3b219be8209d25a2f8991f6745a8b8f63 | with open("input.txt", "r") as f:
test_input = "2 3 0 3 10 11 12 1 1 0 1 99 2 1 1 2"
data = [int(n) for n in f.read().split(" ")]
class Node(object):
def __init__(self, no_subnodes, no_metadata):
# number of nodes and metadata
# the nodes and metadata will be added externally
... |
991,533 | 393a5586ddd5b5172d8a946a38e62f230507c477 | #include <stdio.h>
#include <stdlib.h>
int largest,element,a[1300010];
int cmp(const void *a,const void *b)
{
return *(int *)a - *(int *)b;
}
int median(int a[],int left,int right)//求中位数
{
return a[(left + right)/2];
}
void sqlit(int a[],int middle,int left,int right,int *ll,int *rr)//计算中位数个数最左端和最右端
{
int... |
991,534 | 3e2c988f2061e01c2554f0b74e540a36afe1d838 | # Kekan Nikhilkumar
# 1001-563-734
# 2018-09-09
# Assignment-01-02
import numpy as np
# This module calculates the activation function
def calculate_activation_function(weight,bias,input_array,type='Sigmoid'):
net_value = weight * input_array + bias
if type == 'Sigmoid':
activation = 1.0 / (1 + np.exp(-net_value))
... |
991,535 | e606c3567512bb3f25fd1daf87736e3c3d6f8d3e | from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class User(AbstractUser):
profile=models.ImageField()
class Post(models.Model):
user=models.ForeignKey(User, on_delete=models.CASCADE)
image=models.ImageField()
caption=models.TextField()
c... |
991,536 | 979e54665fa79fc45e6ff9ef371470f4eceacb73 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import wget
import os
from tensorflow.examples.tutorials.mnist import input_data
def view_image(obs):
square_obs = np.reshape(obs,(28,28))
plt.imshow(square_obs, cmap="gray")
plt.show()
def plot_data(df, y_lst, filename):
for y_v... |
991,537 | d7621ef37a6ef4e8bf22bf19dfea438355ff3e12 | # -*- coding: utf-8 -*-
from odoo import fields, models, api
class Partner(models.Model):
_inherit = "res.partner"
payment_days_ids = fields.Many2many('payment.days', 'res_partner_paymnet_days_rel', 'res_partner_id', 'payment_days_id', string="Payment Days")
collection_executive_id = fields.Many2one("res.users", s... |
991,538 | ee43196b2a2ac85f7dd5d121d1f65f049af19b7d |
from maineed.event import *
print(running)
print(ps_count)
print(psi)
show_init = True
end_init = False
fail_init = False
timer = False
timer2 = 0
play_sound = True
byby = False
gogo = False
gogoc = 0
gogob = 1
while running:
if show_init:
background_sound.play()
byby = drow_init()
show_in... |
991,539 | 3fe2041ea58d3d09891a877711857f81e730f510 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/8/11 7:23 下午
# @Author : liujiatian
# @File : 3.组合总和.py
# 给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。
#
# candidates 中的数字可以无限制重复被选取。
#
# 说明:
#
#
# 所有数字(包括 target)都是正整数。
# 解集不能包含重复的组合。
#
#
# 示例 1:
#
# 输入:candidates... |
991,540 | b4ebd2b371e17f1a6301fe2dc7e2bbfa7b73e66d | #!/usr/bin/env python
import os
import numpy as np
import csv
from rulo_utils.csvcreater import csvcreater
def numpywriter(filepath , array=0):
file = open(filepath, 'ab')
np.savetxt(file,array )
file.close()
|
991,541 | 39b4d103460290421cf07a869ff458e138e0f1cc | from django.shortcuts import render
from django.core.paginator import Paginator
from .models import Post, Category
# Create your views here.
def blog(request):
posts = Post.objects.all()
paginator = Paginator(posts, 4)
page = request.GET.get('page')
posts = paginator.get_page(page)
return render... |
991,542 | c680154999043b1ed833edbf855643fe92278969 | #!/usr/bin/env python
#The MIT License (MIT)
#Copyright (c) 2016 Massimiliano Patacchiola
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
#MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ... |
991,543 | d884d4c194da90145a475e095b8d4054ae303d00 | import math
d = float(input('Please set d:'))
n = math.floor(10.0/abs(d)) + 1
print('A({0},R_0) = {1}'.format(d,n*n))
|
991,544 | 8d9691167bdf8ab87ade14a3d0dbcbbc43233624 | # 使用{}创建字典
d = {}
d = {"name": "youhuan"}
print(d)
# dict创建一个序列
a = dict(name="youhuan")
print(a)
# len获取字典键值对的个数
# in,not in 检查字典中是否包含指定的键
# 获取字典中的值
print(d.get("name2", "moren"))
print(d["name"])
#修改字典中的值
d["name"] = "miaomiao"
print(d)
#setdefault()向字典中添加值,如果不存在则添加,如果存在就不做任何操作
#update()用于合并两个字典,如果有重复的key,新的会替换旧... |
991,545 | 292df7a38a99746cafc4f1e9170908bcfccc2cf9 | import dash
app = dash.Dash(__name__, title="Rubicon")
|
991,546 | bf7b79d7b2d881069a9ded8107b765ec09643d9a | maxRep = 0
maxNumber = 0
for num in range(2,1000+1):
# Numbers that are mod(5) or mod(2) will never repeat
if num % 2 == 0 or num % 5 == 0:
continue
# Emulate long divison
else:
mods = []
reps = 0 # Length
div = 1 # Divisor
while div < num:
div *= 10... |
991,547 | bd2fd8148fd2e3cb3392761edd7f29856862f67d | import torch
import numpy as np
from scipy.misc import imread, imresize
from torchvision.models import resnet101
import torch
import torch.nn.functional as F
import torch.nn as nn
def load_resnet_image_encoder(model_stage=2):
""" Load the appropriate parts of ResNet-101 for feature extraction.
Parameters
... |
991,548 | 848f6ff3a6c40cc9b2006f7b718bfaa272827ca4 | #!/usr/bin/python3
# use YAML
# use YAML::Tiny
# use Data::Dumper
# use Hash::Merge::Simple qw/ merge /
import argparse
import os
import sys
import logging
import logging.config
import pprint
import yaml
class Config:
def __init__(self,
config_file='/usr/local/cam/conf/config.yml',
... |
991,549 | 83acd7bf8c3a9ba7677e9955c32d1d50dbe2bfe5 | import argparse
import time
import os
import json
import random
import numpy as np
from generate_map import *
from utils.general_functions import *
from utils.graphs import *
def str2bool(v):
if isinstance(v, bool):
return v
if v.lower() in ('yes', 'true', 't', 'y', '1'):
return True
elif v... |
991,550 | 544d8a40f76ef9876402b21cdcae4d01e962f2c8 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Student(models.Model): # Creating a Student table in django database to see in Django Administration
name = models.CharField(max_length=20, null=True)
age = models.CharField(max_len... |
991,551 | 5828a73ec9ec680a2c5efef1b4b0e108feff0a4e | '''
Created on 2018年9月15日
@author: xingli
'''
import os,sys
sys.path.append('/home/pi/Desktop/xing/iot-device/apps')
from time import sleep
from labs.module03 import TempSensorAdaptor
from labs.module04 import I2CSenseHatAdaptor
sysPerfAdaptor = TempSensorAdaptor.TempSensorAdaptor()
i2cSenseHat = I2CSenseHa... |
991,552 | d2ce6b1e5be9dce5b17750c9d24a2b98746ae3c1 | from collections import namedtuple
import torch
import cupy
from string import Template
from ...backend.torch_skcuda_backend import TorchSkcudaBackend
from .torch_backend import TorchBackend2D
# As of v8, cupy.util has been renamed cupy._util.
if hasattr(cupy, '_util'):
memoize = cupy._util.memoize
else:
me... |
991,553 | 30a22e1935fbd2730bceabadf44756f260280c6e | import argparse
import random
import sys
import time
import pygame
import comp
import grid
import player
import ship
# TODO later
# interactive ship placement
# add heatmap option
# normalize wording: ships sunk or sunk ships
def main():
parser = argparse.ArgumentParser()
parser.add_argument('filename', hel... |
991,554 | 01ea08279191778e1a9fda3d6ed5011501396d13 | import pandas as pd
import itertools
import numpy as np
data = pd.read_csv("dataset.csv", ",")
empty_string = "empty"
unique_outlook = data['Outlook'].unique()
unique_temperature = data['Temperature'].unique()
unique_humidity = data['Humidity'].unique()
unique_windy = data['Windy'].unique()
def calculate_support... |
991,555 | ae2802be45a7831eb4121c73c64a39a7b0b4a996 | import scipy.io
import numpy as np
import matplotlib.pyplot as plt
from sklearn import svm, metrics
# csv writer
from util import *
# hyperparameters
GAMMA = 0.000001
# kernel options: linear, poly, rbf, sigmoid, precomputed
KERNEL = 'poly'
# degree of the polynomial kernal function
DEGREE = 2
# tolerance
TOL = 1e-9... |
991,556 | 5489bc16648055180580f02ced8d1216263b9cdb | # pylint: disable=redefined-builtin
"""Test related method and functionality of Context."""
import pytest
import responses
from decanter.core import Context
from decanter.core.extra import CoreStatus
def test_no_context(globals, client):
"""Test calling coerx_api when no context created.
CoreClient will cal... |
991,557 | dccfad4074f50f0a1d14f1260d6ac7c75ad3802a | # -*- coding: utf-8 -*-
"""This file contains the text format specific event object classes."""
from plaso.events import time_events
from plaso.lib import eventdata
class TextEvent(time_events.TimestampEvent):
"""Convenience class for a text format-based event."""
DATA_TYPE = 'text:entry'
def __init__(self, ... |
991,558 | eda7832cd1f91b27a038efb1474acaacb6a03fcf | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
"""
"""
class Solution:
# @param matrix, a list of lists of integers
# @param target, an integer
# @return a boolean
def searchMatrix(self, matrix, target):
if not matrix:
return False
row_idx = self.search_row(matrix... |
991,559 | 18908fbf9b58aa362dc3ca76aaf871f49be3d2aa |
from keras import layers
from keras import models
from keras.utils import plot_model
from keras.optimizers import SGD
import numpy as np
from STFT import istft
import scipy.io.wavfile
import matplotlib.pyplot as plt
import os
from DataGeneration import dataGenBig
from Others import formatData
from GenerateModels im... |
991,560 | 3a1ae7ab514d4f038fb9546b6e2ae690f34e6f2c | # -*- coding: utf-8 -*-
'''
@Author : Arron
@email :hou.zg@foxmail.com
@software: python
@File : 平均值.py
@Time : 2018/2/12 22:16
'''
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
# x = np.arange(1, 10, 1)
xt = tf.constant([[1., 2.],
[3., 4.]])
sess = tf.Session()
... |
991,561 | 6221b8fa1cad4a08078aad9843ff084a462e913d |
import faulthandler; faulthandler.enable()
import time
from tqdm import tqdm
import time
import json
from os import environ
from elasticsearch import Elasticsearch, helpers
from elasticsearch_dsl import Search
ES_INDEX_FULL_TEXT = "nycdocs-use"
FIRST = False
ES_INDEX_CHUNK = "nycdocs-use-chunk128"
vector_dims = 512
... |
991,562 | 0436e56cfdf432ec1e6b9c00fa51713fd8f43c3e |
#calss header
class _STREAK():
def __init__(self,):
self.name = "STREAK"
self.definitions = [u'a long, thin mark that is easily noticed because it is very different from the area surrounding it: ', u'an often unpleasant characteristic that is very different from other characteristics: ', u'a short period of goo... |
991,563 | 98f1f7a2a4ad95daabd55b2f2c36196a05056a3c | import os, sys
import warnings
import numpy as np
class OneSigma:
def __init__(self, args, model_base):
super().__init__()
self.args = args
self.base = model_base
self.reset()
def reset(self):
self.n_err = 0
self.n_obs = 0
self.initialized = False
... |
991,564 | 4a4d2149cd9577bd1064a12a514affcc8a8f8c81 | # -*- coding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
SPONSOR_LEVELS = (
('diamond', u'DIAMANTE'),
('platinum', u'PLATINO'),
('gold', u'ORO'),
('silver', u'PLATA'),
('bronce', u'BRONCE'),
)
class Sponsor(models.Model):
name = models.CharField(max_le... |
991,565 | c7e3e73c2c5b7c8574269eb2411acf867e4e7497 | #!/usr/bin/env python3.6
import argparse
import asyncio
import time
import sys
import string
import json
import random
import multiprocessing as mp
import aiohttp
async def post_message(session, url, message):
async with session.post(url, json={'message': message}) as resp:
assert resp.status == 201 or ... |
991,566 | 26ab918d8cdbfe63c6e6430670f413d686f06586 | import numpy as np
from numpy import pi
from numpy.testing import assert_allclose
import brownian_ot
from brownian_ot.utils import rot_x, rot_y, rot_z, sphere_D, dimer_D
from brownian_ot.force_utils import calc_fx, calc_fy, calc_fz, calc_tx, calc_ty
def test_rotation_matrices():
invert_yz = np.diag([1, -1, -1])
... |
991,567 | 4e1a943dc0e3c2cfbec842510e7c30143e574425 | age = input("Are you a cigarette addict older than 75 years old? (please answer yes or no) :")
if age == "yes" :
age = True
elif age == "no":
age = False
chronic = input("Do you have a severe chronic disease? (please answer yes or no) :")
if chronic == "yes" :
chronic = True
elif chronic == "no":
chron... |
991,568 | d0eab604d32132732960eb56124cbe5bd06c4ecb | with open('header.md') as f:
readme = f.read()
with open('AUTHORS.md') as f:
readme += f.read()
with open('footer.md') as f:
readme += f.read()
with open('README.md', 'w') as f:
f.write(readme)
|
991,569 | 60e854a50e91584e9a5a430810330944aa818f92 | import torch
from torch.autograd import Variable
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from collections import namedtuple, deque
import random
import numpy as np
import matplotlib.pyplot as plt
from copy import deepcopy
from torch.optim import Adam
#-------hyperParameter---... |
991,570 | 480f501fe2cd6e2a61b1f498b6732f3b24fa23e0 | #Create your own implementation of a built-in function enumerate, named `with_index`,
# which takes two parameters: `iterable` and `start`, default is 0.
# Tips: see the documentation for the enumerate function
iterable = ['one', 'two', 'three', 'four', 'five']
def with_index(iterable, start=1):
n = start
for ... |
991,571 | ef227424fe7b9bde8b8c3bb17015ac08b1ad1f97 | #!/usr/bin/python
# 2.12 Lab 3 tf examples
# Peter Yu Sept 2016
import rospy
import tf
import numpy as np
import threading
import serial
import tf.transformations as tfm
from helper import transformPose, pubFrame, cross2d, lookupTransform, pose2poselist, poselist2pose, invPoselist
def main():
rospy.init_node('a... |
991,572 | ec842e2987a30a22fb0b71ee22a45dd9effaa317 | # encoding=utf-8
import logging
import os
import sys
import multiprocessing
from gensim.models import Word2Vec
from gensim.models.word2vec import LineSentence
import fire
def main(**kwargs):
for k, v in kwargs.items():
print(k)
print(v)
if k == 'inSegFile':
inSegFile = v
... |
991,573 | d0c1376ab6d6fe9de17f628ab013016e66a29c0d | from __future__ import division
import numpy as np
import tensorflow as tf
np.random.seed(1234)
class PolicyAdaptive(object):
"""docstring for PolicyAdaptive"""
def __init__(self, step_size, method):
self.lambda_ = step_size
self.method = method
self.alpha_ = 0.9
self.beta1_ = 0.9
self.beta2_ = 0.5
self.... |
991,574 | 7fbc27be5a79644de05bf5eab98e09adb0f4b95a | import pandas as pd
from datetime import datetime
data = pd.read_csv('Data/DSNY_Monthly_Tonnage_Data.csv')
# Create accurate borocd numbers
district = []
for i in data['COMMUNITYDISTRICT']:
if len(str(i)) == 1:
i = "0" + str(i)
district.append(i)
else:
district.append(i)
data['COMMUNI... |
991,575 | a6341e9c7295b1d51b51efb4e3baf42ca6878ffa | import torch
import torch.nn as nn
import torch.nn.functional as F
BN_EPS = 1e-4
class ConvBnRelu2d(nn.Module):
def __init__(self, in_channels, out_channels, kernel_size=(3, 3), padding=1):
super(ConvBnRelu2d, self).__init__()
self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_si... |
991,576 | 9aa0b8b21d5e85bd22620efe5ce0cf53ddbb1a10 | from flask import Blueprint
from flask_restful import Api
public_api_bp = Blueprint('public_api', __name__)
public_api = Api(public_api_bp)
from . import public_main
from . import public_verify
from .. import errors
|
991,577 | 8944d32bf2f488db526606838e8fd0fa9646f210 | # -*- coding: utf-8 -*-
from odoo import models, fields, api
class students(models.Model):
_name = 'ai.table'
name = fields.Char()
value = fields.Integer()
value2 = fields.Float(compute="_value_pc", store=True)
description = fields.Text()
value3 = fields.Text()
group_id = fields.Many2one(... |
991,578 | 2fcc88e4bbf4249f3f763341894d916a450b052e | ## busquedas
lista= [19,5,9,5,33,87,12]
suma= 0
for i in range(0, 7):
if lista[i] >= 10:
print(lista[i])
suma= suma + lista[i]
print("Total: ", suma)
val= int(input("V: "))
pos= -1
for i in range(0, 7):
if lista[i] == val:
pos= i
print("Posicion : ", pos)
pos= 0
for i in range(0, ... |
991,579 | 99044ff123d4ce9c0b78760c1eaac1f14a8feec3 | # -*- coding: utf-8 -*-
"""
Created Sat Mar 17 10:50:37 2018
@author: DeepLearning
"""
import sys
import os
import mxnet as mx
import numpy as np
import pandas as pd
import data
from scipy.spatial.distance import cdist
from sklearn.cluster import KMeans
import model
from autoencoder import AutoEncoderModel
from solve... |
991,580 | f244a700b08413e131a1577fcbee858d56867759 | import math
def isPrime(num):
isPrime = True
if (num % 2) == 0:
return False
for x in range (2,num):
if(num % x) == 0:
isPrime = False
break
return isPrime
def runPrimeTest():
for y in range (2, 400):
if isPrime(y):
print y
def generateAllPrimes(num):
listOfPrimes = []
for x in range(2,num):
... |
991,581 | 70b8d2aa0c26c2cd1a18579f82b6a1c86ed75bb8 | # Generated by Django 3.2.6 on 2021-09-02 01:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('secondary', '0006_auto_20210830_2358'),
]
operations = [
migrations.AddField(
model_name='parent',
name='email',
... |
991,582 | dd22dd84e09e55206223bc9d0932a2a201c9848b | import torch
from torchvision.utils import save_image
def reconstruct(filename,input,encoder,decoder,image_size,num_chanel,device):
with torch.no_grad():
x_sample = input.to(device)
x_reconstruct_mean = decoder(encoder(x_sample))
save_image(torch.cat((x_sample, x_reconstruct_mean), dim=0).v... |
991,583 | b6e9f830759f3c3ca9fc548016ad16a67c1cd509 | """Test the `GlobManager` class.
"""
import os
from tests.helper_functions import TestCaseWithFakeFiles
from watch_do import GlobManager
class TestGlobManager(TestCaseWithFakeFiles):
"""Test the `GlobManager` class.
"""
def test_last_files(self):
"""Test that the `last_files` property is being ... |
991,584 | 74d98230d3aafb3b4f347917db4021e26aee89b0 | # -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
#过滤器
import json
import scrapy
from scrapy.contrib.pipeline.images import ImagesPipeline
from scrapy.exceptions import DropItem... |
991,585 | a787ec716807c85408bbf9138935155016cfc1b4 | #
# BuilderBot.py
#
# @author Alain Rinder
# @date 2017.06.07
# @version 0.1
#
import random
import time
from src.player.IBot import *
from src.action.IAction import *
class BuilderBot(IBot):
def play(self, board) -> IAction:
if self.remainingFences() > 0 and len(board.storedValidFencePl... |
991,586 | f42d590602554951de13c3007a079bccf14a30d9 | from django.db import models
#from numpy.random import random_sample
# Create your models here.
class Tempvalt(models.Model):
temperature = models.FileField()
altitude = models.IntegerField() |
991,587 | d7a672fbcc8982ca0b82d02eeb7859200639f570 | import urllib
import requests
import time
from bs4 import BeautifulSoup
import csv
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36"
query = 'Python'
query = query.replace(' ', '+')
URL = f"https://google.com/search?q={query}&num... |
991,588 | 598d4bd6dcaf55e3587cbb1df4fc0622260a2007 | from ast import arg
import boto3
from botocore.exceptions import ClientError
import argparse, os, glob, logging, json, sys
from subprocess import check_output
from datetime import datetime
#########################
# Utility Functions #
#########################
# Setup the logging
def setup_logging(log_file_pa... |
991,589 | 01819743e12acee57f97ba5e55ef4f72517b1e6d | from django.test import TestCase, SimpleTestCase
from django.urls import reverse, resolve
from accounts.views import profile, order_history
from accounts.forms import UserProfileForm
class TestURLs(SimpleTestCase):
def test_profile_URL(self):
"""
Testing profile URL
"""
url = rever... |
991,590 | 3fc1a8c6eaa54c1465f9b7067a4a20d01a91fdad | import pytest
from django.contrib.auth.models import AnonymousUser
from django.test import RequestFactory
from ..api.views import FoesViewSet
from ..models import Foe
pytestmark = pytest.mark.django_db
class TestFoeViewSet:
def test_get_queryset(self, foe: Foe, rf: RequestFactory):
view = FoesViewSet()
... |
991,591 | ecf14b5d5b08c0eb33e6e25d8bb938b7646ac7c4 | from django.conf.urls import url
from basic_app import views
app_name='basic_app'
urlpatterns=[
url(r'^register/',views.register,name='register')
]
|
991,592 | 1ebcc253daea235221a7fb38ac3bf30ce96e89ec | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 4 17:29:16 2019
@author: Tanya Joon
"""
#importing dependencies
from glob import glob
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Input, Dense, Flatten, Average
from tensorflow.keras.utils import t... |
991,593 | 142f8f96ba9f7d1fc12f8aba6acf9dbae7b0a954 | import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import pyomo.environ as po
import time
from datetime import datetime
import itertools
import sys
from optparse import OptionParser
import data
################ PLOTTING ################
class Timeslot():
def __init__(self, start, end, color, titl... |
991,594 | 84051f672930f6737415535730f346c6e278e1f5 | #!/usr/bin/env python
# coding=utf-8
from handlers.index import IndexHandler
from handlers import wap
app = [
(r"/", IndexHandler),
(r"/trade/wap/pay", wap.WapPayHandler),
(wap.URL_WAP_PAY_CALLBACK, wap.WapPayCallbackHandler),
(wap.URL_WAP_PAY_NOTIFY, wap.WapPayNotifyHandler),
(r"/trade/wap/refun... |
991,595 | c812871a0c63102522e99fa949cb2c8bf5beeba3 | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import cStringIO
import re
import ipaddr
from bob.forms import AutocompleteWidget
from django import forms
from django.conf import settings
from... |
991,596 | f6f646fd2122f394ae9e034cbcdd413d953c4741 | from dataclasses import dataclass, field
from typing import Optional
from .derived_view_structure import DerivedViewStructure
from .destination_display_ref import DestinationDisplayRef
from .fare_scheduled_stop_point_ref import FareScheduledStopPointRef
from .multilingual_string import MultilingualString
from .schedule... |
991,597 | 9a69d42331e666754254ee28ac069c14a256edb0 | from pymongo import MongoClient
import pymongo
def to_mongo(list_dic):
assert (type(list_dic == list))
lista = []
client = pymongo.MongoClient("mongodb+srv://m001-student:m001-mongodb-basics@sandbox.q0fpj.mongodb.net/<proyecto>?retryWrites=true&w=majority")
database = client.proyecto #indicando base ... |
991,598 | 849e3f358a4e798b2f7ae3ea484962435a57144d | # -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-07-16 01:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0030_auto_20200709_0223'),
]
operations = [
migrations.AlterField... |
991,599 | 9c5092226276a4ba97f5bb3ada79d33ef7d4815c | n,m = map(int,input().split())
ab = [list(map(int,input().split())) for _ in range(n)]
cd = [list(map(int,input().split())) for _ in range(m)]
ans = [0]*n
for i in range(n):
count = 10**9
for j in range(m):
ch = abs(ab[i][0] - cd[j][0]) + abs(ab[i][1] - cd[j][1])
if ch < count:
ans[i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.