index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
7,500 | f87c036c1eb5026e088bed62fbc330cfd2ea1952 | # coding=utf8
from __future__ import print_function
from application.controllers import *
from application.models import board
def __return__():
return render_template('board/board.html',
lecturers = board.Lecturer.query.all(), disciplines = board.Discipline.query.all())
def __return_modal__(id):
le... |
7,501 | 3d55a5b4e332523025f65e5f5859f4633f4ee9a3 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Created with YooLiang Technology (侑良科技).
# Author: Qi-Liang Wen (温啓良)
# Web: http://www.yooliang.com/
# Date: 2015/7/12.
from monkey import BasicModel
from monkey import Fields
class WebInformationModel(BasicModel):
class Meta:
label_name = {
"... |
7,502 | 11d96a8a400afb0861b92d8900e003826614c99a | # Generated by Django 3.1.3 on 2020-11-19 06:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myems', '0004_auto_20201118_1446'),
]
operations = [
migrations.RenameField(
model_name='dg',
old_name='sn',
... |
7,503 | c6d6fcc242e1b63104a3f3eb788880635257ff4c | api_id = "2168275"
api_hash = "e011a9cb95b7e7e153aa5840985fc883"
|
7,504 | bdd9ebfa9a2f14d57efd527ca88032bfb0160a5e | from tkinter import *
import mathcalc as c
root= Tk()
root.title("CALCULATOR")
ent=Entry(root,width=35)
ent.grid(row=0,column=0,columnspan=3,padx=10,pady=10)
#ent.grid(row=0,column=0)
ch=''
num=ent.get()
def clicked(num):
current=ent.get()
ent.delete(0,END)
ent.insert(0,str(current)+str(num))
def click... |
7,505 | 0edca9893d62eea6513543a1d3dd960e9e95d573 | import math
def normal(data,mean,variance):
# print data-mean
return -1*(((data-mean)**2)/(2*variance)) - (0.5 * math.log(2*3.1415*variance))
a = math.log(0.33333) + normal(67.7854,6.0998,13.5408)
b = math.log(0.33333) + normal(67.7854,119.3287,9.4803)
c = math.log(0.33333) + normal(67.7854,65.7801,12.6203)
d =... |
7,506 | 2d3ab575b18144f714f06167f54cd069af4e5895 | num=int(input("enter no"))
def factorial(no):
fact=1
if no <0:
print("-ve no factorial not exist")
else:
for i in range(1,no+1):
fact=fact*i
return fact
print(factorial(num)) |
7,507 | f7a493ab8e9845d0e9da33a0ee45d7c3ef66deb5 | from django.http import HttpResponse
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
def people(request):
return render(request, 'people.html')
def docs(request):
return render(request, 'docs.html')
def gallery(request, page=None):
if page:
return render(request, 'g... |
7,508 | 5cc325758d5bd99ebe49c40af4d2e339bbf64044 | import time
import click
from contextlib import contextmanager
from pathlib import Path
from model.data import CellsDataset
from model.model import build_model, train_transform, test_transform
from model.vis import plot_cells
@contextmanager
def timer(name):
t0 = time.time()
yield
print("{color}[{name}] d... |
7,509 | aefb49410e077180a660d17c4c646265a75969a7 | offset = input()
cal = 1030 + int(offset) * 100
if 0 < cal < 2400:
print('Tuesday')
elif cal < 0:
print('Monday')
else:
print('Wednesday')
|
7,510 | 7112eb52aea9be6f8e682b4dacc6b615365c8cea | import numpy as np
from cost_functions import trajectory_cost_fn
import time
class Controller():
def __init__(self):
pass
# Get the appropriate action(s) for this state(s)
def get_action(self, state):
pass
class RandomController(Controller):
def __init__(self, env):
""" YOUR CODE HERE """
... |
7,511 | 8ec981bf8746e09d3865bc20dcfbf2fbd797c145 | import xl2dict
myxlobject= XlToDict()
myxlobject.convert_sheet_to_dict(file_path="Soul Breaks.xlsx", sheet="First Sheet",
filter_variables_dict={"User Type" : "Admin", "Environment" : "Dev"}) |
7,512 | fb787e688da975d37f9fcc39bf5e02957b186982 | # (c) Copyright 2015-2016 Hewlett Packard Enterprise Development LP
# (c) Copyright 2017 SUSE LLC
import json
from bll.plugins import service
import logging
import pecan
import pymysql.cursors
LOG = logging.getLogger(__name__)
class PreferencesSvc(service.SvcBase):
"""
Simple service to manage user preferenc... |
7,513 | 6cdaf89d97be8f5ef37ab35f2916a36b4c75ddbe | def pantip(k, n, arr, path,len):
if len == 0:
if sum(path)==k:
path.reverse()
print(path)
return
path.append(arr[len-1])
pantip(k,n,arr,path,len-1)
path.pop()
#backtrack
pantip(k,n,arr,path,len-1)
inp = input('Enter Input (Money, Product) : ').... |
7,514 | 9f01483aaa744972fae358577e6f093bd491f357 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
CELERY_TIMEZONE = 'Asia/Shanghai'
# CELERY_RESULT_BACKEND='redis://localhost:6379/1'
# BROKER_URL='redis://localhost:6379/2'
BROKER_BACKEND = 'mongodb' # mongodb作为任务队列(或者说是缓存)
<<<<<<< HEAD
BROKER_URL = 'mongodb://10.6.0.149:27017/' ... |
7,515 | 07d2da14d0122ad2c8407bb13b8567ca62356bef | def build_shift_dict(self, shift):
'''
Creates a dictionary that can be used to apply a cipher to a letter.
The dictionary maps every uppercase and lowercase letter to a
character shifted down the alphabet by the input shift. The dictionary
should have 52 keys of all the uppercase letters and all th... |
7,516 | f1c32fe7a29cddf4f881b46f4feab06390a76a44 | # -*- coding: utf-8 -*-
import hashlib
import time
from datetime import datetime, timedelta
# 像访问对象一样, 访问字典
class ObjectLikeDict(dict):
def __getattr__(self, name):
try:
return self[name]
except:
return ''
# 合并字典
def merge_dict(dict1, dict2):
return (lambda a, b: (lam... |
7,517 | 7a1a9d2e773fb783d8522f1ea51e753d5d3782e9 | import config
import math
import pygame
import utils
class Rocket:
def __init__(self):
self.x = config.initialPosition['x']*config.game['scale'] + config.game['width']/2;
self.y = config.game['height'] - config.game['floorHeight'] - config.initialPosition['y']*config.game['scale'];
self.angle = config.initial... |
7,518 | 6a400419c26c62471dfc6893cc2d1ff6d88e49f4 | import whoosh.index as index
from whoosh.fields import *
from whoosh.qparser import MultifieldParser
from whoosh import scoring
w = scoring.BM25F(B=0.75, content_B=1.0, K1=1.5)
fieldnames = ["bill_text", "bill_title", "year", "sponsor_name", "subject"]
boosts = {"bill_text": 1, "bill_title": 2.5, "year": 0, "sponsor_n... |
7,519 | 9033ba0a19d765a83737d59289735a9ffd02abb1 | distance = float(input("Введите начальную дистанцию: "))
target = int(input("Введите целевую дистанцию: "))
day = 1
print("{:>3}-й день: {:.3}".format(day, distance)) # некрасивенько
while target > distance:
day += 1
distance += distance / 10
print("{:>3}-й день: {:.3}".format(day, distance))
print("Ответ: ... |
7,520 | 3bc6091d822fa197dcce3cd75fa9755dc9f93592 | """Scans all files in this project for FIXME and TODO comments and writes them to todos.txt
has to be invoked while being in myLambda/ and not in e.g. myLambda/src"""
import sys
import os
import re
files = []
searchFiles = []
# get all subdirs and its files
for root, dirs, f in os.walk('./'):
files.append((root, f))
... |
7,521 | 5a7b68648898818e0db47f225f3d4b0972cd5b99 | _all__ = ["minning_algo"]
|
7,522 | 1d72a9882aea1e0f808969828ed2e69ecd79ac71 | from typing import Dict, Any
from urllib import request
from django.shortcuts import render, get_object_or_404
from django.urls import reverse
from .models import Product
from cart.forms import CartAddProductForm
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout... |
7,523 | 40471bfcf05ef45fbb070bbb5bfd4c425fe59b1c | # Differences between Python 2 and Python 3
print "hello world"
# become
print("hello world") # in Pyton 3
raw_input('What is your name?')
# become
input('What is your name?') # in Python 3
# the language of Python
# Reserved words
and
as
assert
break
class
continue
def
del
elif
else
except
finally
for
from
g... |
7,524 | dfcfa4fa036fe8c058d66fc0b9ea73ddb9d4446e | from aiogram import Dispatcher
from create_bot import bot
from data_base import sqlite_db
# new user in group
async def new_member(message):
new_user = message.new_chat_members[0]
user_id = new_user['id']
if new_user['username']:
user_name = new_user['username']
elif new_user['first_name']:
... |
7,525 | c35ecad842477fc8501a763f7eb972f6e7fc13e1 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 1 11:14:13 2019
@author: dobri
"""
import numpy as np
from astropy.stats import circmean
x = np.multiply(np.pi,[(0,1/4,2/4,3/4,4/4),(1,5/4,6/4,7/4,8/4),(5/4,5/4,5/4,5/4,5/4),(0/5,2/5,4/5,6/5,8/5)])
s = np.shape(x)
phikprime = np.array(x*0, dtype... |
7,526 | dd71feda1ed5ff7ef9dee1573ad63939a3e09691 | # Copyright (C) 2018-2023 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.tools.mo.ops.pack import PackOp
from openvino.tools.mo.front.extractor import FrontExtractorOp
from openvino.tools.mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs
class StackFrontExtractor(FrontExtractorOp):
... |
7,527 | 4a3611ecd70d80575f9f68bf45d67532a17b9c93 | import itertools
from typing import Tuple, List, Dict, Optional, Hashable, Collection
class Hypergraph:
"""
Represents a hypergraph, consisting of nodes, directed edges,
hypernodes (each of which is a set of nodes) and hyperedges (directed edges
from hypernodes to hypernodes). Contains functionality to... |
7,528 | ffe10ee8b2ebaad565e9aef5047440a067d4e239 | import server.wsgi as flask
import server.grunner as gunicorn
from utils.cfgreader import EnvReader, BoolVar
def use_flask() -> bool:
env_var = BoolVar('USE_FLASK', False)
return EnvReader().safe_read(env_var)
if __name__ == '__main__':
if use_flask(): # dev mode, run the WSGI app in Flask dev server
... |
7,529 | 480787d7bc0e87df7c59c4deb402eea76643680c | from unidecode import unidecode
import pdb
import os, manage
import re
from datetime import *
import codecs
import csv
import smtplib
from django.core.urlresolvers import reverse
from django.shortcuts import redirect
from django.contrib.auth.models import User
from django.db.models import Q
from django.contrib import... |
7,530 | 2236591b3a30f51442beb20c6c43cc9e6cd921d2 | # import sys
# sys.stdin = open("농작물input.txt")
T = int(input())
for n in range(1, T+1):
N = int(input())
arr = [list(map(int, list(input()))) for _ in range(N)]
# print(arr)
a = N//2
b = N//2
result = 0
for i in range(N):
for j in range(a, b+1):
result += arr[i][j]
... |
7,531 | 2023e0b749338488e63cbbb475b7a915bccccce0 | from subprocess import check_output
import json
import datetime
date = datetime.datetime.now()
mo = date.month
day = date.day
year = date.year
str = '{0}-{1}-{2}'.format(mo, day, year)
instances = json.loads(check_output("aws lightsail get-instances", shell=True))
inst_names = []
inst_dict = {}
for instance in instan... |
7,532 | 290811317ddb49a7d2a9f44ab7e0b6d201db12e1 | from recipes.almahelpers import fixsyscaltimes # SACM/JAO - Fixes
__rethrow_casa_exceptions = True
context = h_init()
context.set_state('ProjectSummary', 'proposal_code', '2017.1.01355.L')
context.set_state('ProjectSummary', 'piname', 'unknown')
context.set_state('ProjectSummary', 'proposal_title', 'unknown')
context.s... |
7,533 | 3185b6b1902099caed66ce6f97cd1b9940261fc1 | import torch.nn as nn
from layers import maskAConv, MaskBConvBlock
class PixelCNN(nn.Module):
def __init__(self, n_channel=3, h=128, discrete_channel=256):
"""PixelCNN Model"""
super(PixelCNN, self).__init__()
self.discrete_channel = discrete_channel
self.MaskAConv = maskAConv(n_... |
7,534 | 04097e63de5cd94ca8921be5cb6c2155c1e7bc20 | import pathlib
import sys
import yaml
from google.protobuf.json_format import ParseError
sys.path = [p for p in sys.path if not p.endswith('bazel_tools')]
from tools.config_validation.validate_fragment import validate_fragment
def main():
errors = []
for arg in sys.argv[1:]:
try:
valid... |
7,535 | ad622ff2e1d9286246b2175694a9ae796f8d2557 | ''' This module creates the models/tables in the database
catalog using sqlalchemy '''
from catalog import db
class Items(db.Model):
''' Model to store all the information about an item '''
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String)
item = db.Column(db.... |
7,536 | 608c116cd42132bd63be5056f0aaf5c78933886e | # SPDX-FileCopyrightText: 2021 John Park for Adafruit Industries
# SPDX-License-Identifier: MIT
import time
import random
import board
import audiomp3
import audiopwmio
from adafruit_crickit import crickit
ss = crickit.seesaw # Crickit seesaw setup
button = crickit.SIGNAL1 # momentary switch to trigger animation
ss... |
7,537 | 8adf8cfc72d5af955bf7509d3573a9bcc7c0845e | import inspect
import re
import openquake.hazardlib.source as oqsrc
# List of valid attributes for an area source
AREAS_ATTRIBUTES = set(['source_id',
'name',
'tectonic_region_type',
'mfd',
'rupture_mesh_spacing',
'magnitude_scaling_relationship',
... |
7,538 | 6f271e6cfb03977d52c50562c3c394b962c9af83 | # vim:sw=4 ts=4 et:
# Copyright (c) 2015 Torchbox Ltd.
# tomasz.knapik@torchbox.com 2017-12-07
#
# Permission is granted to anyone to use this software for any purpose,
# including commercial applications, and to alter it and redistribute it
# freely. This software is provided 'as-is', without any express or implied
# ... |
7,539 | 1e02d584cde0cdf251aa36abd27b683219ef87ed | # -*- coding: utf-8 -*-
"""
Created on Fri Apr 10 01:03:35 2020
@author: Jordan
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import date
## from COVID19_Simple import *
from COVID19_Diff import calc_diff_country
### Dash Stuff ###
import dash
import dash_core... |
7,540 | d57b91bf41f031e3362dabdef8c67a0da04fe577 | from ROOT import *
gSystem.Load("libAnalysis")
import sys
import argparse
parser = argparse.ArgumentParser(description="Python script to process and merge showers.")
group = parser.add_mutually_exclusive_group()
group.add_argument("-v", "--verbose", help="Turn on verbose output",
action="store_tru... |
7,541 | acb879cb72e5b3ac897a271dc680e4ca763d2122 | from django.db import models
class Professor(models.Model):
nome = models.CharField(max_length=100)
apelido = models.CharField(max_length=30)
descricao = models.TextField(max_length=1000)
def __str__(self):
return self.nome
class ImagemProfessor(models.Model):
professor = models.Forei... |
7,542 | 5fb3905abf958f0a8be41cd6ad07efb2a0cf6c66 | import sys, os
def resource_path(relative_path):
""" Get absolute path to resource, works for dev and for PyInstaller """
try:
# PyInstaller creates a temp folder and stores path in _MEIPASS
base_path = sys._MEIPASS
except Exception:
base_path = os.path.abspath(".")
return os.p... |
7,543 | e7c18fa99c801fd959c868954f020d8c55babe0d |
def long_alpha(str1):
list1 = []
list2 = ""
maxi = 0
j = 0
for i in range(len(str1)):
if i == 0:
list2 += str1[i]
elif ord(str1[i - 1]) <= ord(str1[i]):
list2 += str1[i]
else:
list1.append(list2)
list2 = ""
... |
7,544 | ad9facb9c8e552845df9171549f886f3e9cba193 | # PROBLEM: Code organized in package and want to import a submodule from one o the other pkg
# submodules without hardcoding the package name into the import statement
# SOLUTION: Use pkg-relative import
# Absolete path
from mypackage.A import grok
print(dir(grok))
grok.testA() |
7,545 | 7a6d45ef87d93af9a15bd352b893164d3a36c399 | import sys
import os
import traceback
from src.properties import *
from src.utils import *
from subprocess import call
from src.entity.cursor import Cursor
from curses import *
def main(screen, file_path):
setUpEnv()
text = readFileIfExist(file_path)
while 1:
try:
text = startEditing(s... |
7,546 | 1808be09c2730af5829bb0c7c0c7cfe9f80fe84c | list = input().split()
n = int(list[0])
k = int(list[1])
list.clear()
for i in range(0, n):
list.append("")
tmp = input().split()
list[i] = tmp[0] + list[int(tmp[1])-1]
for i in range(0, k):
start = input()
print(len([word for word in list if word.startswith(start)])) |
7,547 | c3fae13b488a717419adb8292597746a383b332c | class boxCar:
def __init__(self, *args, **kwargs):
print("print the keyword arguments dictionary {0} by {1}".format(kwargs, "WANGH"))
self.name = kwargs["name"]
self.domains = ["BODY","PWT","INFO","ADAS","INF"]
self.configuration = {}
def addEcu(self, ecu, domain):
i... |
7,548 | 0af45914c8c111a42b0b9684f5f0ee19ef5eeb70 | import math
import random
import time
import numpy as np
class NeuralNetwork:
digits = [
[
1,1,1,1,1,
1,0,0,0,1,
1,0,0,0,1,
1,0,0,0,1,
1,1,1,1,1
],
[
0,0,1,0,0,
0,0,1,0,0,
0,0,1,0,0,
... |
7,549 | e8a024796b6426e572571e46030678e90c537229 | from django import forms
from django.forms import widgets
# from product.models import PRODUCT_OTHER_CHOICE, PRODUCT_CATEGORY_CHOICES
PRODUCT_OTHER_CHOICE = 'other'
PRODUCT_CATEGORY_CHOICES = (
(PRODUCT_OTHER_CHOICE, 'Разное'),
('food', 'Еда'),
('drink', 'Вода'),
('cloth', 'Одежда'),
('electronics'... |
7,550 | 826abb18b11afd7a010e2bfc5a29ba068218c23a | from django.contrib.auth.mixins import LoginRequiredMixin
from django.views.generic import View
from django.http import HttpResponse
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
class View1(LoginRequir... |
7,551 | 34ad2e6fc7167766dac1ca962cab40511c89ad68 | import zipfile
zzz = zipfile.ZipFile('channel.zip','r')
filestr = '90052'
comment = []
for i in range(1000):
fname = filestr + ".txt"
for j in zzz.infolist():
if j.filename == fname :
print j.comment
comment.append(j.comment)
break
inzzz = zzz.open(fname).read()
print 'fname = ' + fname
... |
7,552 | 0f2882971f08450e970e188ed2a06ae1683c682c | import argparse
import logging
import enum
from abc import ABCMeta, abstractmethod
from nmigen import *
from ....gateware.pads import *
from ....gateware.i2c import I2CTarget
from ... import *
class Event(enum.IntEnum):
START = 0x10
STOP = 0x20
RESTART = 0x30
WRITE = 0x40
READ = 0x50
... |
7,553 | 4afc2ceed860c20af071e1d9ccaca17973cb9a8e | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def swapPairs(self, head: ListNode) -> ListNode:
dummy_head=ListNode(0)
dummy_head.next=head
pre=dummy_head
cur=head
... |
7,554 | 927470fe0087b17e5fe67a9b8b3cc13a40d8be1a | import BlockDeviceHandler
import json
import LocalMachine
import os
""" This module automaticly format the disk based on diskconf.json """
def module_print(text):
print_text = "[ autoformat disk ] " + str(text)
print(print_text)
def parse_config_file_from_disk(path, confname="diskconf.json"):
json_path =... |
7,555 | cab233976653b8135276ff849955f32766833354 | import os
import numpy as np
import warnings
import soundfile as sf
def load_path():
path = os.path.join(os.path.dirname(__file__))
if path == "":
path = "."
return path
def create_folder(directory):
try:
if not os.path.exists(directory):
os.makedirs(directory)
except... |
7,556 | 1f114b4716a44f5370495297511c305ecbb680c3 | import os, copy
from a import Moon, updateOneMoon, updateAllMoons
file_path = os.path.dirname(os.path.realpath(__file__))
input_path = file_path + "/b.in.txt"
inpt = open(input_path, 'r')
moons = []
for line in inpt:
new_moon = Moon(line)
moons.append(new_moon)
initial_moon_position = copy.deepcopy(moons)... |
7,557 | 9065842a8e90c833278547310f027bc63c7a9a47 | #!/usr/bin/env python
# coding: utf-8
import numpy as np
import copy
import sys
def mutate(genotype_in, mut_matrix):
genotype_out = np.zeros(8)
for i in range(8):
rand_vec = np.random.choice(8, size=int(genotype_in[i]), p=mut_matrix[i,:])
genotype_out+=np.bincount(rand_vec, minlength=8)
r... |
7,558 | e048170775c589cf0a9fb3d54c72dab4df3f1bcb | import pickle
import numpy as np
in_dir = "C:\\Users\\ganga\\Github\\Generative-Models\\Project\\Data\\Dynamics\\"
out_dir = f"C:\\Users\\ganga\\Github\\Generative-Models\\Project\\Data\\Dynamics\\"
# Read frames
train_frames = pickle.load( open(in_dir +'\\train_frames.pkl' , 'rb' ))
test_frames = pickle.load( open(... |
7,559 | d6046217308745b85455aed78734700b9622782c | import os
from logzero import logger as log
from extract import data_generator
from transform import create_dataframe
def bigquery(
datafile,
dataset=os.environ["BQDATASET"],
project=os.environ["GCPPROJECT"],
schema=[
{"name": "conversation", "type": "STRING"},
{"name": "id", "type": ... |
7,560 | a9ce341ffe26ab6c476237030e23e6ae57b8fa33 | from random import randint
#given a list of names, cities and neigborhoods, generate a client table.
#------------------------MODEL------------------------------
#([cliente_id], [nome], [sexo], [telefone], [cpf], [cidade_nome], [cidade_bairro_nome], [cidade_bairro_cep])
class Employee:
def __init__(self, id, name ,s... |
7,561 | 0131657a7675904ee2743448f514a9f11e0dc0ad | # -*- coding: utf-8 -*-
"""
Default organizer for bioinfoinformatics project directiories - RNA-Seq based model
"""
import os
import sys
#main path
curr_path = os.getcwd()
print("\nYour current directory is: " + curr_path + "\n\nIt contains the following files and directories:\n\n" + str(os.listdir("."))) # displays... |
7,562 | c5e7fdcbd4a9281597a35a180f2853caac68f811 | # Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
from collections import namedtuple
from functools import partial
import inspect
from itertools import product
import math
import os
import numpy as np
from numpy.testing import assert_allclose, assert_array_equal
import pytest
import ... |
7,563 | d77036ed07231719358658a42dc14d20453bd792 | def pattern4(n):
"""
n: length of the base of the triangle ie. the max number
of starts it will contain.
"""
for row in range(1, n+1):
for col in range(1, row+1):
print("*", end="")
print("")
if __name__ == '__main__':
n = int(input(("Enter height of the triangle: ")))
pattern4(n)
|
7,564 | 511016b9cd54f6824360d609ede233b9cc3e4447 | class Mood(object):
GENERIC = 1
HIGH_TEMP = 2
LOW_TEMP = 3
HIGH_DUST = 4
LOW_DUST = 5
def decision(self, data):
temp = float(data)
if temp <= 10:
return self.LOW_TEMP
if temp > 30:
return self.HIGH_TEMP
if (10 < temp <=30):
... |
7,565 | 9ad92b23b8a02204a86af599e507eb889e5bcec7 | #!/usr/bin/env python
import rospy
from geometry_msgs.msg import PoseStamped
from styx_msgs.msg import Lane, Waypoint
from scipy.spatial import KDTree
import numpy as np
from std_msgs.msg import Int32
import math
'''
This node will publish waypoints from the car's current position to some `x` distance ahead.
As men... |
7,566 | 1896f4d5b304915d5cbbb30b0a83854c4a8cc60c | from wtforms import Form, StringField
class SearchForm(Form):
criteria = StringField("Texto a buscar")
|
7,567 | 42a717591fb8fe480581d8996e9811d0292d0eb1 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from cv2 import DualTVL1OpticalFlow_create as DualTVL1
from tensorflow.python.platform import flags
import os
import sys
sys.path.insert(0, '..')
from utils import image_funcs
import numpy as np
def make_di... |
7,568 | c7553cadb49c9c7e80a7800b9bff4d5f64796494 | import pytest
from a3 import *
from test_utils import *
from numpy import allclose
def test_problem_7_1_8():
assert(check_linalg())
assert(abs(problem_7_1_8(5000)-84.8)<1)
|
7,569 | 7ff19ee35422395f78dca1e17a736df20a40ea98 | import os
import sqlite3 as db
os.system('clear')
persons = []
class Person:
def __init__(self, name, surname, job, salary):
self.name = name
self.surname = surname
self.job = job
self.salary = salary
def create(name):
conn = db.connect(name + '.db')
c = conn.cursor()
c.execute("""CREATE TABLE first(
... |
7,570 | 0dec0f04cfe891eea74ef45484fa7433e3429dcd | import os
import glob
ONE_KB = 1024
def get_files(dirname, size_in_kb):
"""Return files in dirname that are >= size_in_kb"""
return (
filename
for _, _, files in os.walk(dirname)
for filename in files
if int(filename) >= size_in_kb * ONE_KB
)
# Pybites solution
def get_f... |
7,571 | d567dfe29380a34534308446a9c8940cede84083 | def func_sum_even(n):
e_digit1=n%10
n//=10
e_digit2=n%10
e_digit3=n//10
sum_even=e_digit1*(1-e_digit1%2)+e_digit2*(1-e_digit2%2)+e_digit3*(1-e_digit3%2)
return sum_even
# n=int(input())
# print(func_sum_even(n)) |
7,572 | e6b3def6ed6f2523d88912832a876caf2742b786 | import argparse
import pickle
import pandas as pd
from pyspark.sql.session import SparkSession
parser = argparse.ArgumentParser()
parser.add_argument('--rs', type=str, nargs='+')
args = parser.parse_args()
ss = SparkSession.builder.getOrCreate()
post_df = None
for f in args.rs:
df = ss.read.json(f).select('id', ... |
7,573 | 422491852b80c2fc4a2e73c01fd01acaad4cf9c8 | #Testing Operating System Descriptions
#OS : LMDE 4 Debbie
#Version: 4.6.7
#Kernal Version : 4.19.0-8-amd64
#Scripting Langages : Python3
#----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------... |
7,574 | e8daf03f987c7512ff245bfbe16c447acd6b5986 | import API.enum as enum
import re
class ObjectValidator():
def __init__(self, validationData={}, *args, **kwargs):
self.data = validationData
self.statusCode = 200
self.validationPipeline = []
self.errors = {}
self.invalidFields = []
def flush(self):
self = Obj... |
7,575 | 74e3f4cd7b09d9b96feb3f927a509b113481eaed | from django.apps import AppConfig
class CheckoutConfig(AppConfig):
name = "checkout"
# Override the ready method and import the signals module
# so that update_on_save and update_on_delete will be called
# after an OrderLineItem model instance is saved or deleted
def ready(self):
import c... |
7,576 | 0a19efea0c8d7e5e248ca3265ffcb55604dc500c | __author__ = 'Administrator'
import socket,os,time
server = socket.socket()
server.bind(("localhost",9999))
server.listen()
while True:
conn,addr = server.accept()
while True:
data = conn.recv(1024)
if not data:
break
cmd,filename = data.decode().split()
if o... |
7,577 | 4c8a873c816678532b029af409be13258757eae1 | # Напишите программу, которая вводит с клавиатуры последовательность чисел и выводит её
# отсортированной в порядке возрастания.
def is_numb_val(val):
try:
x = float(val)
except ValueError:
return False
else:
return True
def main():
num_seq = input("Введите последовательность ... |
7,578 | 20d363f5d02cc0b1069aa8951999c0cb22b85613 | # This is a module
class MyMath:
def isEven(num):
if(num%2==0):
return True
return False
def isOdd(num):
if(num%2==0):
return False
return True
def isPrime(num):
for i in range(2,num):
if num%i==0:
return ... |
7,579 | 31b87a3ceca1f48665ecc9754d5f87bb9b7bbf13 | import psycopg2
from .configuration import ConfigurationException
DB_CONNECT_STRING = "host='{host}' dbname='{dbname}' user='{user}' password='{passwd}'"
class DBItemCompany:
def __init__(self, _id, tweeter, category, categoryUrl, provenScore, ranking, location, url, categoryId):
self.id = _id
se... |
7,580 | b34ad8d7fc8df0ab86c5930ab2b5aa1f86d13ae3 | from django.db import models
class Author(models.Model):
author = models.CharField(
"Author",
max_length=30,
blank=False,
null=False
)
biography = models.TextField(
"About author",
max_length=500,
blank=True,
null=True
)
def __str__... |
7,581 | 2cef5311a9ff9497ad6611fe7b47e4f7c5b1b3c7 | #!/usr/bin/python
from random import *
prob = "change"
cases = [
10,
10,
10,
100,
100,
100000,
100000,
100000,
100000,
100000
]
cur = 0
st = [1,2,5,10,20,50,100,200,500,1000,2000,5000,10000]
for (n) in cases :
cout = ""
... |
7,582 | a28ece0db9bf0d4c3ab26207216b1da45f7aaa0f | """Proper parenthetics extra credit kata."""
from _que_structure import Q
def proper_parenthetics(string):
"""Return if parentheses are matching or not."""
if isinstance(string, str):
paren_q = Q()
for i in range(len(string)):
paren_q.enqueue(string[i])
opening_parens = 0
... |
7,583 | 170716ccaaf45db2ee974de260883a8d70513f52 | from django.db import models
class Event(models.Model):
name = models.TextField()
host = models.TextField(null=True)
fields = models.TextField(null=True)
description = models.TextField(null=True)
date = models.TextField()
start_time = models.TextField()
end_time = models.TextField()
ba... |
7,584 | 0e19d7251db3382c34ad2d38a7984b65325ecfbf | from django.db import models
from django.db.models.base import Model
# Create your models here.
class Categoria(models.Model):
categoria = models.CharField(max_length=40)
def __str__(self):
return self.categoria
class Producto(models.Model):
codigo = models.CharField(max_length=40)
nombre = mo... |
7,585 | ba289bcdc0aa7c2ad70dba7fac541900d0b55387 | import os
# Set a single thread per process for numpy with MKL/BLAS
os.environ['MKL_NUM_THREADS'] = '1'
os.environ['OPENBLAS_NUM_THREADS'] = '1'
os.environ['MKL_DEBUG_CPU_TYPE'] = '5'
import numpy as np
from matplotlib import pyplot as plt
from copy import deepcopy
from kadal.optim_tools.MOBO import MOBO
from kadal.s... |
7,586 | fa3ab879541c04e278317b11dd79e6e1b4319536 | FILE = "Luke"
NAME = "Luke Walker"
NATIONALITY = "American"
CLASS = "Manipulator"
WEAPON = ""
BIRTH = ""
BIRTH_LOCATION = ""
LETTER = "W"
RECRUITMENT_ORDER = 10
SUMMARY = ""
ABILITIES = ""
BACKSTORY = ""
HIGHLIGHTS = ""
SUMMONS = ("Tonberry", "Grimnir", "Griever", "Starlet")
|
7,587 | 1574f034ff9b6ddb785e4c54758b2057009198ed | alias_macro = {
"class": "Application",
"method": "alias_macro",
"doc": """
Returns or modifies the macro of a command alias.
""",
"syntax": """
Rhino.AliasMacro (strAlias [, strMacro])
""",
"params": {
0: {
"name": "alias",
"... |
7,588 | 3dc83168264fbb4f9b0ab2980b845dffdc4417bb | import requests
from bs4 import BeautifulSoup
class Book:
def __init__(self, url):
self.url = url
self.title = ""
self.category = ""
self.upc=""
self.price_including_tax=""
self.price_excluding_tax=""
self.number_available=""
self.description=""
... |
7,589 | e51c57f4487a3225936d073142f1f770815c0d47 | #!/usr/bin/env python
# coding: utf-8
import sys,pysrt
import urllib2,urllib,json
import re
from urlparse import urlparse
import os
from mtranslate import translate
from argparse import ArgumentParser
reload(sys)
sys.setdefaultencoding('utf8')
#------------------------------------------------------------------------... |
7,590 | 1a29b3138f6a33fbe2781f044c1bcccd03ecd48d |
d = {
1 : 'I',
5 : 'V',
10: 'X',
50: 'L',
100: 'C',
500: 'D',
1000: 'M'
}
e = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
... |
7,591 | b6b3d94db62b47aac9bf78e8224a38ccff9335e3 | from . import utility
from . import regular_gram_schmidt as RGSC
from . import custom_gram_schmidt as CGSC
def RegularGramSchmidt():
while True:
vectors = utility.get_matrix_from_user(5)
if len(vectors) > 0:
calc = RGSC.RegularGramSchmidt()
result_matrix = calc.calc(vectors... |
7,592 | ad024a2001dc6a6fa3a2a9c1b51f79132e914897 | # -*- coding: utf-8 -*-
import requests
import json
url = "http://39.108.188.34:9090/spider/zhongdengdengji.go"
# url = "http://localhost:9090/spider/zhongdengdengji.go"
input = {
"timelimit": "1年",
"title": "GD20190305001",
"maincontractno": "YT20181228001",
"maincontractcurrency": "人民币",
"mainc... |
7,593 | f51d85ff352d9c84a8ded29ad94b24ca6dda46ad |
'''
IplNorm.py
Description:
Normalizing 0 - 255 initial fingerprint to a normalized image.
Using energy normalization.
Input:
-image
Output:
-norm_im
@author: Edoardo Foco
'''
import cv2
import numpy as np
def normalise(image):
dbl_image = image.astype(float)
#... |
7,594 | 9fd73e0a1dacc46c177f11ce4cf2351b3d622c0d | # Improting Image class from PIL module
from PIL import Image
# Opens a image in RGB mode
im = Image.open("data/frame1.jpg")
# Setting the points for cropped image
left = 155
top = 65
right = 360
bottom = 270
# Cropped image of above dimension
# (It will not change orginal image)
im1 = im.crop((left, top, right, bot... |
7,595 | d7570bbea1e8c7674d507f8e86ce04d22058b21b | class Solution:
def numIdenticalPairs(self, nums: List[int]) -> int:
count = 0
inputLength = len(nums)
for i in range (0, inputLength):
for j in range (i, inputLength - 1):
if (nums[i] == nums[j + 1]): count += 1
return count |
7,596 | ef7fad5019e79950e8fad56404e9ba5d302cfe1c |
def convertEnEntier(nombre):
result = "";
if (nombre == 4):
result = "IV"
if (nombre == 3):
result = "III"
if (nombre == 2):
result = "II"
if (nombre == 1):
result = "I"
return result
print (convertEnEntier(1))
print (convertEnEntier(2))
pri... |
7,597 | 8b0eed6d1f24b5dd30726ce08c97354a5d5ab69b | # Generated by Django 2.1.2 on 2018-10-25 09:36
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
dependencies = [
('grafit', '0002_article'),
]
operati... |
7,598 | 42e16def0fcf234f3d7c2709de36a321d8ddf29e | import collections
import re
from collections import Counter
import operator
import pickle
import math
import json
path='C:/Users/rahul/Desktop/CSCI 544/HW 2/op_spam_train/'
#path=sys.argv[1]
badWordList = ['and','the','was','for']
RE=r'\b[^\W\d_]+\b'
# NEGATIVE TWEETS
c=collections.Counter()
NT="negativeTweets.txt/... |
7,599 | 5adb16c654a4e747f803590c42328fa6ba642e95 | import os
from subprocess import Popen, PIPE
from Bio import SeqIO
from Bio.Align.Applications import ClustalOmegaCommandline
from Bio import Phylo
from io import StringIO
# from ete3 import Tree, TreeStyle
import pylab
class TreeDrawer:
def __init__(self, sequences=None):
self.sequences = sequences
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.