index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
991,900 | 0562c01ea8fae6daf1c96c6764afa33133e4c10c | from models import backbones
import os
dirpath = os.pardir
import sys
sys.path.append(dirpath)
import torch.utils.model_zoo as model_zoo
from torch.autograd import Variable
from torch.optim import lr_scheduler
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.autograd as autograd
import ... |
991,901 | aa0a5ddeb352784c2d421dd43e7803ccb0a706f4 | '''
找出所有相加之和为 n 的 k 个数的组合。组合中只允许含有 1 - 9 的正整数,并且每种组合中不存在重复的数字。
说明:
所有数字都是正整数。
解集不能包含重复的组合。
示例 1:
输入: k = 3, n = 7
输出: [[1,2,4]]
示例 2:
输入: k = 3, n = 9
输出: [[1,2,6], [1,3,5], [2,3,4]]
'''
from typing import List
class Solution:
def combinationSum3(self, k: int, n: int) -> List[List[int]]:
def helper(i... |
991,902 | 81a3bbf5742e7eaf2f5eb7768432dfef74465b67 | import os
from os import listdir
from os.path import isfile, join
import numpy as np
from pprint import pprint
class Data:
def __init__(self, path, njobs=5):
# Base data
# ['J', '#machId jobPred jobSucc setupTime']
# J = procTime energyConsddate weight rdate
self.__dict... |
991,903 | 0aa52c71f6eb8f3c1fc5136f352b309336071007 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from flask import Flask
from flask_cors import CORS
from flask_migrate import Migrate
from flask_uploads import configure_uploads, patch_request_class
from back.api_1_0 import api, auth, posts, users, tags, archives, categories, comments, users, uploads, api_tasks
from ba... |
991,904 | bd0cf08ba176323cfa973ab5deb2b092d3e46a6a | # -*- coding: utf-8 -*-
from django.test import TestCase
from excelutils.string_utils import agregar_espacios_luego_de_cada_coma_y_cada_punto, get_short_text
class StringUtilsTest(TestCase):
def test_agregar_espacios_en_blanco_a_string_con_comas(self):
expected = u'Esto, debería, estar, separado, por, com... |
991,905 | 05829e00a7405c2ee2926b6752387c9464cf8b47 | # File: hw3_part5.py
# Written by: Brandon Nguyen
# Date: 9/24/15
# Lab Section: 20
# UMBC email: brando15@umbc.edu
# Description: The purpose of this program is to prompt the user to enter the
# day of the month. Assuming the month starts on a Monday, the
# program the... |
991,906 | 3a84666bbb58ea48718513566161f60c7ba08a5e | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('people', '0001_initial'),
]
oper... |
991,907 | 90ecad84174aef0c5f269e2c84162ed5ee23dd90 | class Node :
def __init__(self, value, level=0, left=None, right=None) :
self.level = level
self.value = value
self.left = left
self.right = right
def set_value(self, value) :
self.value = value
def get_left(self) :
return self.left
def get_right(se... |
991,908 | a835bc5fc82716992b08d8412db176c2658ba4e8 | from sqlalchemy import Column, Integer, Float, String, Boolean,ForeignKey, Unicode
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine
import uuid, random
Base = declarative_base()
class Product(Base):
__tablenam... |
991,909 | 0531fe6e11302da5a3f9cc804114b3de6d10a99a | # Generated by Django 3.2.4 on 2021-07-01 00:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('grupoCero', '0003_alter_obra_precio'),
]
operations = [
migrations.AddField(
model_name='obra',
name='imagen',
... |
991,910 | d87bfb370d2a79c82cf8d998a0facdf869137652 | # Generated by Django 2.1.10 on 2019-07-17 23:45
from django.db import migrations
import tinymce.models
class Migration(migrations.Migration):
dependencies = [
('Tracker', '0058_project_date_of_end'),
]
operations = [
migrations.RemoveField(
model_name='task',
na... |
991,911 | e217704fb8f01f606af7b638c6709c72b4cb5b39 | # These URLs are normally mapped to /admin/urls.py. This URLs file is
# provided as a convenience to those who want to deploy these URLs elsewhere.
# This file is also used to provide a reliable view deployment for test purposes.
from django.conf.urls.defaults import *
urlpatterns = patterns('app.auth.views',
url(r'... |
991,912 | aabccc12356ff86b7d5613e365de7bc6f935d57e | x_value = 10
print(x_value)
def my_function(self):
print (self)
def function2(self, x_value):
print (x_value)
class Test:
x_value = 20
print (x_value)
def a_method(self):
print (self.x_value)
def method2(self, x_value):
x_value = 30
print (x_value)
print (x_value)
print(x_value)
my_function("yash")
... |
991,913 | 4a4f0e71027d92fa172f78811993aa1d62e2a6c7 | #2.1
class RectangularArea:
"""Class for work with square geometric instances """
def __init__(self, side_a, side_b):
"""
Defines to parameters of RectangularArea class. Checks parameters type.
:param side_a: length of side a
:param side_b:length of side a
"""
sel... |
991,914 | c865f26fefdd34f313548054685c46e5b04ca030 | '''
Frontend for running vm migration
'''
# import clay libs
import clay.data
import clay.create
import clay.pin
# import func libs
import func.overlord.client as fc
class Migrate(object):
'''
Used to manage virtual machine live migration
'''
def __init__(self, opts):
self.opts = opts
... |
991,915 | abd1675e57f8f2cf7ac4b6dc925493c170cafa92 | import numpy as np
import subprocess
import sys
import time
sys.path.append('../../scripts/')
from singlerun import OneRun
from readparams import ReadParams
from psidata import PsiData
from scipy.integrate import simps
def integrand(rs,psis):
return 2*rs*psis/(rs[-1]*rs[-1])
if __name__=="__main__":
... |
991,916 | fd11e66c1e0b3956299eaba5b5654ecd81f33afb | import torch
from utils import save_checkpoint, load_checkpoint, validate
import torch.nn as nn
import torch.optim as optim
import config
from dataset import MapDataset
from generator_model import Generator
from discriminator_model import Discriminator
from torch.utils.data import DataLoader
from tqdm import tqdm
def... |
991,917 | 7af2a9653a8aa7510733b79702cd4d052ed0d5bc | from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse, JsonResponse
from django.template import loader
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
import json
from ucsrb.models import TreatmentScenario
from django.... |
991,918 | 822cac35c5381f76f8b33f5e614d4faa29a45d80 | import smartcard
#from smartcard.util import toHexString
import time
import numpy as np
def parseRFID():
while True:
time.sleep(0.5)
try:
reader = smartcard.System.readers()
if not reader:
print("No readers")
return None
else:
... |
991,919 | 24867637509006adcdf2c087ccd356032288523f | #!/usr/bin/pythpon3
import sys
ifile = sys.argv[1]
ofdir = sys.argv[2]
genome_sequences = dict()
geneacc = ""
genome = ""
lineno = 0
for line in open(ifile,'r'):
if lineno % 2 == 0:
cc = line.strip().split('\t')
family = cc[2]
gene = cc[2].replace('sequence_','')
rep = cc[1].split('_')[3]
genome = cc... |
991,920 | ce06439c92ea8faaba7c700a3b87f00d534df4c6 | """Raised when a window has no rows."""
from illud.exception import IlludException
class NoRowsException(IlludException):
"""Raised when a window has no rows."""
|
991,921 | 82bbb09a4fbbb6b08736c5708544fbd596c0dcd4 | # for network related component
import os
Import('OS_ROOT')
from build_tools import *
objs = []
pwd = PresentDir()
list = os.listdir(pwd)
if IsDefined(['NET_USING_LWIP', 'NET_USING_LWIP202']):
objs = SConscript(('lwip-2.0.2/SConscript'))
if IsDefined(['NET_USING_LWIP', 'NET_USING_LWIP212']):
objs = SConscript(('lw... |
991,922 | 0f5b9fd51a494a85bd5c30271c32e60f166cba22 | '''Для каждого натурального числа в промежутке от m до n вывести все делители,
кроме единицы и самого числа. m и n вводятся с клавиатуры.'''
m = int(input())
n = int(input())
dict_ = {}
for i in range(m, n+1):
dev = 2
dev_list = []
while dev < i:
if i % dev == 0:
dev_list.append(dev)
... |
991,923 | 4679ba7924956a7db9b51fc5903c19eda30e40fc | import PreActResNet18
import torch
import torch.nn as nn
import torchvision.datasets as datasets
from torch.utils.data import DataLoader
import torchvision.transforms as transforms
batch_size = 1
classes = ('plane', 'car', 'bird', 'cat', 'deer',
'dog', 'frog', 'horse', 'ship', 'truck')
test_data = dataset... |
991,924 | a6ccdb931c4067b432c3fc849afe49f59a2bb9ea | from torch.utils.data import Dataset, DataLoader
import cv2
import torch
from models.monet_s_set import Set
import numpy as np
from math import log
import random
import math
class DataSet(Dataset):
def __init__(self, mode='train'):
super(DataSet, self).__init__()
print('正在初始化数据集')
self.set... |
991,925 | 3f1b82105d3c25ab555b5a92e417547505e8eebd | def fizz(n):
''' Returns fizz when a number is divisible by 3
Returns buzz when a number is divisible by 5
Returns fizzbuzz when a number is divisible by both 3 and 5
'''
if n % 3 == 0 and n % 5 == 0:
return 'FizzBuzz'
elif n % 5 == 0:
return 'Buzz'
elif n % 3 == 0:
return 'Fizz'
else:
return n |
991,926 | c53dcaa9a97d916ee1f46f924c0499abced0addd | #coding=utf-8
import os
import time
from appium import webdriver
#apk_path=os.path.abspath(os.path.join(os.path.dirname(__file__)),"..")#获取当前项目的根路径
desired_caps={}
desired_caps['platformName']='Android'#设备系统
desired_caps['platformVersion']='5.1.1'#设备系统版本
desired_caps['deviceName']='OneOlus X'#设备名称
#测试apk包的路径
#desired... |
991,927 | 25edc477f287db13db988d81a033fdaa8c62665e | >>> from socket import *
>>> fd = socket(AF_INET, SOCK_DGRAM)
>>> fd.sendto('hello dear', ('127.0.0.1',3000))
10
>>>
|
991,928 | 4f1af07c78fa4096b3feb1d821760280ff9483af | import os
import glob
import time
import random
from flask import Flask, render_template, jsonify
app = Flask(__name__)
ACCURACY = 1
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
#constructing the folder where the temp info is available
base_dir = '/sys/bus/w1/devices/'
device_folder = glob.glob(base_... |
991,929 | 77bce7e630d6687fcbf5489198eb8d0832815b95 | """The habitica integration."""
import logging
from habitipy.aio import HabitipyAsync
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_NAME,
CONF_API_KEY,
CONF_NAME,
CONF_SENSORS,
CONF_URL,... |
991,930 | 8ae5a05e80326a961c8c5ec1822c71aeb960175e | class Queue:
def __init__(self):
self.queue=[]
def enqueue(self,data):
self.queue.append(data)
def dequeue(self):
if(len(self.queue)>0):
#print('Dequeuing' + str(self.queue[0]))
self.queue.pop(0)
def showQueue(self):
print(self.queue[0])
... |
991,931 | 87b056a2ace6f143aff5abbb64d84268f3c0f5b5 | #!/usr/bin/python
"""
create_videobridge_config:
This script creates the following configuration file that will be
read by JItsi Videobridge component, at startup
requires:
- Python 2.7+
- Linux 2.6.x
"""
import sys, os, stat
def create_videobridge_config(prosody_section, jicofo_section):
print "config... |
991,932 | 967e5525d80a3e320684be358bb7ee8ecdb004c7 | from django.http import HttpResponse, HttpResponseRedirect, QueryDict
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from django.views import generic
from .models import *
from django.utils import timezone
from Module.Core_Network_Arch.cacti import CactiDataAnalyzer
... |
991,933 | a3f357acc59639dd347bd87637ebb093085379df | import string
import os
import xml.etree.ElementTree as ET
from xml.dom import minidom
import sys
import time
from datetime import date
import re
from collections import OrderedDict
from operator import itemgetter
import codecs
from docx import Document
from lxml import etree
import zipfile
#P... |
991,934 | f1607c1de74fdbcd5e93c98b198d4864d3057d24 | import torch
from torch import nn
from torch.nn import functional as F
import math
"""
Все тензоры в задании имеют тип данных float32.
"""
class AE(nn.Module):
def __init__(self, d, D):
"""
Инициализирует веса модели.
Вход: d, int - размерность латентного пространства.
Вход: D, int... |
991,935 | 3006ccd302e6d881ebfbf8adca7f39efac5132d0 | # Reference Code:
# https://github.com/aws-samples/amazon-sagemaker-bert-pytorch/blob/master/code/train_deploy.py
######### Imports #########
import argparse
import json
import logging
import os
import sys
from tqdm import tqdm
import numpy as np
import pandas as pd
import torch
import torch.distributed as dist
impor... |
991,936 | b18e9305cab51ff03541dff6e55214d55327f205 | import sqlite3 as lite
import generate_dataset as gd
if __name__ == '__main__':
db = lite.connect('../plag.db')
c = db.cursor()
gd.get_author_ids(c)
authors = c.fetchall()
gd.get_sentence_dataset_by_author_id(c, authors[0])
a = c.fetchall()
print len(a)
gd.get_sentence_dataset(c)
a = c.fetchmany(1024)
print... |
991,937 | 0f63b99a23698f760e20ea7ed4377ee88645f0d3 | #!/usr/bin/env python
# Copyright (c) VECTOR TECHNOLOGIES SA Gdynia, Poland, and
# Cable Television Laboratories, Inc. ("CableLabs")
#
# 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 Li... |
991,938 | fec049b48c8e8603b51be23ce11cf3ff387baa54 | # -*- coding: utf-8 -*-
class Product:
"""Intantiate products from a given list."""
def __init__(self, clean_product):
"""Product fields."""
self.name = clean_product['product_name_fr']
self.description = clean_product['generic_name_fr']
self.grade = clean_product['nutrition_gr... |
991,939 | 50cee8ccbcb2c65a1207833199be463306eb1b4d | from math import pi, cos, sin, radians, degrees, asin, acos, atan, sqrt
# rotates vector against the clock
def rotate(v, angle, in_degrees=True, return_complex=True):
if in_degrees:
angle = radians(angle)
if isinstance(v, complex):
v = v.real, v.imag
x, y = v
x_new = x*cos(angle) - y*s... |
991,940 | c273fc7b5dbe2b76217b3e677707ee2fcbf560a3 | #!/usr/bin/env python
#!encoding: utf-8
import socket
listen_fd = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
listen_fd.bind(('0.0.0.0', 7777))
listen_fd.listen(2)
print('开始监听...')
## accept是一个阻塞方法, 如果没有客户端连接进入就停在这里
## addr是一个元组, 格式为 ('客户端IP', 客户端端口)
conn_fd, addr = listen_fd.accept()
print('收到来自 %s 的连接' % ad... |
991,941 | f5cb91a239fa41b2fff988e451d5df991ba64d5b | import csv
data = csv.reader(open(r'C:\Users\IBM_ADMIN\Desktop\1.csv',encoding='utf-8'))
db = []
db2 = []
for row in data:
db.append(row)
o=-3
for i in range(10):
for i in range(len(db)):
db[i][0]=o
o+=1
print('('+str(db[i])+')'+',')
# for i in range(10):
# db2[]
data2 = open(r'C:\Users\IBM_ADMIN\... |
991,942 | a921cd35501b9783e50c352dad488371d29c1a6f | import argparse
import multiprocessing as mp
import time
import sys
import os.path
import numpy as np
import data
import tagWeighting
import locality_gen
from utils import *
def main(file_size, refresh, MAX_ITERATIONS=99):
main_timer = Timer()
data_fetch_timer = Timer()
train_data, test_data = get_data... |
991,943 | 62e9f8b2078fa4b041681728e734865137fed790 | from flask import Flask
# app = Flask(__name__,template_folder="templates",static_folder="static")
app = Flask(__name__)
from flask_demo import views |
991,944 | e3b2178dbc8a41d261bc00bff2f676186515f4db | # coding: utf-8
# Author:renyuke
# Date :2020/12/2 9:44
import datetime
starttime = datetime.datetime.now()
#long running
endtime = datetime.datetime.now()
print(endtime-starttime).seconds |
991,945 | 9666a94c75aae47bab7923d26e141175509c04bd | #!/usr/bin/env python
#
#
#
#
#
#
# IMPORT SOURCES:
# BIOSERVICES
# https://pythonhosted.org/bioservices/
#
#
# Create instance of a biological process.
#
# PRE-CODE
import faulthandler
faulthandler.enable()
# IMPORTS
# Import sub-methods.
from gnomics.objects.biological_process_files.go... |
991,946 | 836256ce0e576da6c34c299445d5f9a891defd2e | import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
from collections import deque
import numpy as np
import pygame
import random
import cv2
# VARIABLES:
#hyper params
ACTIONS = 3
GAMMA = 0.99
INITIAL_EPSILON = 1.0
FINAL_EPSILON = 0.05
EXPLORE = 500000
OBSERVE = 50000
REPLAY_MEMORY = 500000
BATCH = 100
# V... |
991,947 | d3a5e516d018e7c81d984f8efd4ade22b237c45c | import io
import json
import os
import re
import csv
import subprocess
import sdi_utils.gensolution as gs
import sdi_utils.set_logging as slog
import sdi_utils.textfield_parser as tfp
import sdi_utils.tprogress as tp
try:
api
except NameError:
class api:
class Message:
def __init__(self,bo... |
991,948 | f0a42ebcb892cc7c5d3c9c19a75eafe8ecd50515 | """
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
Written (W) 2013 Heiko Strathmann
"""
from numpy.lib.npyio import savetxt... |
991,949 | a7c0eee240e3d6468019c3e936e4de78493eb63f | import boto3
import json
import os
s3 = boto3.resource('s3')
bucket = s3.Bucket('cs691-football-dataset')
with open('data/jersey_number_labelling_via_project.json') as f:
data = json.load(f)
file_names = list(map(lambda val: val["filename"], data["_via_img_metadata"].values()))
for fname in file_names:
bucke... |
991,950 | b5b28fe93164e6515027828f44f73952cb66d6cb | import sys
sys.stdin = open('숨바꼭질 3.txt')
from collections import deque
N, K = map(int, input().split())
PG = 100001
dist = [-1]*PG
q = deque()
q.append(N)
dist[N] = 0
while q:
pos = q.popleft()
for nxt in [2*pos, pos+1, pos-1]:
if 0 <= nxt < PG and dist[nxt] == -1:
if nxt == 2*pos:
... |
991,951 | 805a27e89ed00c9e2c9374d24afaf690799c6da2 | import tensorflow as tf
import gpflow
from gpflow import kullback_leiblers
from gpflow import Parameter
from gpflow.config import default_float
from gpflow.utilities import positive, triangular
from gpflow.models import (
SVGP,
GPModel,
ExternalDataTrainingLossMixin,
InternalDataTrainingLossMixin,
)
fro... |
991,952 | ce42f6beb819675c78db345305497ca2a19b4679 | import json
from flask import abort, Blueprint
from tntfl.blueprints.common import tntfl
from tntfl.template_utils import playerToJson, gameToJson, getPlayerAchievementsJson, perPlayerStatsToJson, getPerPlayerStats
player_api = Blueprint('player_api', __name__)
@player_api.route('/player/<player>/json')
def player... |
991,953 | aab25076fdbeec66629ce3ef8fd211d4f7bef4a4 | from typing import List
from pydantic import BaseModel, validator
from pydantic.types import PositiveInt
import re
from datetime import datetime
from .turn import Turn
class Tournament(BaseModel):
id: PositiveInt
name: str
place: str
date_start: datetime
date_end: datetime
nb_turns: PositiveIn... |
991,954 | a8200a6198d1472ca3b5fee0ccfb6d74690a1983 | #!/usr/bin/env python3
#-*- coding:utf-8 -*-
''' 博客文章表单 '''
from flask_wtf import FlaskForm
from wtforms import (
StringField,
PasswordField,
BooleanField,
TextAreaField,
SelectField,
SubmitField,
)
from wtforms.validators import (
Required,
Length,
Email,
R... |
991,955 | c51c2a71c12e71e79c5198d00440b896d4df478f | import pygame
class Images:
def __init__(self):
self.images = dict()
self.dir = "resources/images/"
def get(self, path):
image = self.images.get(path)
if (image == None):
image = pygame.image.load(self.dir + path)
self.images[path] = image
return ... |
991,956 | f38861d383610a78dc783ed59459c0f311b9e25f | import random # for rolling dice randomly
N = 2 # number of dice
L = 870 # number of throws
# Rolls N dice randomly and returns their values
def rollDice(N):
outcomes = []
for i in range(0,N):
outcomes.append(random.randint(1,6))
return outcomes
# Checks is a number even or not. Ret... |
991,957 | aacceba520352c6651f9d41a919d5323a980a738 | class HVAC(object):
def __init__(self):
self.blower = Blower()
self.coil = Coil()
self.staticPressure = 0.0 # Pa
return
class Blower(object):
# performance curves
# static pressure vs CFM
# brake horsepower vs CFM
def __init__(self):
return
class Coil(obje... |
991,958 | f7c3ef8315427725519ad834056d4e472e8dfb7e | import os
import sys
from Parser import Parser
from FlowControl import FlowControl
if __name__ == "__main__":
vmFiles = []
completePath = sys.argv[1]
if os.path.isdir(completePath) and not completePath.endswith("/"):
completePath = completePath + "/"
filePath, fileName = os.path.split(compl... |
991,959 | c275124153f9925e6ad9dc46f9bde3f178d9a43c | from django.contrib.auth.models import Group
from dalme_app.models import Set
from django.contrib.auth.models import User
from rest_framework import serializers
from ._common import DynamicSerializer
from dalme_api.serializers.users import UserSerializer
from dalme_api.serializers.others import GroupSerializer
from dja... |
991,960 | c5dba6e8afe2fcdb484edcb1c283ae895392196f | #!/usr/bin/env python
"""
Intro
Something I've played around with in recreational mathematics has been construction of a divisor table to visually compare/contrast the prime divisors of a set of numbers. The set of input numbers are across the top as column labels, the prime divisors are on the left as row labels, an... |
991,961 | a2f19627da70d671fe3c1d3c94e32208435697bd | import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import more_itertools as mit
import time
class UpdateMap:
#def __init__(self, link_uri):
def __init__(self):
# Initializations
x_map = [0, 0, 140, 140, 163, 163, 428, 428, 450, 450, 715, 715, 738, 738, 1002, 1002, 1025, 1025... |
991,962 | d828bc2a49ff51069c9ad3b0cf928e976e5709cb | from django.contrib import admin
from .models import Level, Objective, Profile, Project, Vehicle, VehicleType
# Register your models here.
@admin.register(Level)
class LevelAdmin(admin.ModelAdmin):
fields = ("name","transform", "project_id", "date_created", "date_modified", "level_id", "roads", "structures", "reco... |
991,963 | f4b427a23e7274ee6fc78dd6f82c7c1d01dc99c3 | #!/usr/bin/env python3
import sys
import re
from math import sqrt, degrees
class Record:
def __init__(self, planet, jd, x, y, z, vx, vy, vz):
self.planet = planet
self.jd = jd
self.x = x
self.y = y
self.z = z
self.vx = vx
self.vy = vy
self.vz = vz
de... |
991,964 | 12e52ffc5571252c3ed4f1e8464ccddc5db57908 | """"
HTTP object - gets http requests and send the
"""
class HTTP:
def __init__(self):
"root path should be the full path, if its in the same folder .\\"
self.packet = "" # should be the all packet with the headers.
self.request = "" # request should be
def get_request(sel... |
991,965 | 1b8755fe9343e4e689dcf3e59eb7d35c8eee9b80 | #!/usr/bin/env python
from flask import Flask, render_template, Response
import cv2
from balloon_finder import BalloonFinder
app = Flask(__name__)
@app.route('/')
def index():
"""Video streaming home page."""
return render_template('index.html')
def gen():
"""Video streaming generator function."""
b... |
991,966 | c0839b78182b84f1788b404decee987456845261 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 Nebula, Inc.
#
# 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
#
# ... |
991,967 | a533645028c4f13582950f0f653073ff860ae858 | import boltzpy as bp
import numpy as np
import matplotlib
matplotlib.use('Qt5Agg')
matplotlib.rcParams['text.usetex'] = True
matplotlib.rcParams['text.latex.preamble'] = r'\usepackage{amsmath, amssymb, faktor}'
import matplotlib.pyplot as plt
from fonts import fs_title, fs_legend, fs_label, fs_suptitle, fs_ticks
'''
N... |
991,968 | 9b7b082fa45f8b86c480abf295d0d722362eb9da | from os import listdir
import fnmatch
count = dict() # count of malwares classified to different families
percentage = dict() # percentage of malwares classified to different families
num_files = 0 # number of XXXXXXXXX malware files
# list of malware families to be classified as
families = [f for f in listdir("/d... |
991,969 | 59755f501d363ed9d3f1399c092123c7ff1b2287 | def aumenta (preco = 0, taxa = 0):
res = preco + (preco * taxa/100)
return res
def diminuir(preco=0, taxa=0):
res = preco - (preco * taxa / 100)
return res
def dobro(preco):
res = preco * 2
return res
def metade(preco):
res = preco / 2
return res
|
991,970 | 598bb317cba5dd4b8727b562e4ede7683746698d | # -*- coding: utf-8 -*-
import socket
import time
import signal
import csv
import os
import json
from nGle_util import nGle_util
class set_file_members:
def __init__(self):
self.ngle = nGle_util()
def set_file(self, address='localhost', datas=list()):
file_name = "nGle_sys_{}_{}".format(address, self.ngle.get... |
991,971 | fc46174bbdfa009cb66e2f57ef15012fad45cbc9 | from models import CrawlerDocument
from mongoengine import connect
from threading import Thread, Lock
from elasticsearchcli import ElasticSearchCli
import logging
from mongoengine import register_connection
logging.basicConfig(level = logging.DEBUG)
'''
Class is responsible for managing the index
'''
class IndexC... |
991,972 | fefcf35e48abd3f9e0c4b1f65173bc06c54f1290 |
'''
Creating a Rule-Based Expert System
Authors:
Aaditya Arigela
INSTRUCTIONS:
Simply run command :- python RuleEngine.py
Future work:
- Write advanced rules to enhance Knowledge base
- Develop a user interface to produce a deliverable system.
NOTE: The rules are written in plain Engl... |
991,973 | faec801407c17cca851f9023fa117360920e4992 | #!/usr/bin/env python3
import logging
import os.path
from modelLang import parsers, backends
from modelLang.parsers import Parser
from modelLang.backends import Z3Backend
class FromFileTest():
testfile = "tests/statements/fromfile.lmod"
@staticmethod
def run():
parser = Parser(pwd=os.path.dirnam... |
991,974 | 1984179e66cdf29c05fa943e804c16047970ca2b | from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth import get_user_model
from django import forms
class LoginForm(AuthenticationForm):
pass
class RegisterForm(UserCreationForm):
first_name = forms.CharField(max_length=30, widget=forms.TextInput())
last_na... |
991,975 | f97b8d7195f2630ab663449e6594b967acb466c9 | import numpy as np
import random
import matplotlib.pyplot as plt
import math
import pandas as pd
import os
import xlsxwriter
from os import system
import PyInquirer as inquirer
from time import perf_counter
######## CREACION DE LOS GENERADORES ########
def big_bang():
for i in range(p):
#... |
991,976 | d2025f0059e12b72e9f2062bae15845a29a9c4fd | from django.views import generic
from django.core.urlresolvers import reverse
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from .models import User... |
991,977 | e816eff269d00243510733ea50c29bd004a11d1a | import ConfigParser as cParser
import os, keyring
import slicer, ctk, qt
from pg8000 import DBAPI as sql # Move to QADatabase._getDatabaseType()
import Resources
from QualityAssuranceLib import *
Resources.derived_images.printButton("THIS IS A TEST")
class QAModule(object):
"""
Class to contain parameters ... |
991,978 | f1f435edd69d35675afdd8f139c083091e0d5a88 | """
Forming limig diagram predictive tool on the basis of
macro-mechanical constitutive models using anisotropic yield function
and hardening curve.
Adapted from FB's forming limit calculation subroutine/algorithm
Youngung Jeong
--------------
youngung.jeong@gmail.com
younguj@clemson.edu
-----------------------------... |
991,979 | 24af07b48b56a926b8035a5902321f7edf82bd54 | '''
Created on 16 Oct 2017
'''
owire_get_out_schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Neuron_Instruction",
"type": "object",
"properties": {}
}
owire_get_out_example = {"dev": "temp", "circuit": "1_01", "address": "abcdefgh", "typ": "DS9999"}
owire_post_inp_schema =... |
991,980 | 17b622bd3071eaf8b145d915e5eafecd7b4c5364 | import json
from celery import shared_task
from core.startSshProcess import start_process_on_device, check_host
from .models import ResultWorkForTaskManager
@shared_task
def get_data_for_task_manager(data: dict) -> dict:
""" We receive data to form a state about the operation of a remote device.
Example: ssh ... |
991,981 | 746a4fe1f774765f7879694dfbe682db71cf3f9b | #!/usr/bin/env python3
# Copyright 2009-2017 BHG http://bw.org/
x = 0x0a
y = 0x02
z = x & y # and: common
print(f'(hex) x is {x:02x}, y is {y:02x}, z is {z:02x}') # hexadecimal(x): 0-15(16 jin zhi)
print(f'(bin) x is {x:08b}, y is {y:08b}, z is {z:08b}')
x = 0x0a
y = 0x05
z = x | y # Or
print(f'(hex) x is {x:02x}, ... |
991,982 | a05313f1ddf208736617f87bee0fba16b2a1bc74 | from flask import Flask, render_template, redirect, request, make_response
from urllib.parse import urlencode
from secret import client_id, client_secret
import requests
from flask_mobility import Mobility
app = Flask(__name__)
Mobility(app)
# REDIRECT_URI = "http://127.0.0.1:5000/authorize"
REDIRECT_URI = "https://st... |
991,983 | 1ecfecc7df49a6cea29efa8f7a386b058830c63d | import sys
sys.path.append('..')
from sklearn import metrics
from sklearn.svm import SVC
from sklearn.preprocessing import label_binarize
import numpy as np
import os
from load_data import load_data_small
from baseline import SVM_recommend_run
from pre_process import pre_process
from configs import *
def evaluateSc... |
991,984 | 6ddbf83bf816022efb6acbfce161e79e58a23d82 | filePath = 'pi_digit.txt'
with open('pi_digit.txt') as f:
read = f.read()
print(read)
print()
with open(filePath) as fileContent:
lines = fileContent.readlines()
for line in lines:
print(line.rstrip()) |
991,985 | 1580c651f1f5de37f52e8802d14478c7db360f55 | # @Author : 小杜同学
# @Email : anmutu@hotmail.com
# @Github : www.github.com/anmutu
# @怎么肥四 : https://www.zmfei4.com
# @Time : 2020/5/19 2:27
# https://leetcode-cn.com/problems/move-zeroes/
# 给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
# example
# 输入: [0,1,0,3,12]
# 输出: [1,3,12,0,0]
# 删除追加法
d... |
991,986 | 15ea9495eea1af0eeb67cca3e0417e7df596b5fc | # Copyright 2017 Balazs Nemeth, Mark Szalay, Janos Doka
#
# 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 o... |
991,987 | 7bc1584729d7f939e3a0e6325bc2e0b425f8690f | # Generated by Django 2.1.5 on 2019-04-26 15:11
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('geneseekr', '0023_auto_2... |
991,988 | 08e9207eada50989571dc2f1a8b5a1bca18b20ea | import os
import hashlib
import dill
import xxhash
import numpy as np
import pandas as pd
from pandas.util import hash_pandas_object
from . import exception
from . import save_file
from . import operator
from . import param_holder
from . import constant
class CalcNode:
""" Node of Calculation Graph
Args:
... |
991,989 | 103f88a0f240784f381a55e9270651e6a312c75f | import heapq
import sys
N = int(sys.stdin.readline())
heap = []
for n in map(int, sys.stdin.readline().split()):
heapq.heappush(heap, n)
for _ in range(1, N):
for n in map(int, sys.stdin.readline().split()):
heapq.heappush(heap, n)
heapq.heappop(heap)
print(heapq.heappop(heap)) |
991,990 | b2a42b47413c86c0775905a354563ae70901661b | import requests
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.image as mpimg
data_urls = {
'covid19_by_area_type_hosp_dynamics': 'https://github.com/VasiaPiven/covid19_ua/raw/master/covid19_by_area_type_hosp_dynamics.csv',
'covid19_by_settlement_actual': 'https://github.com/Vasi... |
991,991 | c0f194c3fefb60d800eca725d6e1eeea13a3513d | import numpy as np
import pandas as pd
import statsmodels.api as sm
import patsy as pt
import sklearn.linear_model as lm
# загружаем файл с данными
df = pd.read_csv("http://roman-kh.github.io/files/linear-models/simple1.csv")
# x - таблица с исходными данными факторов (x1, x2, x3)
x = df.iloc[:, :-1]
# y - таблица с и... |
991,992 | 9b30136eb350061dc7a6d9e3725b6bbb82269897 | # -*- coding: utf-8 -*-
"""
Created on Sun Oct 18 21:02:11 2020
@author: Hisana
"""
import pygame
from random import randint
from pygame import mixer
pygame.init()
GD = pygame.display.set_mode((1000, 700))
w = 1000
h = 700
pygame.display.set_caption("S & L BY BRAIN STEAKS")
# change color if u want
headcolor = (255... |
991,993 | 0450ee9beb707f35fa2f7f75d251bee6427547d0 | # coding: utf-8
from __future__ import absolute_import, unicode_literals
import json
from gaecookie.decorator import no_csrf
from config.template_middleware import TemplateResponse
from models import Quest, Game
from gaepermission.decorator import login_required
@no_csrf
@login_required
def index(_logged_user, game_... |
991,994 | 05a0e9bc5103f81cc9f627cd342b18558698384b | canciones = {125:['River', 'Leon Bridges', {'R&B'}],
1458: ['My Silver Lining', 'First Aid Kit', {'Folk', 'Rock'}],
1502: ['Stay Gold', 'First Aid Kit', {'Folk', 'Rock'}],
32: ['Sinnerman', 'Nina Simone', {'R&B', 'Jazz'}]
}
mensual = [(1502, 607), (125, 54), ... |
991,995 | 33a06358414704f826ce1729c721434d9d41e825 | #!/usr/bin/python3
"""
Update data/papers.json
"""
from datetime import datetime
import re
import os
import json
BIBTEX_PATTERN = re.compile(r'(?P<key>\w+)=\{(?P<value>.*?)\}')
WANTED_FIELDS = ['title', 'author', 'journal']
PAPER_STORE = os.path.join('data', 'papers.json')
def parse(line):
match = BIBTEX_PATTERN.... |
991,996 | 2b38c84fb20efeacdd3a3a43211e7a925ef0aef1 |
# Create your views here.
#cyy
from pki import accessProtocol, sm2, SRT_G, contractTAC
from django.contrib.auth.decorators import login_required
from django_redis import get_redis_connection
from django.shortcuts import render,redirect
from pki.models import models
from web3 import Web3
from django.http import Ht... |
991,997 | 79c6fd96ee3fa40e17e393494783294e2869252f | """Module for validating pudl etl settings."""
import itertools
import json
from enum import Enum, unique
from typing import ClassVar
import fsspec
import pandas as pd
import yaml
from dagster import Any, DagsterInvalidDefinitionError, Field
from pydantic import AnyHttpUrl
from pydantic import BaseModel as PydanticBas... |
991,998 | 17f45ba79a07f291285222ee355270923d6a32ab | def count4(n):
c=0
while(n>0):
if n%10 == 4:
c+=1
n/=10
return c
t=input()
while (t > 0):
t-=1
n=input()
print count4(n)
|
991,999 | 297de354dc8f464ca319f925a3d221de9153fdb9 | """
This script is used to create the HDF5 training and validation dataset files.
"""
import sys
sys.path.append('..')
import os
import json
import pickle
import h5py
import numpy as np
from collections import Counter
import pandas as pd
from gensim import corpora
from gensim.models.doc2vec import Doc2Vec, TaggedDocume... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.