index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
998,800 | c8a08f01db7e9602b0d74765c66593979883e92d | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
from Api import settings
from status.managers import StatusManager
from status.utils import upload_update_image
class Status(models.Model):
user = m... |
998,801 | 27c8fd346ca48dda317e929ef608f9a7458433ec | n=int(input('Enter the number of integer you want to insert in the list::'))
lis=[]
for i in range(n):
lis.append(int(input('Enter the element for the sort in assending order::')))
t=lis
l=len(lis)
for i in range(l):
for j in range(i,l):
if lis[i]<lis[j]:
lis[i],lis[j]=lis[j],lis[i]
print(l... |
998,802 | a4229421245aa5dfe4e7a20804292a67c3d53599 | '''
Created on 6 feb 2012
@author: Batch
'''
import xbmc, xbmcaddon, xbmcgui, xbmcplugin
from common import notification, get_url, regex_get_all, regex_from_to, create_directory, write_to_file, read_from_file, clean_file_name
from datetime import date, timedelta
import urllib, os, sys, re
import shutil
from furk impo... |
998,803 | 152e5cd0252f23ab940555fa42178d0f9c6f0eaf | from threading import Thread
import usb
import usb.core
import usb.util
import time
import os
import sys
import struct
from pocketsphinx import LiveSpeech, get_model_path
live_speech=None
dev = usb.core.find(idVendor=0x2886,idProduct=0x0018)
file_path = os.path.abspath(__file__)
model_path = get_model_path()
# Defi... |
998,804 | c0a4d362f87c9e2e07fa730cb7a173f511d7d3ab | import torch
import visdom
# 创建visdom客户端,使用默认端口8097,环境为first,环境的作用是对可视化的空间进行分区
vis = visdom.Visdom(env='first')
# vis对象有text(),line(),和image()等函数,其中的win参数代表了显示的窗格(pane)的名字
vis.text('first visdom', win='text1')
# 在此使用append为真来进行增加text,否则会覆盖之前的text
vis.text('hello pytorch', win='text1',append=True)
# 绘制y=-i^2+20*i+1的曲线,o... |
998,805 | f3fa44e95985408cdc9b06c8f2a622bc2dae0ee3 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Created by fengyuwusong at 2018/1/19
__author__ = 'fengyuwusong' |
998,806 | a963c5439202edd12612e43ba50a70ba7627d0fb | import itertools as it
from conference_scheduler.resources import Shape, Constraint
from conference_scheduler.lp_problem import utils as lpu
def _schedule_all_events(events, slots, X, summation_type=None):
shape = Shape(len(events), len(slots))
summation = lpu.summation_functions[summation_type]
label =... |
998,807 | fd00224fa7816e7718ac592c2ccd2cdaaa55ed24 | # encoding: utf-8
from django.test import TestCase
from django_nose.tools import *
from wpkit.wp import content
from .. import Differ
BALANCE_TESTS = (
(
'<p> <p>Test 0</p>',
False,
'<p> </p><p>Test 0</p>'
),
(
'<p>Test 1 <i>abc <b>nested tags</b> and </p>\n<p>Unbalanced ... |
998,808 | 10aa2f23139ab31db29c82131a909cab2358924f | from django.views.generic import ListView, DetailView, UpdateView
from django.views.generic.edit import CreateView
import django_tables2 as tables
from django_tables2 import RequestConfig, SingleTableView
from core.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from orders.forms import Cu... |
998,809 | 53a933ab636b13350cf861c38c778995289ac8ca | """Robot parameters"""
import numpy as np
import farms_pylog as pylog
class RobotParameters(dict):
"""Robot parameters"""
__getattr__ = dict.__getitem__
__setattr__ = dict.__setitem__
def __init__(self, parameters):
super(RobotParameters, self).__init__()
# Initialise parameters
... |
998,810 | 52dcede9522b7eb556d900d5f78fd77f3126fb82 | # -*- coding: utf-8 -*-
import logging
import re
import threading
from zigbee_hub.telegesis.prompt_parsers import PROMPT_PARSERS
class IncomingMessage(object):
@staticmethod
def is_incoming_message(message):
"""
:param message: the message
:type message: unicode
"""
re... |
998,811 | 191673563e7bcf777afb9bc34d5b5a3197e1d40d | # -*- coding: utf-8 -*-
import scrapy
import re
import json
from tv_spider.spiders.store import client, db
import tv_spider.const.video_source as video_source
import tv_spider.const.tv_status as tv_status
import tv_spider.const.video_status as video_status
class IqiyiSpider(scrapy.Spider):
name = 'iqiyi'
cust... |
998,812 | 33f4027e4ebb7dc24283d1009dd723c83476793d | import torch
from torch import nn
import torch.nn.functional as F
from bbox.bbox import box_decode
class BCEFocalLoss(torch.nn.Module):
def __init__(self, gamma=2, alpha=0.25, reduction='elementwise_mean'):
super().__init__()
self.gamma = gamma
self.alpha = alpha
self.reduction = ... |
998,813 | c38830f15293e78d763b083860b9c6d42a8bf989 | # -*- coding: utf-8 -*-
import datetime
import math
from telegram import InlineKeyboardButton, InlineKeyboardMarkup
from data.data_api import get_trip, get_name, is_suspended, unsuspend_trip, suspend_trip, remove_passenger, get_time, \
remove_trip, get_slots, new_trip, get_new_passengers
from routing.filt... |
998,814 | 48c6ce078d49dbd825c59859508459ed6dda9253 | import numpy as np
from getTrainingData import getTrainingData
def normalizeData():
trainingData = getTrainingData()
size= trainingData.shape
trainingData[:,8] = trainingData[:,8] / np.linalg.norm(trainingData[:,8])
trainingData[:,17] = trainingData[:,17] / np.linalg.norm(trainingData[:,17])
trainingData[:,3] = t... |
998,815 | c411d6485f108a82c1103184cc8824b84b11a866 | '''
Unittests for VertexCovering.py
January 2021 Jakub Kazimierski
'''
import unittest
import VertexCovering
class test_VertexCovering(unittest.TestCase):
'''
Class with unittests for VertexCovering.py
'''
# region Unittests
def test_ExpectedOutput(self):
'''
C... |
998,816 | 2e865da8dd537bc2e4f863db95a70d58849b9608 | from multiprocessing import Process
import threading
import os,signal, time, sys, random, sysv_ipc,datetime
Quantite_energie = 0
def Weather():
print("weather affiche la temperature: ",temperature)
def transaction(lock,semaphore_thread):
message,messageType = MARKET_QUEUE.receive()
data = message.decode().split('... |
998,817 | 6c4a4bff4a319fef0d627965b9a86f958730a7be | from EmpiricalDistribution import EmpiricalDistribution
from Unigram import Unigram
from Bigram import Bigram
brown_clean = './corpora/clean/brown_clean.txt'
def head(n, prob_table):
c = 0
for i in prob_table:
print(i, prob_table[i])
c += 1
if c == n:
break
print()
d... |
998,818 | 0609f0e4597de9817e0acd0751e094fe7f78074c | import re
import os
def getNum(string):
pattern = re.compile('\d+')
nums_list = pattern.findall(string)
return nums_list
def getLineFromFile(readfile):
rf = open(readfile)
lines = rf.readlines()
for line in lines:
nums_list = getNum(line)
for num in nums_list[1:]:
sql = "insert " + nums_list[0] + "-- " +... |
998,819 | 93ca3f29935222a0be3ad3eac0e736fa3bee3be3 | from threading import Thread
import time
from decimal import Decimal
import requests, json
class Strategy(Thread):
def __init__(self, queue, batch_size):
Thread.__init__(self)
self.queue = queue
self.batch_size = batch_size
def run(self):
batch = self.queue.get(self.batch_size)... |
998,820 | 9b4ed7623e687a3a18feee5f07a12f8b400b2100 |
from tests import FieldElementTest
from helper import run
run(FieldElementTest("test_ne"))
run(FieldElementTest("test_sub"))
run(FieldElementTest("test_mul"))
run(FieldElementTest("test_div"))
|
998,821 | a657eabbb0f9695020485fc9f2fe2ca865fea1ac | n = int(input("Vul een getal in: \n"))
getal = "oneven"
if n % 2 == 0:
getal = "even"
print(getal)
|
998,822 | dc2d85ae24926623393235a53c0a6854fc188dd1 | a = int(input())
b = int(input())
total = a + b
diff = a - b
mult = a * b
div = a / b
exp = a ** b
print(a, "+", b, "=", total)
print(a, "-", b, "=", diff)
print(a, "*", b, "=", mult)
print(a, "/", b, "=", div)
print(a, "**", b, "=", exp)
|
998,823 | a265a583ef19d1743e419177c8ac2ccc1d63a303 | from django.urls import path
from .views import VentaView, ProductoView
urlpatterns = {
path('venta/', VentaView.as_view(), name="Realizar una venta"),
path('producto/', ProductoView.as_view())
} |
998,824 | 6e13ffe3657c6e55c02cfccca81385ec0de4ec8e | def transform(value, subject_number):
return (value * subject_number) % 20201227
public_keys = [9717666, 20089533]
key = 1
loop_size = 0
while key != public_keys[0]:
key = transform(key, 7)
loop_size += 1
key = 1
for _ in range(loop_size):
key = transform(key, public_keys[1])
print(key)
|
998,825 | 4ef6b628e6ae4b05eb597f1d061f4578617cefdf | def shifteslayout(i, p, *rows): i["00 Shift/EcalPreshower/" + p] = DQMItem(layout=rows)
shifteslayout(dqmitems, "01-IntegritySummary",
[{ 'path': "EcalPreshower/ESIntegrityClient/ES Integrity Summary 1 Z 1 P 1", 'description': "ES+ Front Integrity Summary 1 - <a href=https://twiki.cern.ch/twiki/bin/view/CMS/DQMShift... |
998,826 | f3a7efabc9ce5ad23cd6f7eb256b800fa9047ac6 | """ read the LHD summary csv file and put in in a dictionary of arrays
where the index is the shot number. This may require adding a "0" shot
(apparently not as of Feb 2013.
Where possible, integers and reals
are converted, and the strings are reduced to the minimum length. (Note - this
will cause errors if longer s... |
998,827 | af152d3b1784137a28144aea26fb38c9f1b2d007 | #### Implement doc2vec ####
import gensim
import pandas as pd
from sklearn.model_selection import train_test_split
pd.set_option('display.max_colwidth', 100)
# Read in data, clean it, and then split into train and test sets
messages = pd.read_csv('data/spam.csv', encoding='latin-1')
messages = messages.drop(labels = ... |
998,828 | 1141a2849817bb86a3964d03b8a24d43f6acc488 | from app.model.tables import Movie
from app.model.tables import db
from app.model.serializer import SerialMovie
from sqlalchemy import func
serial_movie = SerialMovie()
serial_movie_many = SerialMovie(many=True)
def check_movie(name: str, year: int) -> bool:
movie = Movie.query.filter_by(name=name, year=year).f... |
998,829 | 9c2c520c4db6b05238396231b5175b0f2c3d7655 | import tensorflow as tf
import numpy as np
from stable_baselines.common.callbacks import BaseCallback
from collections.abc import Iterable
import logging
import os
from framework.FileManager import FileManager
class EpisodeStatsLogger:
def __init__(self, tb_writer):
self.writer = tb_writer
def create... |
998,830 | 8953e3f1f9ac4fcbbfd9d5ae3647b6db1fd74b74 | # BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
__all__ = ("from_iter",)
from collections.abc import Iterable
from awkward_cpp.lib import _ext
import awkward as ak
from awkward._dispatch import high_level_function
from awkward._nplikes.numpylike import NumpyMetadata
np = Numpy... |
998,831 | 2484a0fdecd662a5765423d21409685f18cb6619 | class Validator():
def month_is_valid(self, month):
if(month is None):
return False
if(int(month) not in range(1, 13)):
return False
return True
def quarter_is_valid(self, quarter):
if(int(quarter) in range(1, 5)):
return True
return ... |
998,832 | f633a2f299d28cae99c20313246a96a8af6587b2 | """
只使用10个桶。(实际上是20个,可以优化。)
第一遍排序将nums中的数放到个位对应的桶中去。 每个桶是一个数组,可以装多个数据。
第二遍排序将桶中的数放到十位对应的桶(另一个桶)中去。 以此类推。
* 每次从桶中取数据都要从0号桶取到9号桶。 且桶中数据得按顺序读取。*
正确性验证:
第一遍时,每个桶中数字的个位数是一样的。
第二遍时,假如2号桶中有2个数字,则2个数字的十位一样,下面数字的个位数较小。(因为上一轮中个位数小的在小号的桶,因此会先取到它,放到当前桶)
以此类推,第N遍排序后,每个桶里数字后N位肯定是有顺序的。 所以最终是有顺序的。
... |
998,833 | 47a5c0965d6ec3a13609a971b494ee357dc6b16a | <<<<<<< HEAD
class Solution:
def singleNumber(self, nums: List[int]) -> int:
"""
交换律:a ^ b ^ c <=> a ^ c ^ b
任何数于0异或为任何数 0 ^ n => n
相同的数异或为0: n ^ n => 0
"""
# a = 0
# for n in nums:
# a = a ^ n
# return a
# 脑筋急转弯型:
... |
998,834 | 3dff13b69fc49196686b2c26bd435d1d5992e2d0 | import os
def directory_choice():
#this function should print out
#all of the available directories
#in the current working directory
#then ask the user to choose one
#and return it
print(os.getcwd())
documents = (os.listdir(os.getcwd()))
print()
lst = []
for i in do... |
998,835 | 6a76844ab901cb35144f512cb4fb034b24d2f319 | # Convolution Neural Network (CNN)
# Importing the libraries
from keras.models import Sequential
from keras.layers import Conv2D
from keras.layers import MaxPooling2D
from keras.layers import Flatten
from keras.layers import Dense
from keras.preprocessing.image import ImageDataGenerator
# Initialising the CNN
classif... |
998,836 | b3b8fd25bb87579398dbce2bd119ea7ab5374f1e | """
This module contains the functions used to create Dash layout elements.
"""
from datetime import datetime
from zoneinfo import ZoneInfo
import polars as pl
from dash import dcc, html
from dash.development.base_component import Component
from feffery_antd_components.AntdTree import AntdTree
from src.data.data_extr... |
998,837 | 8a40ad24088a8307988dfe88a96c295312309089 | import os
from PIL import Image, ImageDraw
from weighted_quick_union import WeightedQuickUnion
class WeightedQuickUnionImage(WeightedQuickUnion):
"""docstring for WeightedQuickUnionImage"""
def __init__(self, n):
super(WeightedQuickUnionImage, self).__init__(n)
self.w = 400
self.h = 40... |
998,838 | a5561e0c9c5a1ce8d95feec86d9f2df8912b06eb | from string import digits, ascii_letters
_chars = ascii_letters + digits
def to_char(table):
return ''.join([_chars[i] for i in table])
def to_base62(url_id):
table = []
while url_id > 0:
mod = url_id % 62
table.append(mod)
url_id = int(url_id / 62)
table.revers... |
998,839 | 2dd997908da046a2944f3e51bb194c52023c6f95 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat 11 March 11:40:23 2017
@author: Professor Junbin Gao
Copyright: Professsor Junbin Gao, The University of Sydney Business School
March 2017
"""
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt('ibmclose.txt')
times, x = d... |
998,840 | 216485bb3f0fcf454dfea0c3182d83da3a4b83a9 |
def ask_number_columns():
print("Digite número de linhas e colunas", end="\n")
return input()
def ask_pos():
print("Digite linha", end="\r\n")
x = input()
print("Digite coluna", end="\r\n")
y = input()
return str(int(x)-1) + str(int(y)-1)
def print_board(no_rows_columns, number_bomb_map... |
998,841 | 9df4134ebb66bea97b678c5f895d730c9038e1fc | import requests
import re
url = 'http://www.budejie.com/text/'
html = requests.get(url)
print(html.status_code)
content = html.text
duanzi = re.findall(r'<div class="j-r-list-c-desc">\s+(.*)\s+</div>', content)
f = open('duan.txt', 'w')
for each in duanzi:
if '<br />' in each:
new_each = re.sub(r'<br />... |
998,842 | 4c79925689731831ba0b967edd52abd5737aacb8 | # -*- coding: utf-8 -*-
from .abstract_tag import AbstractTag
class ExperienceTag(AbstractTag):
pass
|
998,843 | 79c529e66fa9f2ed291a724f23a910cd4713a951 | n = int(input())
i = 0
j = ""
for i in range(0,n):
j+=(n-i)*"*"
j+=2*i*"o"
j+=(n-i)*"*"
print(j)
j=""
|
998,844 | 4e3aa71fee75a2abfc9c209091ad0b20afb09b5f | from django.conf import settings
def common(request):
return {
'BASE_TEMPLATE': getattr(settings, 'YUMMY_BASE_TEMPLATE', 'base.html')
}
|
998,845 | a68154062e71519aa1ecf4514ac468238cca3491 | from flask import Flask, render_template, redirect, url_for, request
app = Flask(__name__)
# @app.route("/")
# def index():
# return "Hello world"
@app.route("/", methods=['GET', 'POST'])#renders the login page
def login():
error = None
if request.method == 'POST':
if request.form['username'] != ... |
998,846 | e2632d3c4c8f204dc3720d8e4d3573cd96c5754d | import csv
import re
def at_removal(sentence):
x = sentence.split()
i = 0
length = len(x)
while i < len(x):
if re.search('@', x[i]):
x.pop(i)
length -= 1
i -= 1
i += 1
result = ' '.join(x)
return result
def hashtag_removal(sentence):
x ... |
998,847 | a8311d5e4d378da99b91686728f9d72fc41293a8 | import double_or_nothing_util as dnUtil
import sys
import math
class BotPlayer:
def __init__(self):
self.resetBot()
def resetBot(self):
"""Set up the bot for the beginning state of the game"""
self.state = [None, None, None, False]
self.score = 0
counts = {}
f... |
998,848 | a13835bdaab1331ff5d47f79ef5b72d5dab31c78 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
dataset = pd.read_csv('diabetes.csv')
print(dataset.head(5))
print(dataset.shape)
print(dataset.de... |
998,849 | da4e6ed5da47c4ebc0463f2139541fe6003ec2ed | import os
import porter
# initializing punctuation marks list and stop words list
PUNCTUATION_MARKS = [',', '.', '<', '>', '|', ':', '(', ')', '/', '_', '\\', '?', '-', '!', '#', '%', '^', '&', '*', '_', '+', '~']
STOP_WORDS = open('STOP_WORDSs.txt', "r").read().split('\n')
# cleaning data by removing punctuat... |
998,850 | a17315d2fa42a84558e5588305a8720b575c3b91 | """
First compute the prefix sums: first[m] is the sum of the first m numbers.
Then the sum of any subarray nums[i:k] is simply first[k] - first[i].
So we just need to count those where first[k] - first[i] is in [lower,upper].
To find those pairs, I use mergesort with embedded counting. The pairs in the left half and ... |
998,851 | d9c3fea7d3586b07aa95904be48a8e6babf82c12 | """Syntax highlighting."""
from __future__ import annotations
import itertools
import logging
import time
import tkinter
from tkinter.font import Font
from typing import Any, Callable, Iterator
from pygments import styles, token
from pygments.lexer import Lexer, LexerMeta, RegexLexer
from pygments.lexers import Markd... |
998,852 | 27b69fd17c93942c1287c6c7fa856fefd34df7b2 | from django.db import models
class Pessoas(models.Model):
nome = models.CharField(max_length=30)
sobrenome = models.CharField(max_length=30)
idade = models.IntegerField()
salario = models.DecimalField(max_digits=10, decimal_places=2)
bio = models.TextField()
foto = models.ImageField(upload_to='... |
998,853 | 59c189fdea0a40f71699339bb7d006fb20f715c9 | def get_node_outputs(node_path):
"""
Get all node outputs and return it
"""
item = ix.get_item(node_path)
obj_array = ix.api.OfItemArray(1)
obj_array[0] = item
item_outputs = ix.api.OfItemVector()
ix.application.get_factory().get_items_outputs(obj_array, item_outputs, Fals... |
998,854 | dd0d0eae86003d6f0d9bbcc1d17fd8bc48e5af3a | import os
import re
import time
import sys
#save similarities or differences to a file
def saveFile(log):
file = open("similarLogs.txt","w")
for line in log:
file.write(line)
file.write("\n")
file.close()
return
#Open files and write them to a list
def openFile(Filename):
f = open(Filename,"r")
print "Ope... |
998,855 | df56a5e7c77a303a85b69a757bc9dcb380792310 | """Math functions for calculator."""
def add(numbers):
"""Return the sum of the two inputs."""
sum1 = 0
for i in numbers:
sum1 = sum1+i
return sum1
def subtract(numbers):
"""Return the second number subtracted from the first."""
dif = numbers[0]
for i in numbers[1:]:
di... |
998,856 | 3537d78049e8c5a78c57b4e86a118ea59c717d99 | import media
import movie_trailer
dwaraka=media.Movie("Dwaraka","Making a thief change into a god man",
"http://www.telugumirchi.com/en/wp-content/uploads/2016/08/dwaraka-movie-poster.jpg",
"https://www.youtube.com/watch?v=DDWPxs8zTzg",
"srinivasa ravindra",
... |
998,857 | 541a47c6c88a97c3f3e81cc0e359c4f50f822772 | #-*- coding:utf-8 -*-
'''
绘制L-System曲线
根据设定的迭代规则(字符串替换),得到曲线字符串
然后逐步绘制
'''
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.animation as animation
'''
曲线规则:
start 开始迭代的字符串
reps 替换规则
level 迭代次数
rotate 旋转角度
actions 动作规则
left 左旋
... |
998,858 | 37df11ac0354d68d9546f1e63d33bf829bf3bbc8 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--interactive", action="store_true")
args = parser.parse_args()
import trajoptpy
import openravepy as rave
import numpy as np
import json
from trajoptpy.check_traj import traj_is_safe
if rave.__version__ < "0.9":
raise Exception("this examp... |
998,859 | fa1f6c3a88350960be3d56ebdf312ae3b4bda20a | import numpy as np
# import matplotlib.pyplot as plt
from scipy import interpolate
class Extrapolator:
"""Extrapolate and interpolate a sparse vector field into a dense one"""
def __init__(self):
return
# @staticmethod
# def plot_vector_field(x, y, step=1, scale=1, show_plot=True):
# ... |
998,860 | 0eb77a35566f7c229e336e93e22cab2a2bba5bed | # -*- coding: utf-8 -*-
"""
Created on Thu Feb 13 09:43:11 2020
@author: Utilisateur
"""
from autograd import grad
from lik_functions import ord_loglik_j, binom_loglik_j, categ_loglik_j
###########################################################################
# Binary/count gradient
###################... |
998,861 | 16759af55432f707454cfa9990846ca07325f7f9 | # Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
998,862 | ae3fcd0efb4a137c07b3df9993b41639d6490d24 | # -*- coding: utf-8 -*-
#############################################################################
# #
# EIDEAnalog library (excerpt). #
# ... |
998,863 | 956c9cc5abd5b77f8e532b584f17d0375c65be29 | '''
@Author: your name
@Date: 2020-06-08 15:28:39
@LastEditTime: 2020-06-08 18:52:10
@LastEditors: Please set LastEditors
@Description: In User Settings Edit
@FilePath: /Cracking_the_Code_Interview/Leetcode/String/28.Implement_strStr.py
'''
# Implement strStr().
# Return the index of the first occurrence of needle in ... |
998,864 | a2fac703505da20c75337ad76565a3c53f8d6f77 | __author__ = 'Lunzhy'
import os
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import font_manager
from Submissions.IWCE2014 import *
## 5000, 10000, 15000 points
possoin_time = [515, 1367, 2025]
dd_time = [662, 2427, 4785]
total_time = [1294, 4030, 7151]
others_time = [total_time[i] - possoin_t... |
998,865 | 5f903f2764f8a6e68d02eff1b0677e1fc87fad9b | import maya.cmds as mc
def getSGfromShader(shader=None):
if shader:
if mc.objExists(shader):
sgq = mc.listConnections(shader, d=True, et=True, t='shadingEngine')
if sgq:
return sgq[0]
return None
def assignObjectListToShader(objList=None, s... |
998,866 | 1c77d11406255b45dcee25fd294b13cdca97c20d | import os
import logging
import requests
from weather import get_weather, get_radar
from telegram.ext import Updater, CommandHandler
logging.basicConfig(
filename="log.txt",
level=logging.DEBUG,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
)
token = os.environ["telegram_bot_token"]
def... |
998,867 | 3b2a4730cb306d91e8f1cedc25bd176465ba30b6 | monday_temperatures = [9.1, 8.8, 7.5]
print(monday_temperatures)
monday_temperatures.append(8.1)
print(monday_temperatures)
monday_temperatures.clear()
print(monday_temperatures)
monday_temperatures = [9.1, 8.8, 7.5]
print(monday_temperatures)
print(monday_temperatures.index(8.8))
# print(monday_temperatures.index(... |
998,868 | 5646606518b4cb0fbc600d5a3c6ffdab348a946c | # -*- coding: utf-8 -*-
"""
Created on Thu Aug 27 09:49:17 2020
@author: Claudio Collado
"""
#Ejercicio 4.13
import random
import numpy as np
def error():
error = random.normalvariate(0,0.2)
return error
N = 999
temp = np.array([float(37.5 + error()) for i in range(N)])
np.save('Temperaturas',temp)
print... |
998,869 | c4d5d83231a4f67e44943d2fcd756aa8a8e2e27a | import pickle
words = open("garbled_email_dictionary.txt").read().split("\n")
"""
wdict = [defaultdict(lambda:[]) for i in xrange(11)]
for w in words:
print w
for i,c in enumerate(w):
letters = list(w)
letters[i] = "*"
wdict[len(w)]["".join(letters)].append(w)
plainwdict = map(dict,wdic... |
998,870 | 405fe9b05ffd7712c89d75fed6b34f21337da4aa | import gzip
import json
with gzip.open('./models/dataset/Digital_Music_5.json.gz', 'rb') as g:
data = {}
i = 0
fiveStar = 0
fourStar = 0
threeStar = 0
twoStar = 0
oneStar = 0
items = set()
users = set()
for line in g:
line = json.loads(line)
keys = ['reviewerID... |
998,871 | 17b44f215f7d2903d2469e378027b5532e6e650b | from django.db import models as db
from django.utils.importlib import import_module
from django.contrib.contenttypes.fields import GenericRelation
# relation constants
FOREIGN_KEY = 30
MANY_TO_MANY = 31
ONE_TO_ONE = 32
GENERIC = 33
# relations choices for type select box
RELATION_CHOICES = (
(FOREIGN_KEY, 'Foreig... |
998,872 | ae4f7003a7e20a967a24215d52432cfc5ad25ceb | import dash_core_components as dcc
import dash_html_components as html
from data_reader import *
from Sentiment import *
import dash_table
from graphs import *
import base64
def no_with_comma(n):
return "{:,}".format(n)
def no_to_percentage(n):
return "{0:.2f}%".format(n)
# For individual boxes at top li... |
998,873 | 67ce968596d9dd06e8112cb6979eea94fde4dd4d | # Source: https://stackoverflow.com/a/26284607/6759699
from numpy.core.numeric import binary_repr, identity, asanyarray, dot
def matrix_power_mod(M, n, mod_val):
# Implementation shadows numpy's matrix_power, but with modulo included
M = asanyarray(M)
if len(M.shape) != 2 or M.shape[0] != M.shape[1]:
... |
998,874 | 77b0aa26dd8d77336ae69518ed81c96d4c4f8862 | # -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 17:14:39 2019
@author: jivitesh's PC
"""
import numpy as np
arr3=np.arange(5)
print(arr3)
condition=[True,False,True]
x=[10,20,30]
y=[70,80,90]
condition=np.array(condition)
x=np.array([True,False,True,False,True])
y=np.array([False,True,False,False,Tr... |
998,875 | adb64d75ebe0b54476805c8024ae7689c6a7c99d | import os
from flask import Flask, session
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
import csv
app = Flask(__name__)
# Check for environment variable
if not os.getenv("DATABASE_URL"):
raise RuntimeError("DATABASE_URL is not set... |
998,876 | 14379b3e9d48e0a610e25ab1ff7b609468ee09b3 | print ("excel to python process")
print ("-----------------------")
import xlrd
wbv=xlrd.open_workbook("info1.xls")
ns=wbv.nsheets
sn=wbv.sheet_names()
print ("Number of sheets in the info1.xls is:",ns)
print ("sheet Names are :",sn)
wsv=wbv.sheet_by_name("Information")
nr=wsv.nrows
nc=wsv.ncols
print ("total number of... |
998,877 | 915de9a96c40deaa5a8846fba8326cb72103b1e8 | from django import urls
from django.urls import path
from . import views
urlpatterns = [
path('',views.home,name='home'),
path('m-data',views.m_data,name='mdata'),
path('stazioni_appaltanti',views.stazioni_appaltanti)
]
|
998,878 | a78fc71a0bc4ecac9bb3a6a7a7421ef9a654325e | import sys
import json
from flask import request
sys.path.extend([r'D:\bmd\bmd_server\src\company\flask_server'])
# from flask_server.bmd_celery.tasks import check_online_total,check_tel_total
from flask import Blueprint
import os
api = Blueprint("api",__name__)
from flask_server.common import get_log
from flask_ser... |
998,879 | 0810f491d0d6fd59635da9a45ac135a73d9e5c62 | import unittest
from unittest.mock import Mock
from parameterized import parameterized, parameterized_class
from module1 import attack_damage
from unittest import mock
class Module1Tests(unittest.TestCase):
@mock.patch("module1.randint", return_value=1, autospec=True)
def test(self, mocked_randint):
... |
998,880 | a594679614eb2f101dbfab2937c7157f522c5323 | from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QDialog
from Ui_mainui import Ui_Dialog
class Dialog(QDialog, Ui_Dialog):
"""
Class documentation goes here.
"""
def __init__(self, parent = None):
super(Dialog, self).__init__(parent)
self.setupUi(self)
@pyqtSlot(... |
998,881 | c636d43e056d27f7e4c24dd4a456304092d1dec5 | from euler_util import is_palindrome
def euler55():
"""http://projecteuler.net/problem=55
2520 is the smallest number that can be divided by each of the numbers from
1 to 10 without any remainder.
What is the smallest positive number that is evenly divisible by all of the
numbers from 1 to 20?
... |
998,882 | 9c801855bf78ef458912784f7cbf0215cf120d5d | from __future__ import print_function
import re
import os
import gzip
import time
import matplotlib.pyplot as pl
import matplotlib
from matplotlib.animation import FuncAnimation
import numpy as np
import scipy
from .utils import mystr as _mystr
from .utils import pyname
from collections import namedtuple
from .pyd... |
998,883 | 408c5867835dc29639a7c3a177a1e12bbd275bf1 | #!/usr/bin/env python
import queue
q = queue.PriorityQueue()
alist = [5, 2, -2, 7, 0, 1, 4] # -2 0 1 2 4 5 7
size = 3
for item in alist:
q.put(item)
if q.qsize() == size:
break
# now go over remaining items and check if q min is < next element
start = size
while(start < len(alist)):
top = q.get()
if top < a... |
998,884 | 27b3e3859dd92bc246ee0de747c996ee8adbebb6 | #
# Copyright (c) 2021, NVIDIA CORPORATION.
#
# 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 ... |
998,885 | 76b6c25f6c0ca6754da728ef50831a839b00385d | from single_layer import single_neutron
import numpy as np
import logging
logger = logging.getLogger(__name__)
class NeuralNetwork:
"""
Implement a Neural network of given required shape.
It implements both forward propogation and Backward propogation.
"""
def __init__(self, number_of_layers_neuro... |
998,886 | 53287824244fc056bdbf92c21618673cf3685f4c | # Guess that number game
import sys
from random import randint
count=0
ranNum = randint(1,20)
list=['Four','Three','Two','One','Zero']
print('******* Guess a number between 1 and 20. You have 5 tries *****\n\n')
while count < 5:
guess = int(input('Guess a number: '))
count=count+1
if gue... |
998,887 | 45f28232068e75a52044aa7dac9002a10a977f35 | #
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
998,888 | 74c0989ac0a0779fb83f6326ce977d45a09e8fc1 | import sys
import numpy as np
from sklearn import linear_model # 回归模型
import matplotlib.pyplot as plt # 可视化
import sklearn.metrics as sm # 预测评估
# prepare data for y=f(x)
filename = sys.argv[1]
X = []
Y = []
with open(filename,'r') as f:
for line in f.readlines():
xt,yt = [float(... |
998,889 | c28b937060b60583c8e90ed6f3b54c19280f3544 | lst = list()
print(type(lst))
for i in range(0,5):
a = "ok"
lst = lst.append(a)
print(lst)
|
998,890 | 1be66317fd59d0e7bdadaeb7339061494d85ceec | import json
import os
import urllib
from datetime import datetime
import re
from urllib.request import urlopen
import youtube_dl
from bs4 import BeautifulSoup
from gtts import gTTS
from newspaper import Article
gamingStreamIdList =["feed/http://feeds.abcnews.com/abcnews/topstories"]
# gamingStreamIdList =["feed/http:... |
998,891 | ee851f2ffaf21d781df8beb587a9e0343daf41ac | from agent import Agent
from planet import Planet
from rule import Rule
def main(args):
agents = [Agent(p=0.2) for _ in range(10)]
rule = Rule(planet=Planet(Resources=2000, N=10),
agents=agents, viz=args.viz)
for age in range(1, args.max_age):
rule.tick()
if age % args.prin... |
998,892 | 16581ef16eec8cc60d937c33969af4a4c51b3d48 | class Solution:
def containsNearbyDuplicate(self, nums, k):
dic={}
for index,n in enumerate(nums):
if n not in dic:
dic[n]=[]
dic[n].append(index)
for n in dic:
list=dic[n]
for i in range(len(list)-1):
if list[i+... |
998,893 | aa2c20509dcaa5178b6a2bdbe7aaee468f1b45ca | from django.shortcuts import render
from rest_framework import generics, permissions
from user.models import Profile
from django.contrib.auth.models import User
from user.serializers import ProfileSerializer, UserSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response
fr... |
998,894 | 652fe7dbff05ebc3699f4827e4521fec27288a1d | from setuptools import setup, find_packages
setup(name='Test', packages=find_packages())
|
998,895 | 8fe12c843c2e0ac72dedbd28a5d770ac3d814712 | from django.db import models
from django.utils import timezone
# Create your models here.
class Sales(models.Model):
descuento = models.IntegerField(verbose_name="Descuento")
fecha_inicio = models.DateTimeField(verbose_name="Fecha de inicio", default=timezone.now)
fecha_fin = models.DateTimeField(verbose_... |
998,896 | 5539c27a2727647d2f1d72841e4b6cc473c7a686 | import os
from os import path
for i in os.listdir('/tmp'):
if '-' in i : print i
print a
try :
st = os.stat(filepath)
except:
continue
print filepath
print d_size.setdefault(st.st_size, []).append(filepath) |
998,897 | a1c51b56b70e767be8b8ced737f0c0561727ee25 | # Due to some modifications of the Python interface in the latest Caffe version,
# in order to run the code in this file please replace
#
# if ms != self.inputs[in_][1:]:
# raise ValueError('Mean shape incompatible with input shape.')
#
# in caffe_root/python/caffe/io.py line 253-254, with
#
# if ms != self.inputs[i... |
998,898 | ad71159d1e6af3910669f1b7b7bd4ede6916483b | from library.views.type.type_create import *
from library.views.type.type_update import *
from library.views.type.type_delete import *
|
998,899 | b919d081c2e4f64bf6a731fd0d017ad764f40de9 | #!/bin/python3
import sys
# case가 'MMMMMMMMM' , 'MMMMMMMMMMMMMMMMM' 이런거일때 결국 n제곱..
def solution(members, maleFans, totalCase):
result = 0
failCaseDict = {}
for memberIdx in range(len(members)):
member = members[memberIdx]
if member == 'F':
continue
else:
for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.