index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
4,300 | 7d3264e9a90ebd72439f77983cbf4f9755048a85 | import requests,cv2,numpy,time,imutils
class imageAnalyzer():
def __init__(self,
roverName="Rover03",
url="http://192.168.1.10:5000/api/",
temp_img_path = "./temp",
):
self.url = url + roverName
self.temp_img_path = ... |
4,301 | b6e4214ace89165f6cfde9f2b97fcee8be81f2ed | # coding=utf-8
# Copyright 2019 SK T-Brain Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
4,302 | d0e5cfc7b619c2eaec19248619d7d59e41503c89 | a=[i for i in range(10)]
del a[0]
print a
del a[-1]
print a
del a[1]
print a
del a[0:2]
print a
del a[1:3:1]
print a
#test del all
del a[:]
print a
a.append(1)
print a
# Make sure that del's work correctly in sub-scopes:
x = 1
def f1():
x = range(5)
def f2():
del x[1]
return f2
f1()()
|
4,303 | 90d792fe18e589a0d74d36797b46c6ac1d7946be | # The purpose of this module is essentially to subclass the basic SWIG generated
# pynewton classes and add a bit of functionality to them (mostly callback related
# stuff). This could be done in the SWIG interface file, but it's easier to do it
# here since it makes adding python-specific extensions to newton easier.
... |
4,304 | a727502063bd0cd959fdde201832d37b29b4db70 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-02-10 11:06
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('album', '0013_auto_20160210_1609'),
]
operations = [
migrations.CreateModel(... |
4,305 | 1ed7dba63db38e53a1dc5fac3c36f0dd98075c1f | from datetime import *
import datetime
import time
time_one = datetime.time(1, 2, 3)
print("Time One :: ", time_one)
time_two = datetime.time(hour=23, minute=59, second=59, microsecond=99)
print("Time Two :: ", time_two)
date_one = datetime.date(month=3, year=2019, day=31)
print("Date One :: ", date_one)
today = dat... |
4,306 | 3dc2d9a5e37ce1f546c0478de5a0bb777238ad00 | from pynput.keyboard import Listener
import logging
import daemon
import socket
import thread
logging.basicConfig(format="%(asctime)s:%(message)s")
file_logger = logging.FileHandler("/home/user0308/logger.log", "a")
logger = logging.getLogger()
logger.addHandler(file_logger)
logger.setLevel(logging.DEBUG)
def press(... |
4,307 | 18aafb71d7e6f5caa2f282126c31eb052c08ad3c | import errno
import os
import shutil
from calendar import monthrange
from datetime import datetime, timedelta
from pavilion import output
from pavilion import commands
from pavilion.status_file import STATES
from pavilion.test_run import TestRun, TestRunError, TestRunNotFoundError
class CleanCommand(commands.Command... |
4,308 | c9de51ee5a9955f36ecd9f5d92813821fb68fb3d | import argparse
import os
import shutil
import time, math
from collections import OrderedDict
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
import torchvision.datasets as datasets
im... |
4,309 | e1913c80375e4871119182d0267e9f228818624f | # Obtener en otra lista unicamente números impares:
my_list = [1, 4, 5, 6, 9, 13, 19, 21]
# Vamos a hacer una list comprehension:
lista_impares = [num for num in my_list if num % 2 != 0]
print(my_list)
print(lista_impares)
print('')
# Vamos a usar filter:
lista_pares = list(filter(lambda x: x % 2 == 0 , my_list))
p... |
4,310 | 234aad868ea71bbe476b303bcff37221820f1d90 | import os
import time
import json
import click
import click_log
import logging
from flightsio.scraper import FlightScraper
logger = logging.getLogger(__name__)
click_log.basic_config(logger)
@click.group()
def main():
"""
An empty click group, required in order to bundle the other commands.
"""
pass... |
4,311 | f1021bfbf11886a01a84033b880d648c3286856b | # -*- coding: utf-8 -*-
#!/usr/bin/env python
from subprocess import call
def query_DB_satellites(outputpath="../data/", user="anonimo", passwd="secreto"):
"""
Queries the multidark database to extract all the haloes in the box within a ID range.
The output is stored as an ascii (CSV) file.
"""
#... |
4,312 | 47c5375816ab35e8225e5f3695f7ee2ab5336076 | DEFAULT_SIZE = 512
class DataEncoding:
@staticmethod
def segment_decode(segment):
arr = bytearray(segment)
ack_binary = bytearray([arr[i] for i in range(4)])
tip_binary = bytearray([arr[4]])
len_binary = bytearray([arr[i] for i in (5,6)])
ack = int.from... |
4,313 | 71b78b1347456420c3fc29605887d20ba5bff06e | from zeus import auth, factories
from zeus.constants import Result, Status
from zeus.models import FailureReason
from zeus.tasks import aggregate_build_stats_for_job
def test_unfinished_job(mocker, db_session, default_source):
auth.set_current_tenant(auth.Tenant(repository_ids=[default_source.repository_id]))
... |
4,314 | d959ed49a83fb63e0bce31b5c81c013f0986706b | #!/usr/bin/python
# Developed by Hector Cobos
import sys
import csv
import datetime
def mapper():
# Using a reader in order to read the whole file
reader = csv.reader(sys.stdin, delimiter='\t')
# Jump to the next line. We want to avoid the line with the name of the fields
reader.next()
# loop
for line in reade... |
4,315 | ccba923fa4b07ca9c87c57797e1e6c7da3a71183 | import time #melakukan import library time
import zmq #melakukan import library ZeroMQ
context = zmq.Context() #melakukan inisialisasi context ZeroMQ pada variable context
socket = context.socket(zmq.REP) #menginisialisasikan socket(Reply) pada variable context(ZeroMQ)
socket.bind("tcp://10.20.32.221:5555") #melakuka... |
4,316 | 36e538ca7fbdbf6e2e6ca1ae126e4e75940bb5cd | def check_orthogonal(u, v):
return u.dot(v) == 0
def check_p():
import inspect
import re
local_vars = inspect.currentframe().f_back.f_locals
return len(re.findall("p\\s*=\\s*0", str(local_vars))) == 0
|
4,317 | c27c29a5b4be9f710e4036f7f73a89c7d20acea5 | class String:
def reverse(self,s):
return s[::-1]
s=input()
obj1=String()
print(obj1.reverse(s)) |
4,318 | 6c8180d24110045348d9c2041c0cca26fa9ea2d2 | # OSINT By FajarTheGGman For Google Code-in 2019©
import urllib3 as url
class GCI:
def banner():
print("[---- OSINT By FajarTheGGman ----]\n")
def main():
user = str(input("[!] Input Name Victim ? "))
init = url.PoolManager()
a = init.request("GET", "https://facebook.com/" + user)
b = init.re... |
4,319 | 8bf75bf3b16296c36c34e8c4c50149259d792af7 | import sys
try:
myfile = open("mydata.txt",encoding ="utf-8")
except FileNotFoundError as ex:
print("file is not found")
print(ex.args)
else:
print("file :",myfile.read())
myfile.close()
finally :
print("finished working")
|
4,320 | 77f37a80d160e42bb74017a55aa9d06b4c8d4fee | # !/usr/bin/python
# coding:utf-8
import requests
from bs4 import BeautifulSoup
import re
from datetime import datetime
#紀錄檔PATH(建議絕對位置)
log_path='./log.txt'
#登入聯絡簿的個資
sid=''#學號(Ex. 10731187)
cid=''#生份證號(Ex. A123456789)
bir=''#生日(Ex. 2000/1/1)
#line or telegram module
#platform='telegram'
platform='line'
if plat... |
4,321 | 68d9f77f91a13c73373c323ef0edbe18af9990a3 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from celery import Celery
app = Celery('task', include=['task.tasks'])
app.config_from_object('task.config')
if __name__ == '__main__':
app.start()
|
4,322 | c64e41609a19a20f59446399a2e864ff8834c3f0 | import tty
import sys
import termios
def init():
orig_settings = termios.tcgetattr(sys.stdin)
tty.setcbreak(sys.stdin)
return orig_settings
def get_input():
return sys.stdin.read(1)
def exit(orig_settings):
termios.tcsetattr(sys.stdin, termios.TCSADRAIN, orig_settings)
if __name__ == "__main... |
4,323 | 598c634aac1df951f544127e102a1e2d61cac0b0 | #!/usr/bin/env python
from time import sleep
from org.mustadroid.python.interleech import processPage
import MySQLdb
from org.mustadroid.python.interleech.item import Item
import re
import time
if __name__ == "__main__":
db = MySQLdb.connect(host = "localhost",
user = "interleech",
pa... |
4,324 | a5c9ff1fe250310216e2eaa7a6ff5cc76fc10f94 | import docker
import logging
import sys
if __name__ == '__main__':
# setting up logger
logging.basicConfig(stream=sys.stdout,
format='[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s',
level=logging.DEBUG)
# get the docker client
clie... |
4,325 | c218428908c28a8c65bd72e66dcddaf7db1909d7 | from __future__ import absolute_import
from talin.quotations import register_xpath_extensions
def init():
register_xpath_extensions() |
4,326 | 15bf84b716caf66a23706e9292b47ddb9bf4d35e | num = int(input("Enter the number: "))
print("Multiplication Table of", num)
for i in range(1, 10):
print(num,"a",i,"=",num * i)
|
4,327 | 0c7816028e6cbd12684b0c7484835e735f1d2838 | #!/usr/bin/env python3
import argparse
from glob import glob
import sys
import numpy as np
import matplotlib.pyplot as plt
import pysam
import math
import pandas as pd
import haplotagging_stats
import os
import collections
import seaborn as sns
NUM_CONTIGS="num_contigs"
TOTAL_LEN="total_len"
HAPLOTYPE="haplotype"
HAPL... |
4,328 | d2a9a2fd3a1118c0855b8f77ce4c25cc6b4e8f87 | import random
def get_ticket():
ticket = ''
s = 'abcdefghijkrmnopqrstuvwxyz1234567890'
for i in range(28):
r_num = random.choice(s)
ticket += r_num
return ticket
|
4,329 | f4fa7563d2cce5ee28198d4974a4276d9f71f20b | import sys
import pandas as pd
from components.helpers.Logger import Logger
class DataFrameCreatorBase:
"""
DataFrameCreatorBase
"""
START_DATE = "03/16/2020"
def __init__(self, input_file):
self._input_file = input_file
self.df = self._read_raw_csv()
self._clean_df()
... |
4,330 | 71cee06ce697030fd0cea363ddecaa411b39544d | from appConfig.App import app, db
import os
dbDir = os.path.dirname(__file__)
# staticFolder = '%sstatic' % os.sep
dbDir = '%s%sappConfig%smine.db' % (dbDir, os.sep, os.sep)
if not os.path.exists(dbDir):
# 创建数据库并创建表
db.create_all()
# app._static_folder = staticFolder
@app.route('/')
def hello_world():
... |
4,331 | 23937ae531cc95069a1319f8c77a459ba7645363 | # write dictionary objects to be stored in a binary file
import pickle
#dictionary objects to be stored in a binary file
emp1 = {"Empno" : 1201, "Name" : "Anushree", "Age" : 25, "Salary" : 47000}
emp2 = {"Empno" : 1211, "Name" : "Zoya", "Age" : 30, "Salary" : 48000}
emp3 = {"Empno" : 1251, "Name" : "Simarjeet", "Age"... |
4,332 | ba41f2a564f46032dbf72f7d17b2ea6deaa81b10 | from __future__ import unicode_literals
import abc
import logging
import six
import semantic_version
from lymph.utils import observables, hash_id
from lymph.core.versioning import compatible, serialize_version
logger = logging.getLogger(__name__)
# Event types propagated by Service when instances change.
ADDED = '... |
4,333 | 91d240b02b9d7a6c569656337521482d57918754 |
# https://github.com/jscancella/NYTribuneOCRExperiments/blob/master/findText_usingSums.py
import os
import io
from pathlib import Path
import sys
os.environ['OPENCV_IO_ENABLE_JASPER']='True' # has to be set before importing cv2 otherwise it won't read the variable
import numpy as np
import cv2
import subprocess
from ... |
4,334 | 1e87f625fb7bd9f9bf4233229332c909702954a5 | from helper import *
async def main(URL, buy_time):
browser, page = await get_window()
# 30s登陆时间
await page.goto('https://account.xiaomi.com/pass/serviceLogin?callback=http%3A%2F%2Forder.mi.com%2Flogin%2Fcallback%3Ffollowup%3Dhttps%253A%252F%252Fwww.mi.com%252F%26sign%3DNzY3MDk1YzczNmUwMGM4ODAxOWE0NjRiNTU... |
4,335 | edbb721784dff81e3e1ab5e0458a4080508807fe | # -*- coding:utf-8 -*-
import sys
from PyQt4 import QtGui,QtCore
import experiment
class Node(QtGui.QGraphicsEllipseItem):
def __init__(self,name):
super(Node, self).__init__()
self.__name = name
def getName(self):
... |
4,336 | 2c1e51f2c392e77299463d95a2277b3d2ca7c299 | print(1/2 * 2) # division ret
|
4,337 | 8339ac512d851ea20938a1fbeedcb751cb2b8a6a | from psycopg2 import ProgrammingError, IntegrityError
import datetime
from loguru import logger
from db.connect import open_cursor, open_connection
_log_file_name = __file__.split("/")[-1].split(".")[0]
logger.add(f"logs/{_log_file_name}.log", rotation="1 day")
class DataTypeSaveError(Exception):
pass
class ... |
4,338 | b6715ad42d59720eb021973394a0b7bfd540181b | from .standup import *
from .auth_register import *
from .channels_create import *
import pytest
# If channel does not exist
def test_notExisting_channel():
db.reset_DB()
auth_register('testmail@gmail.com', 'pas123456', 'Bob', 'Smith')
realtoken = Token.generateToken('testmail@gmail.com')
fake_channel = ... |
4,339 | f254f93193a7cb7ed2e55e4481ed85821cafcd7b | TOTAL = 1306336
ONE = {
'0': 1473,
'1': 5936,
'2': 3681,
'3': 2996,
'4': 2480,
'5': 2494,
'6': 1324,
'7': 1474,
'8': 1754,
'9': 1740,
'a': 79714,
'b': 83472,
'c': 78015,
'd': 61702,
'e': 42190,
'f': 68530,
'g': 48942,
'h': 63661,
'i': 34947,
'j': 24312,
'k': 26724,
'l': 66351,
'm': 77245,
'n': 36942,
'o': 40744,
'p': ... |
4,340 | 596ee5568a32c3044e797375fbc705e2091f35c2 | from functools import partial
import numpy as np
import scipy.stats as sps
# SPMs HRF
def spm_hrf_compat(t,
peak_delay=6,
under_delay=16,
peak_disp=1,
under_disp=1,
p_u_ratio = 6,
normalize=True,
... |
4,341 | 3788888a17e2598e781803f89cd63ac9c3219f59 | import os
import json
def load_json_if_exists(path):
if not os.path.isfile(path):
return {}
with open(path) as f:
return json.load(f)
def json_dump(obj, file_path):
with open(file_path, 'w') as f:
json.dump(obj, f)
def get_folder_paths(directory):
return [os.path.join(directo... |
4,342 | 59ddb85d55c342342be4edc1fc3b92af701fa6cc | import BST
tree = BST.BST(10)
tree.insert(5, tree.root)
tree.insert(15, tree.root)
tree.insert(25, tree.root)
tree.insert(12, tree.root)
tree.insert(35, tree.root)
print(tree.height(tree.root)) |
4,343 | d46035699bee1ad9a75ea251c2c3ab8817d6a740 | # Import packages
import pandas
import requests
import lxml
# Get page content
url = "https://archive.fantasysports.yahoo.com/nfl/2017/189499?lhst=sched#lhstsched"
html = requests.get(url).content
df_list = pandas.read_html(html)
# Pull relevant URLs
|
4,344 | 79e4592d5ea84cc7c97d68a9390eb5d387045cf0 | from functools import wraps
from time import sleep
def retry(retry_count = 2, delay = 5, action_description = 'not specified', allowed_exceptions=()):
def decorator(func):
@wraps(func) # to preserve metadata of the function to be decorated
def wrapper(*args, **kwargs):
for _ in range(re... |
4,345 | 4d0f612c74dc175766f489580fc4a492e1bfd085 | import pandas as pd
import math
import json
import html
import bs4
import re
import dateparser
from bs4 import BeautifulSoup
from dataclasses import dataclass, field
from datetime import datetime
from typing import Any, List, Dict, ClassVar, Union
from urllib.parse import urlparse
from .markdown import MarkdownData, Ma... |
4,346 | bedae2621bfcc64deb0d13d7cbce3cfb89720245 | from rest_framework import viewsets
from .models import *
from serializer import *
from django.http import HttpResponse
from django.views import View
from django.core import serializers
# Create your views here.
class ProyectoViewSet(viewsets.ModelViewSet):
queryset = Proyecto.objects.all()
serializer_class =... |
4,347 | eefd94e7c04896cd6265bbacd624bf7e670be445 | """
Given a sentence as `txt`, return `True` if any two adjacent words have this
property: One word ends with a vowel, while the word immediately after begins
with a vowel (a e i o u).
### Examples
vowel_links("a very large appliance") ➞ True
vowel_links("go to edabit") ➞ True
vowel_links("an... |
4,348 | 9969dcf820a5ff34b483593cd43e4dfba9588ed2 | import sys
from . import cli
def main() -> None:
try:
command = sys.argv[0]
args = sys.argv[1:]
cli.main(command, args)
except KeyboardInterrupt:
pass
|
4,349 | c455263b82c04fe2c5cc1e614f10a9962795f87e | """
Utilities for calculations based on antenna positions,
such as baseline and phase factor.
"""
import os
import numpy as np
import pickle
c = 299792458 # m / s
data_prefix = os.path.dirname(os.path.abspath(__file__)) + "/"
try:
ant_pos = dict(pickle.load(open(data_prefix + "ant_dict.pk", "rb")))
def base... |
4,350 | c0512a90b6a4e50c41d630f6853d1244f78debfb | #dict1 = {"я":"i","люблю":"love","Питон":"Рython"}
#user_input = input("---->")
#print(dict1[user_input])
#list1 =[i for i in range(0,101) if i%7 ==0 if i%5 !=0]
#print(list1)
#stroka = "я обычная строка быть которая должна быть длиннее чем десять символ"
#stroka1=stroka.split()
#dict1={}
#for i in stroka1:
# ... |
4,351 | 37d465043eddd34c4453fd7e31b08d0ba58b725f | #https://www.acmicpc.net/problem/2581
def isPrime(x):
if x==1:
return False
for d in range(1,int(x**0.5)):
if x==d+1:
continue
if x%(d+1)==0:
return False
else:
return True
N=int(input())
M=int(input())
sum=0
min=10001
for x in range(N,M+1):
if i... |
4,352 | 3cace66ddf8484d285c2b2a8fabbb83778a2c4af | from __future__ import division
import numpy as np
table = open("Tables\\table1.txt", "w")
table.write("\\begin{tabular}{|c|c|c|c|} \\hline\n")
table.write("Hidden Neurons & Loss & Training Acc. & Valid. Acc. \\\\ \\hline\n")
H = [1,5,10,11,12,20,40]
for h in H:
file = open("Out\\out-h"+str(h)+".txt", "r")
line = ... |
4,353 | e2682a5cab95914e7567431cb04c3fb542eda3bf | import numpy as np
import pandas as pd
import xgboost as xgb
from sklearn.metrics import confusion_matrix
USE_MEMMAP = True
data = pd.read_csv( 'dataset.csv' ).as_matrix()
X = data[ :, 0:-1 ]
y = data[ :, -1 ]
if USE_MEMMAP:
Xmm = np.memmap( 'X.mmap', dtype=X.dtype, mode='w+', shape=X.shape )
ymm = np.memmap( ... |
4,354 | 52513bf3f50726587bee800f118e2ac0fa00d98b | #!/usr/bin/env python
# -*- coding: utf-8 -*-
def quick_sort(a):
_quick_sort(a, 0, len(a)-1)
return a
def _quick_sort(a, lo, hi):
if lo < hi:
j = partition2(a, lo, hi)
_quick_sort(a, lo, j-1)
_quick_sort(a, j+1, hi)
def partition(a, lo, hi):
# simply select first element as... |
4,355 | f0702c8555ef07aac9e667c35b5b5fd85820ec54 | # from https://web.archive.org/web/20121220025758/http://xkcd.com/actuary.py.txt
# script written by Randall Munroe. Most comments by Emily Cain (although there were a few brief ones explaining how the program worked before I looked at it)
# Summary of program (by Emily):
# this program takes inputs of current ages ... |
4,356 | c18e452592d53f22858f2307c60aa997b809c3c3 | s = input()
st = '>>-->'
st2 = '<--<<'
sch1 = sch2 = 0
i = 0
j = 0
k = -1
while i != -1:
i = s.find(st, j)
if (k != i) and (i != -1):
k = i
sch1 += 1
j += 1
j = 0
i = 0
k = -1
while i != -1:
i = s.find(st2, j)
if (k != i) and (i != -1):
k = i
sch2 += 1
j += 1
prin... |
4,357 | 95a2f5abb37642651316a8954a4289e5b04e4916 | # Class 1: Flight which contains the flight number(f_id), its origin and destination, the number of stops between the
# origin and destination and the type of airlines(f_type)
class Flight():
# INIT CONSTRUCTOR
def __init__(self, f_id, f_origin, f_destination, no_of_stops, flight_type, p_id, p_type):
s... |
4,358 | 003976d850e371e01e6d0a307d3cf366f962c53d | from abc import abstractmethod
class BaseButton:
@abstractmethod
def render(self):
pass
@abstractmethod
def on_click(self):
pass
class WindowsButton(BaseButton):
def render(self):
print("Render window button")
def on_click(self):
print("On click")
class Ht... |
4,359 | bf133e73f0c842603dbd7cc3a103a2aa95e2236e | from Common.TreasureIsland import TIenv
from .Agent import TIagent
import torch
feature_size = (8, 8)
env = TIenv(frame_rate=0, num_marks=1, feature_size=feature_size)
agent = TIagent(feature_size=feature_size, learning_rate=0.0001)
EPISODE_COUNT = 50000
STEP_COUNT = 40
for episode in range(EPISODE_COUNT):
o... |
4,360 | d6cea40e907a0424b2b1b8162f19aa8203443e55 | n = int(input())
a = oct(n)
b = hex(n)
print(a[2:],b[2:].upper())
#.upper : 소문자 -> 대문자
|
4,361 | 9ba60270a4afcf242de53692afd8ebff7d9b37a7 | from abc import ABC
class Parent(ABC):
def printing(self):
print(self._words)
class Parent2(ABC):
form = "Parent2 Setup: %s"
class Child(Parent, Parent2):
def __init__(self, words):
self._words = self.form % words
super(Child, self).printing()
if __name__ == "__main__":
Child("hello world")
|
4,362 | cabebeb5ca02da2505df4a138e8b28f74dd108fa |
class ClickAction:
Click = 0
DoubleClick = 1
class MouseButton:
Left = 0
Right = 1
Middle = 2 |
4,363 | 350a79d6cead6814ad48292b14a204e753dc938c | # Testing
import sys, os
sys.dont_write_bytecode = True
import argparse, socket
from requestframe import RequestFrame
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--header-mutate-level", type=int, choices=range(11), nargs='?', help="Set the mutation level for the headers ... |
4,364 | b34e293b509328c728909262594bdf3d3ecf5360 | #!/usr/bin/env python2
# A basic example of sending Blue a command in cartesian space.
from blue_interface import BlueInterface
import numpy as np
import time
import sys
import argparse
import Leap
from utils.rotations import quat2euler, euler2quat, mat2euler
from utils.leap_listener import SampleListener
import mat... |
4,365 | 364d70fab02291bafadebea68fee94c0210e2de9 | """
Various utilities for neural networks implemented by Paddle. This code is rewritten based on:
https://github.com/openai/guided-diffusion/blob/main/guided_diffusion/nn.py
"""
import math
import paddle
import paddle.nn as nn
class SiLU(nn.Layer):
def forward(self, x):
return x * nn.functional.sigmoid(... |
4,366 | 431f109903e014a29aed7f125d47f327e17b9f65 | from django.http import HttpResponse
from django.shortcuts import get_object_or_404
from django.urls import reverse
from gatheros_event.views.mixins import AccountMixin
from gatheros_subscription.helpers.extract import (
create_extract,
get_extract_file_name,
)
from gatheros_subscription.models import Subscrip... |
4,367 | 591d0a166af5b8d0bed851c2f56ecc3da4f3a5eb | """
Generates a temperature celsius to fahrenheit conversion table
AT
11-10-2018
"""
__author__ = "Aspen Thompson"
header = "| Celsius | Fahrenheit |"
line = "-" * len(header)
print("{0}\n{1}\n{0}".format(line, header))
for i in range(-10, 31):
print("| {:^7} | {:^10.10} |".format(i, i * 1.8 + 32))
|
4,368 | 883d2efeb6d7d43cf82eef2e0397110fd8e3ea03 | # Copyright 2022 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
4,369 | 098c91f4aa367cb389e542c0199b633e7ecd4003 | from ccapi.interfaces.bitfinex import Bitfinex
from ccapi.interfaces.bittrex import Bittrex
from ccapi.interfaces.poloniex import Poloniex
from ccapi.interfaces.bithumb import Bithumb
from ccapi.interfaces.coinone import Coinone
from ccapi.interfaces.korbit import Korbit
# from ccapis.interfaces.coinbase import Coinbas... |
4,370 | 03b38e6e2d0097d5d361b0794aba83b8e430323d | from .storage import Storage
class ConnectionManager:
def __init__(self):
self.store = Storage()
def handle(self,msg):
if msg['type'] in {'register', 'heartbeat'}:
self.store.reg_hb(**msg['payload'])
elif msg['type'] == 'result':
self.store.result(msg['payload']... |
4,371 | 6fe22b3f98bff1a9b775fce631ae94a4ee22b04c | """Sorting components: peak waveform features."""
import numpy as np
from spikeinterface.core.job_tools import fix_job_kwargs
from spikeinterface.core import get_channel_distances
from spikeinterface.sortingcomponents.peak_localization import LocalizeCenterOfMass, LocalizeMonopolarTriangulation
from spikeinterface.sor... |
4,372 | 599310cfd05be28445535bc72251128ed72a9069 | class Node:
def __init__(self, value, next=None):
self.value = value
self.next = next
def __str__(self):
values = []
iter = self
while iter != None:
values.append(iter.value)
iter = iter.next
return ' -> '.join(values)
@staticmetho... |
4,373 | e35a106a3852a7a004fdae6819d4075e1fe929d6 | __author__ = 'Orka'
from movie_list import MovieList
from movie_random import MovieRandom
from remove_chosen_movie_from_list import RemoveChosenMovieFromList
from save_list_to_CSV import SaveListToCSV
from length_limit import LengthLimit
file_name = 'cinema.csv'
function = 'r+'
filename_save = 'cinema.csv'
f... |
4,374 | e3fe77867926d9d82963c8125048148de6998e2b | from enum import Enum
class ImageTaggingChoice(str, Enum):
Disabled = "disabled",
Basic = "basic",
Enhanced = "enhanced",
UnknownFutureValue = "unknownFutureValue",
|
4,375 | 4c8e3c21dd478606cf09f2e97dc9deed6597dae5 | import hashlib
import sys
def getHashcode(string):
for i in range(10000000000):
hash_md5 = hashlib.md5(str(i).encode('utf-8'))
res = hash_md5.hexdigest()
if res[0:len(string)] == string:
print(i)
exit()
if __name__ == '__main__':
getHashcode(sys.argv[1]) |
4,376 | c3ecac1c0facbf6f0905bb03fd337a7f4f5bbeff | from django.shortcuts import render
from .models import Votings
from .serializers import VotingsSerializer
from rest_framework.response import Response
from rest_framework import status
from rest_framework.decorators import api_view
import requests, json
@api_view(['GET'])
def votings(request):
votings = Votings.o... |
4,377 | c60971b3b0649fce8c435813de4a738f4eacda27 | import pandas as pd
import notification
def modify(nyt_url, jh_url):
# read data from both sources into a dataframe
# remove unwanted data, formats, and filters
# join dataframes on index
try:
nyt_df = pd.read_csv(nyt_url,
header=0,
nam... |
4,378 | eca4abf706fd094a40fdfc8ea483d71b0a018ce9 |
import sys
from .csvtable import *
from .utils import *
from .reporter import Reporter
class ColumnKeyVerifier:
def __init__(self):
self.keys = {}
def prologue(self, table_name, header):
if 0 == len(header):
return False
# 키는 첫번째 컬럼에만 설정 가능하다.
return header[0].is_... |
4,379 | 01626772b0f47987157e9f92ba2ce66a0ec2dcb4 | # socket_address_packing.py
import binascii
import socket
import struct
import sys
for string_address in ['192.168.1.1', '127.0.0.1']:
packed = socket.inet_aton(string_address)
print('Originale :', string_address)
print('Impacchettato:', binascii.hexlify(packed))
print('Spacchettato :', socket.inet... |
4,380 | 64ed3c512894902f85d619020b78338e228dddb6 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# FISL Live
# =========
# Copyright (c) 2010, Triveos Tecnologia Ltda.
# License: AGPLv3
from os.path import *
from datetime import datetime
from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.... |
4,381 | 952f8341f0fcbe6f3f3d1075ce345e61967a4336 | from setuptools import setup
setup(name='gym_asset_allocation',
version='0.0.1',
install_requires=['gym','numpy','pandas','quandl'] # And any other dependencies
) |
4,382 | e1ab4b034c949b8158c6ccc1e8e3f4a960a38c72 | import torch.nn as nn
import torch
from torch.distributions.categorical import Categorical
import torch.nn.functional as F
from torch.optim import Adam
import gym
import numpy as np
Device = torch.device("cuda:0")
class ActorCriticNet(nn.Module):
def __init__(self, observation_space, action_space,
... |
4,383 | c22b37bff74de7ea99f2009652dd00e57bb316b8 | '''
HTTP Test for channel details
'''
import sys
sys.path.append('..')
from json import load, dumps
import urllib.request
import urllib.parse
import pytest
PORT_NUMBER = '5204'
BASE_URL = 'http://127.0.0.1:' + PORT_NUMBER
#BASE_URL now is 'http://127.0.0.1:5321'
@pytest.fixture
def register_loginx2_create_invite():
... |
4,384 | 738e6d4d608aa977094420a432cbd8a05ea8a1b5 | import math
import numpy as np
import basis.robot_math as rm
import grasping.annotation.utils as gu
from scipy.spatial import cKDTree
def plan_contact_pairs(objcm,
max_samples=100,
min_dist_between_sampled_contact_points=.005,
angle_between_contact_... |
4,385 | a55d1286485e66a64aa78259ad1b1922c5c4c831 | from typing import *
class Solution:
def isMonotonic(self, A: List[int]) -> bool:
flag= 0
for i in range(1,len(A)):
diff=A[i]-A[i-1]
if diff*flag<0:
return False
if flag==0:
flag=diff
return True
sl=Solution()
inp=[1,2,2,2... |
4,386 | 21d499555b4bc4944996a57ae544a56aa317b00b | for t in range(int(input())):
st = list(input())
N,j = len(st),1
for i in range(N//2):
if st[i]=='*' or st[-i-1]=='*':
break
elif st[i] != st[-i-1]:
j=0
break
print('#{} Exist'.format(t+1)) if j else print('#{} Not exist'.format(t+1)) |
4,387 | 309f8016dfebcc3595291b127edb4634f72298ec | # -*- coding: utf-8 -*- #
import time
from openerp.osv import osv, fields
import logging
import openerp.addons.decimal_precision as dp
logger = logging.getLogger(__name__)
class ebiz_supplier_account_create(osv.osv_memory):
_name = 'ebiz.supplier.account.create.wizard'
_description = "Ebiz Supplier Account"
... |
4,388 | e67cbddf10440e8a31373e05a82840677d3045f5 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2018-12-20 13:06
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('login', '0006_usermovies_img'),
]
operations = [
migrations.AddField(
... |
4,389 | 24e486edc6f80e0b7d58b5df898e6d34f53111c8 | from pyloom import *
import random
import string
alphabet = string.ascii_letters
def random_string(N):
return ''.join([random.choice(alphabet) for _ in range(N)])
class TestBloomFilter(object):
def test_setup(self):
bf = BloomFilter(1000)
assert 10 == bf._num_hashes
assert 14380 ==... |
4,390 | fd76a7dd90bac7c7ba9201b6db62e6cb3eedeced | import mysql.connector
from getpass import getpass
tables_schema = {
"Country": "SELECT 'Id','Name','Code' " +
"UNION ALL " +
"SELECT Id, Name, Code ",
"Indicator": "SELECT 'Id','Name','Code' " +
"UNION ALL " +
"SELECT Id, Name, Code ",
"Year": "SELECT 'Id','FiveYearPe... |
4,391 | 16e10db90a0a0d8ee7ca5b0c7f86cc81432d87d1 | import webbrowser as wb
points = 0
import time as t
import pyautogui as pg
name = pg.prompt("What is your name? ").title()
pg.alert(name)
if name == "Caroline":
pg.alert ("Hi " + name)
points += 5
t.sleep(1)
wb.open ("https://www.textgiraffe.com/Caroline/Page2/")
elif name == "Bob":
... |
4,392 | 9fc184fe3aa498138138403bef719c59b85b3a80 | import json
def main():
with open('./src/test/predictions.json', 'r') as f:
data = json.load(f)
total = len(data['label'])
google = 0
sphinx = 0
for i in range(len(data['label'])):
label = data['label'][i]
google_entry = data['google'][i]
sphinx_entry = data['p... |
4,393 | 2d7431996bc8d1099c08fddc815b4706deb4f023 |
from arcade.sprite_list.sprite_list import SpriteList
import GamePiece as gp
from Errors import *
class GameConfig:
WINDOW_TITLE = "MyPyTris"
SCREEN_WIDTH = 450
SCREEN_HEIGHT = 900
BLOCK_PX = 45 # 45px blocks on screen
SPRITE_PX = 64 # 64px sprite
BLOCK_SCALE = BLOCK_PX/SPRITE_PX # sprite scal... |
4,394 | 1721bba2cae1e330bffeb9df05341df9522ff885 | import ROOT
from PhysicsTools.NanoAODTools.postprocessing.framework.datamodel import Collection
from PhysicsTools.NanoAODTools.postprocessing.framework.eventloop import Module
from TreeProducer import *
from TreeProducerCommon import *
from CorrectionTools.PileupWeightTool import *
from CorrectionTools.BTaggingTool i... |
4,395 | 7e83d11bb43229eaa199514b4be6a0acf3ab36ce | def lengthOfLongestSubstring(s):
max_len = 0
for i in range(len(s)):
storage = set()
count = 0
for j in range(i, len(s)):
if not s[j] in storage:
storage.append(s[j])
count += 1
else:
break
max_len = max(max_... |
4,396 | 870d260b58c10e0379d66c3b44bc45594ff7d666 |
def solve():
valid_passes = 0
with open('.\day4.txt') as fp:
for line in fp.read().strip().splitlines():
list_of_words = set()
add = 1
for word in line.split():
modified_word = ''.join(sorted(word))
if modified_word in list_of_words:
... |
4,397 | f1547e0893ce9c4661b546e49f3fc998745390d9 |
from collections import OrderedDict
import tcod.event
from components import Entity, PaperDoll, Brain
from components.enums import Intention
from engine import GameScene
from scenes.list_menu_scene import MenuAction, ListMenuScene
from systems.utilities import set_intention, retract_intention
def run(scene: GameS... |
4,398 | fbbf27f063f6d866e5d0b1210ea9acaebb3bdfb4 | from django.shortcuts import render, get_object_or_404
from django.template.loader import render_to_string
from django.http import JsonResponse
from django.contrib.auth.models import User
from diagen.utils.DiagramCreator import build_diagram_from_code
from diagen.utils.TextConverter import convert_text_to_code
from dia... |
4,399 | 8348d353e6fdea77c9c994d541db1420ef57a797 | import numpy as np
import pandas as pd
import plotly.graph_objects as go
from matplotlib import pyplot as plt
def plot_feature_VS_Observed(feature, df, linecolor):
"""
This function plots the 1880-2004 time series plots for the selected feature and observed earth
:param
Input: df -- > The dataframe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.