index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
995,000 | d779fe3d8c124940c4cc6b0cfd0738fcbe1763d3 | # Django
from django.contrib import admin
from django.utils.html import format_html
# Model
from .models import Group, Membership
# Utils
import base64
@admin.register(Group)
class GroupAdmin(admin.ModelAdmin):
'''Group admin.'''
list_display = ('id', 'name', 'slug', 'description',
'cre... |
995,001 | 10fe6790974751a235416caa213494891043ca48 | import sys, pygame
from hero import Hero
from settings import Settings
import gamefunctions as gf
from pygame.sprite import Group
from start_button import Play_button
def run_game():
pygame.init()
game_settings = Settings()
message = input("Start Game:")
screen = pygame.display.set_mode(game_settings.... |
995,002 | a3a0df505ca4eb6e3a2958e547ab1aa0a3a90a2f | import re
import ipaddress
import pandas as pd
def is_valid_ipv4_address (address):
try:
ipaddress.IPv4Address(address)
return True
except ipaddress.AddressValueError:
return False
fileDataHuawei=[]
with open("D:/install/Programming/Python/disp_cur_vvo.txt") as file:
# fileData = fil... |
995,003 | 56f0a4b12c1cfa0ecfb1486afb906a23ff819e3d | # Generated by Django 2.2.6 on 2019-11-10 12:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0004_auto_20191105_0652'),
]
operations = [
migrations.RemoveField(
model_name='item',
name='slug',
... |
995,004 | a589c5940bcc9bc0d178dc83f4cf62f0f4fa9053 | print("Helllllllloooooo World!") #Print greeting
print("What is your name?") #Provide a prompt for the user to provide input
my_name = input() #Create a variable that allows for input
print("Nice to meet you, " + str.capitalize(my_name)) #You are concatenating the string and capitalizing the input from my_name
print('Y... |
995,005 | a4aabcd655618f29c4bd27ba402027e3bbfc2c21 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import json
from Common.socket.Socket import *
class JsonSocket(Socket):
def __init__(self, conn=None, desc="", logger=get_stdout_logger()):
super().__init__(conn, desc, logger)
def __del__(self):
super().__del__()
@staticmethod
def is... |
995,006 | 960599979ac084fc155eb73e808de12a6bc5018f | """
Parse the input formula in dimacs format
"""
class Parser:
def parse_dimacs(input_file):
formula = []
with open(input_file) as file:
for line in file:
if line.startswith('c'):
continue
if line.startswith('p'):
... |
995,007 | 957a43402464ecdd5976ac9dcab0722af93784de | # -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2023 Fetch.AI Limited
#
# 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 ... |
995,008 | 8ec4882d2ff2a65c6d1d492a7e2838b915805ec0 | from flask import Flask
def create_app():
app = Flask(__name__)
app.config.from_object("api.setting")
register_blueprint(app)
return app
def register_blueprint(app):
from api.web import web
app.register_blueprint(web) |
995,009 | f11901bc4966fa99dc9ee9db08798b77b861bb4b | from django.db import models
from django.utils import timezone
from datetime import timedelta
from django.contrib.auth.models import AbstractUser
import os
# Create your models here.
class UserProfile(AbstractUser):
gender = models.CharField(max_length=6, choices=(("male",u"male"),("female",u"female"),("secret"... |
995,010 | 1f5945c5f017f13695fc81e0c3adfda810db3750 | import numpy as np
from collections import deque
import random
from ActorCritic_network.actor_network import ActorNetwork
from ActorCritic_network.critic_network import CriticNetwork
REPLAY_MEMORY_SIZE = 300000 # play result = state of trade_board + selected action + reward + sign-off state
BATCH_SIZE = 256
GAMMA = ... |
995,011 | beba2e17ae94c52dde16da9678166fa14b59740b | import pickle
#direct = '/Users/heine2307/Documents/Universitet/UiO/Master/GitHub/VQE/quantum_algorithms/attributes/'
direct = '/home/heineaabo/Documents/UiO/Master/VQE/quantum_algorithms/attributes/'
#def QuantumComputer(device,noise_model,coupling_map,basis_gates=False):
# name = device
# if device ==... |
995,012 | 83b594f4c36e9613d1be819bb0b36f36be3341c9 | from FTIR_show import getdata
from FTIR_Pretreatment import mean_centralization,standardlize,sg,msc,snv,D1,D2
from sklearn.decomposition import PCA
from statsmodels.stats.outliers_influence import variance_inflation_factor
from sklearn.model_selection import cross_val_score
from sklearn.linear_model import Lasso,L... |
995,013 | 467d1211af0f6f1bb878156cb48cec3ad5271d79 | # -*- coding: utf-8 -*-
import time
import base64
import hashlib
import json
import sys
import os
sys.path.append(os.path.abspath(os.path.join(sys.argv[0], "../../..")))
from spider.generate_excle import generate_excle
from zaishou_data_analysis import zaishou_data_analysis
from zaishou_constant import zaishou_consta... |
995,014 | 429d89ba407bfbecea3efcf975fd3ff359d030dd | # this file, along with actpols2_like_py.data, allows you
# to use this likelihood for Monte Python.
#
import os
import numpy as np
from montepython.likelihood_class import Likelihood
import pyactlike # our likelihood
class ACTPol_lite_DR4(Likelihood):
# initialization routine
def __init__(self, path, dat... |
995,015 | 713952565b8722cc7e730cb2c195b4df7400df33 | import pandas as pd
import numpy as np
import sys
import os
directory= sys.argv[1]
df=pd.read_csv('./{}/dataset_{}.csv'.format(directory, directory), sep=';')
classifications= pd.read_csv('./{}/classifications.csv'.format(directory), sep=';')
df=pd.merge(df, classifications, on='SMILES')
df.to_csv('./{}/data_class... |
995,016 | ccdd99a98e373f609d1ebc54fc2891ffe2dc3d61 | #파이r^2
cir_r=int(input("반지름을 입력해주세요: "))
pai=3.14
cir_a=pai*((cir_r)**2)
print("원의 넓이는",cir_a,"이다.") |
995,017 | be0d9ea28d740d52a06ef7a0ec0bb5263643c75c | from pynput.keyboard import Listener
import logging, time
from shutil import copyfile
import os
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
EMAIL_ADDRESS = os.environ.get("DEVMAIL_ADDRESS"... |
995,018 | a483432731cfcc537d0b60f0552dd12a5ce7bad9 | #!/usr/bin/env python3
import pathlib
import re
import shutil
import sys
from textwrap import dedent
import ply.lex
def get_deps_file():
# TODO recover actual builddir
with open('./latexmkrc', 'r') as f:
lines = f.readlines()
for line in lines:
if 'deps_file' in line:
pass
... |
995,019 | 59ae063f57bb33470c1ab806bcb3cf67db295825 | # import sklearn
# import matplotlib.pyplot as plt
# import random
# import re
import pandas as pd
df = pd.read_excel("2result.xlsx")
def cut(content):
content=str(content).replace("\n","")
return content
df['题干'] =df['题干'].apply(cut)
print(df.shape)
df.to_csv("清理后.csv") |
995,020 | 0854d7de25afd80bc51ab5b41a3263a69087c372 | from config_voting_ILSVRC12 import *
import tensorflow as tf
from tensorflow.python.client import timeline
from datetime import datetime
from copy import *
from FeatureExtractor import FeatureExtractor
subset_idx = 7
img_per_subset = 200
check_num = 2000 # save how many images to one file
samp_size = 50 # number of... |
995,021 | 2eecc9292383557f9f9c2dcaf4210d8052ceb723 | #!/usr/bin/env python
# coding: utf-8
# In[ ]:
import json, requests, os,re,urllib
from requests import get
from time import sleep
from time import ctime
global token
global rpc
global proxies
proxies = {
'http': '',
'https': '',
}
rpc = input('输入Aria2 RPC,留空为本地Aria2:\n')
if rpc == '':
print('使用本地http://... |
995,022 | 81d0817abf9b3e15db8e4ce70a31e1428d1e6997 |
# -*- coding: utf-8 -*-
class Solution(object): # binary manipulation trick
def reverseBits(self, n):
ans = 0
for i in xrange(32):
ans = (ans << 1) + (n & 1) #二进制与操作符"&": http://www.tutorialspoint.com/python/python_basic_operators.htm
n >>= 1
return ans
# ... |
995,023 | 1f39c69a6a2a33b5e22ff05c323c81a9e54b03a9 | from os import link
from django.contrib.auth import forms
from django.contrib.auth.models import User
from django.db import models
from programms.models import Programm
# Create your models here.
class Download(models.Model):
user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
prog = models.F... |
995,024 | 8d8dbb444f1e508741035dd3b53d0254ed373701 | import re
from Element import HSrc
import Circuit
import Element
def parse(filename):
mycircuit = Circuit.Circuit(title="", filename=filename)
file = open(filename, "r")
lines = []
line_number = 0
elements = []
if file is not None:
while True:
line = file.readline()
... |
995,025 | 9876b5cb5f79664eab71c574da2fc920c27f7f53 | import Common.math_functions as mf
import numpy as np
import matplotlib.pylab as plt
x = np.arange(-5.0, 5.0, 0.1)
#y = pr.step_function(x)
y = mf.sigmoid(x)
plt.plot(x, y)
plt.ylim(-0.1, 1.1) #指定y轴的范围
plt.show() |
995,026 | 96640a290bf1947c9117e3aad131a68cc47e9cec | # Copyright (C) 2010-2011 Richard Lincoln
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish... |
995,027 | 542ae1aaa46e760daffe1322e74ff73b21f8bdc0 | # -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_prot0.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_Dialog(object):
def setupUi(self, Dialog):
Dialog.setObject... |
995,028 | d8dd5ceefe19fe851259a312ad0cb7c791e93060 | import sys
import colors
class ColorPrint(object):
def __init__(self):
self.colors = colors
def __getattr__(self, name):
if not name.startswith('print'):
raise NameError('%s has no method %s' % (
self.__module__, name))
color = name.split('_', 1)[-1]
... |
995,029 | 8e57c3348758f09b34258981e409738edea66bc6 | # Generated by Django 3.0 on 2020-01-08 12:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('appsblog', '0003_appsblog_features'),
]
operations = [
migrations.AddField(
model_name='appsblog',
name='install_steps... |
995,030 | e590d09a2a220d4f169f5f400457c39c88cd1e26 | import os
os.system("make depend")
os.system("make")
os.system("make install")
|
995,031 | 0774597344afab28a45457aebff87f21aa246f5f | import grpc
import unary.unary_pb2_grpc as pb2_grpc
import unary.unary_pb2 as pb2
class UnaryClient(object):
"""
Client for accessing the gRPC functionality
"""
def __init__(self):
# configure the host and the
# the port to which the client should connect
# to.
self.ho... |
995,032 | ef482e2256ce60f1c5b091f6a525b6dacf8a6ff1 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('exams', '0037_auto_20150208_2337'),
]
operations = [
migrations.AlterField(
mod... |
995,033 | 02162dcfbd5390a40a7a4517621b3e8d53c62a3d |
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
from collections import defaultdict
import numpy as np
from zutils import *
from zcostfunc import *
from zirie import IRIE
mpl.rcParams['font.family'] = 'serif'
plt.rcParams['font.size'] = 16
plt.rcParams['axes.linewidth'] = 1
import loggin... |
995,034 | c04edea687245f60bfcb8253ec3111455561f95d | import os
import sys
import time
import csv
import numpy as np
def time_to_slot(hh,mm):
""" Split the time steps within one day into 96 different slots.
Parameters
----------
hh : hour
mm : minute
Notes
-----
The time taken for a slot is 15' step
"""
hour_slo... |
995,035 | 0f0f06cb67cee46492b4835b11d95042e5eae240 | # -*- coding: utf-8 -*-
# @Author: Arius
# @Email: arius@qq.com
# @Date: 2019-01-26 23:55:45
|
995,036 | 1761a8e3c92f7f60101c23f61b6d4a42ffaf1ca1 | def harmonicNum(n):
if n == 1:
return 1
else:
return harmonicNum(n-1) + 1/(n-1)
if __name__ == "__main__":
print(harmonicNum(4))
|
995,037 | 0308766a64e1e5d8e9ad1f79306ab25583b31433 | import torch
from torch.utils.data import Dataset, DataLoader
from model import *
from data_loaders import *
from get_embeddings import *
from constants import *
def main():
print("[INFO] -> Loading Preprocessed Data ...")
model_data_german = torch.load("../data/data_de_"+DOMAIN+".pt")
print("[INFO] -> Done.")
#... |
995,038 | 8dc6728a707a00ad65f689ae31bf57d382ee019a | ## Code for HITS.py
## Calculates the hubbiness and authority of all nodes (uses 40 iterations)
import sys
import numpy as np
from pyspark import SparkConf, SparkContext
from pyspark.accumulators import AccumulatorParam
conf = SparkConf()
sc = SparkContext(conf=conf)
lines = sc.textFile(sys.argv[1])
data = lines.map(... |
995,039 | 9a1ce1f7afad23aed2fa2bb0eb7c5ea8cbcf283e | numero = [0]*2
for i in range(2):
numero[i] = int(input('Digite o {}º número: '.format(i+1)))
if numero[0] > numero[1]:
print('O primeiro valor é maior!')
elif numero[0] < numero[1]:
print('O segundo valor é maior!')
elif numero[0] == numero[1]:
print('Os dois valores são iguais!')
|
995,040 | f9a36ab12d1fde95a2e77899a80e9f23aad21b0c |
### import
from quizzer.models.model import Model, MAX_LEN
from quizzer.models.teacher import Teacher
### Class
class Class(Model):
FIELDS = dict(
number=dict(types=unicode, length=(1, MAX_LEN)),
name=dict(types=unicode, length=(1, MAX_LEN)),
teacher=dict(types=Teacher, null=True, defau... |
995,041 | 1831a6f36be5a572f650402982d26e9706e01635 | ## function to find area of rectangle
def area_rectangle(l, b):
return l*b
|
995,042 | f224c5526d3d2ffeb7d8eea87f2cd6febb0bcd2a | import numpy as np
import os
import math
import pygame
from time import sleep
from Robots import Robots
from GamePlay import GamePlay
#class that creates the connect4 environment
class Connect4():
def __init__(self,p1='HUMAN',p2='HUMAN',depth=3,spacing=100,controler=0):
self.gameplay=GameP... |
995,043 | 1104efbfcaa0cdb8fe4492fe85f96bcb6e444801 | from django import forms
from firesdk.firebase_functions.firebaseconn import CompanyId, encode_email, get_user
from firebase_admin import auth
class LoginForm(forms.Form):
company_id = forms.CharField(max_length=50, required=True)
email = forms.EmailField(max_length=254, required=True)
password = forms.Ch... |
995,044 | b8d3a49312644059b6e688c627163c1fe6c8b1be | #!/usr/bin/env python
# coding: utf-8
# load_dims.py
# Author: Kevin Solano
from modulos.create_sparkSession import create_spark_session
from pyspark.sql.functions import *
from pyspark.sql import types as t
import configparser
def load_dim_job():
"""
proceso de carga de dim_job
"""
config = con... |
995,045 | 9a240a177e1fa883d87efebe9b246a9d6d524740 | '''
@author Sam
@date 2017-12-30
@des 第七章数据规整化:清理、转换、合并、重塑
这里主要练习字符串操作
pandas 有对复杂的模式匹配和文本操作的功能进行加强。
'''
import pandas as pd
import numpy as np
import re
val = 'ab, guido'
tmp = val.split(',')
print(val)
pieces = [x.strip() for x in val.split(',')]
print('================>我就是分隔线 1 <==============')
print(pieces)
f, s... |
995,046 | 6b5bb0b30587517d7bfc13f52e26aa7146acc682 | z=lambda i,j,r:i**2+j**2<r**2
def checkio(R):
r=int(R)+1
x=y=0
for i in range(r):
for j in range(r):
if z(i,j,R):
y+=1
x+=z(i+1,j+1,R)
return[x*4,(y-x)*4]
f=lambda R,r,k:sum((i+k)**2+(j+k)**2<R**2 for i in range(r) for j in range(r))
def golf(R):
r=int(R)+1
return [4*f(R,r,1),4*(f(R,r,0)-f(R,r,1))]
... |
995,047 | 65f4a21ff358c4520f5e8c66ca9446c00fde4e94 | import requests
import sys
import io
from urllib import request
def login():
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8') # 改变标准输出的默认编码
# 登录后才能访问的网页
url = 'fakeurl'
# 浏览器登录后得到的cookie,也就是刚才复制的字符串
cookie_str = r''
# 把cookie字符串处理成字典,以便接下来使用
cookies = {}
for line i... |
995,048 | b09919c93b02099e19c1086fae5729e656e22724 | #!/usr/bin/python
from flask import Flask, jsonify, request
app = Flask(__name__)
transactions = [
{
'transaction_id': 1,
'place_id': u'place_id',
'car': 'car',
'cost' : u'UAH',
'leave_before' :u'date',
'hourly_rate': u'rate',
'result': 'result'
}
]
pla... |
995,049 | 30f29976f16cf2caaaee895ac0408ad55136c090 | import os
import time
import json
import logging
import argparse
import sys
sys.path.append(os.path.join("libs", "soft"))
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras import backend as K
from data import ContentVaeDataGenerator
from data import CollaborativeVAED... |
995,050 | 1920d963dad15b2d2a2b90416c808236efdf3c89 | import sys
import json
from dateutil.parser import parse
from datetime import datetime
import pandas as pd
from text_util import TextUtil
class BlogEntry(object):
"""Data class modeling a raw blog entry"""
def __init__(self, title, date, url, raw_text, source, crawl_url):
super(BlogEntry, self).__init... |
995,051 | ee3bf8b20892a30fc3b93f7ed6b4ba082e9bda11 | __all__ = ['similar', 'distance']
import similar
import distance |
995,052 | 3cbb0c768a87da1d5d232c34f2710fc04d808680 | import numpy as np
import os
from skimage.transform import resize
from skimage.io import imread
IMG_SIZE = (299, 299, 3)
NUM_CLASSES = 50
class BatchIterator:
def __init__(self, filenames, directory, resize_shape, batch_size, train_gt):
self._filenames = filenames
self._directory = directory
... |
995,053 | 15b22cbe86b4b2397798a968afb7fc3a6082441d | #!/usr/bin/python3
# Author: Joseph Sevigny
# Date: Feb, 28th 2020
# Purpose: automatic construction of circos plot from gff, fasta, and bed file
# tested for circos v 0.69.3
import os
import shutil
import sys
import argparse
from Bio import SeqIO
# Parse arguments
parser = argparse.ArgumentParser(formatter_class=... |
995,054 | f08492a27f89357815f1a35217ad986620ec7cb9 | from plumbum import cli, colors, local
import os
path = "/home/mattia/.notes/"
if not os.path.exists(path):
os.makedirs(path)
file = path + "notes.txt"
class Notes(cli.Application):
"simple notes handler"
PROGNAME = "Notes"
VERSION = "0.2"
def main(self):
if not self.nested_command:
... |
995,055 | fd5b9b3334554a3705b209651135ab2b5a3ea676 | import sys, os, pygame
from pygame.locals import *
from Scene import Scene
class menuScreen(Scene): #Menu class for the menu screen
def __init__(self, width=300,height=300):
pygame.init()#starts pygame
self.width=width#sets width of window
self.height=height#sets height of window
self.background=pygam... |
995,056 | 7fde4a17fa340847430bd2ac643a7a170236f94b | import struct
class DnsResponseBuilder():
def __init__(self, data, query_length, url, q_id):
self.header = {}
self.records = []
self.data = data
self.is_valid = False
self.length = query_length
self.qtype = None
self.url = url
self.q_id = q_id
... |
995,057 | 0ed556cd830050ec2b90cca708e95e112b10eef3 | # encoding=UTF-8
from flask import Flask, render_template, request, Response, redirect
import scraper
import lottery
import people_filter
import json
from config import config
import hw
app = Flask(__name__)
@app.after_request
def add_header(response): # disabled cached when debugging
response.cache_control.max... |
995,058 | 83a502277c9f9ec3095a97430065c1e691fbe18c | from django.apps import AppConfig
class VistorsConfig(AppConfig):
name = 'vistors'
|
995,059 | 36a6806024ae53da2faca67a92308a444ca8bd9f | import gspread
from oauth2client.service_account import ServiceAccountCredentials
scope=[
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive',
]
json_file_name='diesel-monitor-283800-7f744adca4c3.json'
credentials=ServiceAccountCredentials.from_json_keyfile_n... |
995,060 | 785625ae82786beee6fd88fa00bc944259c4f7c7 | # uvicorn app_assetmgr:app --port 8001 --reload
|
995,061 | 58c7df059139cfcbc5d2f0f038e6ab36690d50e3 | data_path='/data4/jiali/data/iso_train'
import os
count=1
lstm1=0
lstm2=1
if lstm1:
dirs=os.listdir(data_path)
fimg=open('lstm_rgb_list.txt','w')
# fflow=open('lstm_flow.list.txt','w')
for dir in dirs:
files=os.listdir(os.path.join(data_path,dir))
for file in files:
co... |
995,062 | 9740e680777bcd1330a816fd5a5a29d5ca3dedaa | from .base import *
DEBUG = False
# Add any production-specific (but not server-specific) configuration here. |
995,063 | 473a6a86062c9ef3782a06651055420be02b14ac | import os
import numpy as np
import glob
import datetime
figures_dir = './figures'
import argparse
import time
if __name__ == '__main__':
ap = argparse.ArgumentParser()
ap.add_argument('min_h_since_modified', type=float, default=24, nargs='?')
ap.add_argument('-d', '--exp_dir', nargs='?', type=str, default... |
995,064 | dc517a5f133292a0d6a0b5c39a942a3332d2a8d6 | import random
class Option():
def __init__(self):
self.file = [line.rstrip('\n').upper() for line in open('dictionary.txt', "r")]
SCRABBLES_SCORES = [(1, "E A O I N R T L S U"), (2, "D G"), (3, "B C M P"),
(4, "F H V W Y"), (5, "K"), (8, "J X"), (10, "Q Z"), (11, "Ą Ć Ę Ł Ń Ó Ś Ź Ż")]
globa... |
995,065 | ab78e04fe58d97daae7e712729aa9a4ff0ed9fc4 | from django.urls import path, include
from pomelo.settings import api_settings
from .views import ImageViewSet
RouterClass = api_settings.DEFAULT_ROUTER
router = RouterClass()
router.register('image', ImageViewSet)
urlpatterns = [
path('', include((router.urls, 'pomelo'), namespace='pomelo')),
]
|
995,066 | d7d5f3532d0f4c70c77606c64877313e0d432137 | import requests
from bs4 import BeautifulSoup
class Solution:
def __init__(self):
self.req = requests.session()
self.url = ""#server url include port
self.res = ""
def sendP(self, data):
self.res = self.req.post(url=self.url, data=data)
def checkSuc(self, res):
if re... |
995,067 | 47d7f20548a40f5b5de3950ec22ca17a28346dea | # BeagleBone Black Health Sensors
# Autores: Mario Baldini, Joao Baggio, Raimes Moraes
import smbus
from time import sleep
import sys
import driver_adxl345_bus1 as ADXL345_bus1
import driver_adxl345_bus2 as ADXL345_bus2
## BEGIN
adx1 = ADXL345_bus1.new(1, 0x1D) #adxl345_bus1_add53
adx2 = ADXL345_bus1.new(1, ... |
995,068 | f9090a37c3b354a84d7d0678a47dd0ae63513cb2 | # -*- coding:utf-8 -*-
from sys import argv
import requests
EXAMPLE="""
Eg:python test_argv.py http://www.baidu.com
"""
if len(argv) !=2:
print EXAMPLE
exit()
script_name,url=argv
if url[0:4] !="http":
url=r"http://"+url
r=requests.get(url)
print u"接口地址:"+url
print u"状态码:"+str(r.status_code)
... |
995,069 | 14163e7316cf86d61862e81440723eb764eb6263 | #!/usr/bin/env python3
import asyncio
import os
import re
import sys
from PyQt5 import QtWidgets
from quamash import QEventLoop
from slack import RTMClient
from slack import WebClient
from MainWindow import Ui_PyQT5SlackClient
# import logging
# logging.basicConfig(level=logging.DEBUG)
slack_api_token = os.environ["S... |
995,070 | 8de74df84dd61c8a8e593dc7cac53525e85183ca | from commands.help import HelpCommand
from commands.toons import ToonsCommand
from commands.ships import ShipsCommand
from commands.members import MembersCommand
from commands.guild_member import GuildMemberCommand
from commands.member_toon import MemberToonCommand
from commands.member_ship import MemberShipCommand
fro... |
995,071 | e5d422863f485bd97b05064fee917231e296c4e0 | import argparse
import sys
import os
import logging
import ConfigParser
import json
import copy
WORKDIR = os.path.realpath(os.path.dirname(sys.argv[0]))
def init_logger(log_file_name, log_base_path=None, log_level=None,
logger_name=None, print_to_console=None):
if log_base_path is None:
lo... |
995,072 | 181f7f37abaf2506bb08747bd42b5c75b9f79856 | """
Given a non-negative integer num, Return its encoding string.
The encoding is done by converting the integer to a string using a secret function that you should deduce from the following table:
Example 1:
Input: num = 23
Output: "1000"
Example 2:
Input: num = 107
Output: "101100"
Constraints:... |
995,073 | 9e1e30fda2373e7eb0a3fc2d4f8428cf5f42fad8 | from case.interfacetest import InterfaceTestCase
if __name__ == '__main__':
app = InterfaceTestCase()
app.runAllCase("xd") |
995,074 | c0988a8a6286437ad6d1846cbe4af286c06e92b6 | def binarySearch(target):
left, right = 0, len(nums) - 1
while left < right:
mid = left + (right - left) // 2
if target <= nums[mid]:
right = mid
else:
left = mid + 1
return left
... |
995,075 | 6f4e560e6e7702eaab69d5692558b31d3581889a | #Timedelta function demo
from datetime import datetime, timedelta
#timedelta has 3 attributes
print("Max:", timedelta.max) #the most positive timedelta object, timedelta(days=999999999,hours=23),minues=59,seconds=59,microseconds=999999)
print("Min:", timedelta.min) #the most negative timedelta bject,timedelta(-99999999... |
995,076 | f47fec488fb6878c7723ad88505ea1f23db7b97b | """
Module description ...
Reference:
- Surename1, Forename1 Initials., Surename2, Forename2 Initials, YEAR. Publication/Book title
Publisher, Number(Volume No), pp.142-161.
"""
import numpy as np
import matplotlib.pyplot as plt
def draw_lagrangian_descriptor(LD, LD_type, grid_parameters, tau, p_value, norm = True, c... |
995,077 | e3e15e2e47e5dba468c4bc5080a90c81268a8366 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# call functions
abs(-100)
max(1, 2)
int('123')
int(12.34)
float('12.34')
str(100)
bool(1)
bool(-1)
bool(0)
bool('')
bool(None)
a = abs
a(-1)
# define a function
def my_abs(x):
if x >= 0:
return x
else:
return -x
my_abs(-0.5)
# empty function (... |
995,078 | 6e530c48cd9902189f2bbbb7a98ff652eca2b7e2 | # -*- coding: utf-8 -*-
"""
Created on Sat Jul 04 14:50:28 2015
Given an array S of n integers, are there elements a, b, c in S
such that a + b + c = 0? Find all unique triplets in the array which
gives the sum of zero.
Note:
Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
The solutio... |
995,079 | 41e655ec84a876a76c39d9825c0230f5e86cb8ff | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def rightSideView(self, root: 'TreeNode') -> 'List[int]':
if not root:
return []
queue = collections... |
995,080 | 3fb95acea5607990dc7bd1a54d6fe965c3326c0d | """A program to compute a solution to Problem 107 on Project Euler."""
import timeit
def generate_matrix(filename):
"""Generate a matrix from an input text file.
:param str filename: The name of the network file in .txt format
:rtype dict network: The resulting matrix represented as a
2D list of edge... |
995,081 | ae4e8201243934004a6ec75e367a99740f75f538 | from tetrimino import *
rows, colns = 20, 10
board = create_board(rows, colns)
tet = O
tet["pos"] = (18, 0)
place(tet, board)
tet["pos"] = (8, 0)
place(tet, board)
tet["pos"] = (0, 8)
place(tet, board)
print(board)
move_left(tet, board)
place(tet, board)
print(board)
tet["pos"] = (0, 0)
place(tet, board)
print(boar... |
995,082 | 7c866a302c2eaea43490efe7ccdc44cd9c83b1f1 | #!/usr/bin/env python
"""
amazon_api_lookup.py
This module uses the Amazon Product API to lookup barcodes as UPC and
EAN codes, and returns a list of possible product matches in the Amazon
catalog, along with the corresponding Amazon Standard Identification
Number (ASIN).
The actual Amazon Product API credentials ne... |
995,083 | cdeb8aafbcaad2975e4fcd42c398b8f2be374595 | # -*- coding: utf-8 -*-
# ==============================================================================
# Imports
# ==============================================================================
from pytest_rpc.fixtures import * # noqa
# ============================================================================... |
995,084 | 47cb10f212f95e7cfba9132cbf25cc6aeaea58c3 | # -*- coding:utf8 -*-
from django.db import models
from django.utils.timezone import now
from horizon.models import (model_to_dict,
BaseManager,
get_perfect_filter_params)
from Admin_App.ad_coupons.models import (CouponsConfig,
... |
995,085 | 0bcfeaf2ff236e243167e506e32a5ed7804c74f0 | '''
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Ex... |
995,086 | 4ecb88c9eedefde13357d568aedb8ab3690c6ca7 | import gevent
from gevent.pywsgi import WSGIServer
import zmq.green as zmq
from geventwebsocket.handler import WebSocketHandler
from itertools import cycle
import json
from pricing_app import app
from pricing_app.model.index import EquityIndex
WAIT = 60
def zmq_qry_pub(context):
"""PUB -- queries and PUBLISHES... |
995,087 | 6f7d9a72fa98814ada768a258967c370eae5cf97 | import pickle
from train_nn import forward_nn
def create_features(x):
phi = [0 for i in range(len(ids))]
words = x.strip().split()
for word in words:
if 'UNI:'+word in ids:
phi[ids['UNI:'+word]] += 1
return phi
if __name__ == '__main__':
test_f = '../../data/titles-en-t... |
995,088 | c42a7228ea7859a51e3f20826a26f0f04fe003b5 | import requests
from .constants import DEFAULT_API_PATH, OLD_API_PATH
# Utility methods
def raise_for_status(response):
"""
Custom raise_for_status with more appropriate error message.
"""
http_error_msg = ""
if 400 <= response.status_code < 500:
http_error_msg = "{} Client Error: {}".fo... |
995,089 | ebedef4fbc5ab8912a04677c2d202050a8a361b3 | # """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
# def __init__(self, value=None):
# """
# If value is not specified, initializes an empty list.
# Otherwise initializes a single i... |
995,090 | 51bc2ac76f1d15205a786d42cf6d8048927eae80 | '''
Created on Mar 18, 2013
@author: joshua
'''
import xml.etree.ElementTree as ET
import re
import camelcase_sep
import stemming.porter2
import Stemmer
from gensim import corpora, models, similarities
import numpy as np
import scipy.spatial.distance
from sklearn import mixture
import math
from functools import wr... |
995,091 | e0fc1a9202f8491f59ee7c065f6eb0c5407eb81e | from discord import Client
import aioredis
from logging import getLogger
from elastic_helper import ElasticSearchClient
from sql_helper import SQLConnection
from sql_helper.metrics import sql_wrapper
from nqn_common import dpy, GlobalContext
from rabbit_parsers import DemoBaseRabbit
log = getLogger(__name__)
asy... |
995,092 | faf8ad0bdf36a0359115dfe26b3e91fec301cdab | import time
import board
def getTwosComplement(raw_val, length):
"""Get two's complement of `raw_val`.
Args:
raw_val (int): Raw value
length (int): Max bit length
Returns:
int: Two's complement
"""
val = raw_val
if raw_val & (1 << (length - 1)):
val = raw_val - (... |
995,093 | 587258852da591df2b147aa341c601527b77878f | import itertools as I
from uuid import uuid4
from dw.db import schema as S
from dw.util import fp
from dw.util.etc_utils import modulo_pad, factorseq
def crop_xys_list(org_ws, org_hs, crop_w, crop_h):
img_wseq = (org_w + modulo_pad(org_w, crop_w) for org_w in org_ws)
img_hseq = (org_h + modulo_pad(org_h, cro... |
995,094 | ae038b7f4bb52a981c2432cfb1615f983ba57cd9 | from PIL import Image,ImageFilter
from matplotlib import pyplot as plt
img = Image.open('image/a0.jpg')
img1 = img.filter(ImageFilter.CONTOUR) #轮廓
img2 = img.filter(ImageFilter.BLUR) #模糊
img3 = img.filter(ImageFilter.BoxBlur(radius=1)) #模糊
img4 = img.filter(ImageFilter.DETAIL) #锐化
img5 = img.filter(ImageFilter.EMBOSS)... |
995,095 | d4d6a474f48a6975796267900f148b263684d4fb | # -*- coding: utf-8 -*-
# Generated by Django 1.10.6 on 2017-03-20 20:30
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0004_auto_20170319_2143'),
]
operations = [
migrations.RenameField(
... |
995,096 | 28bebf8e090e9a3438503763eddf2a36c47d7b37 | from django.contrib import admin
from .models import *
admin.site.register(Client)
admin.site.register(ServiceProvider_Motor)
|
995,097 | 1bcc41c5fc94446dbd0e5cc3d19313e298d493b2 | from collections import defaultdict
import time
start_time = time.time()
content = open('i', 'r').readlines()
content = [c.strip() for c in content]
G = defaultdict(list)
count = 0
for row in content:
left, right = row.split('-')
G[left].append(right)
G[right].append(left)
def dfs(node, V, using_twice)... |
995,098 | aa4666488a326517d02c4f8b4a6aa647b55afba6 | for a in range(1,999):
for b in range(1,1000-a):
c=1000-a-b
if a*a+b*b==c*c: print a*b*c
|
995,099 | e0162ee53d82aadb71b59bc4f7fe45159f9221a4 | from copy import *
class Solution:
def isPalindrome(self, s: str) -> bool:
if s=="":
return True
if not s:
return False
l=[p for p in s.lower() if p.isalnum()]
print(l)
l.reverse()
if l==l[::-1]:
return True
ret... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.