text stringlengths 38 1.54M |
|---|
# GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# ... |
# encoding: utf-8
import os
from pkg_resources import resource_listdir, resource_filename
from .util import Cache
__all__ = ['Resolver']
class Resolver(Cache):
def __init__(self, default=None, capacity=50):
super(Resolver, self).__init__(capacity)
self.default = default
def parse(self, path):
# Split ... |
import sqlite3
class DBManager:
def __init__(self, database):
"""Подключаемся к БД"""
self.connection = sqlite3.connect(database)
self.cursor = self.connection.cursor()
def select_all(self):
""" Получаем все пункты меню """
with self.connection:
return sel... |
# -*- coding: utf-8 -*-
# @File : removeElement.py
# @Author: ZRN
# @Date : 2018/9/29
"""
给定一个数组 nums 和一个值 val,你需要原地移除所有数值等于 val 的元素,返回移除后数组的新长度。
不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
元素的顺序可以改变。你不需要考虑数组中超出新长度后面的元素.
"""
class Solution:
def removeElement(self, nums, val):
"""
:type nums:... |
number = int(input("Enter a number "))
number = int(number)
if number%2 == 0:
print("Great! %d is an even number "%(number))
else:
print("Nope! %d is an odd number "%(number)) |
class Solution:
def sumSubseqWidths(self, A: List[int]) -> int:
A.sort()
N = len(A)
res = 0
MOD = 10 ** 9 + 7
for i in range(N):
res = (res + ((1<<i) - (1<<(N-i-1))) * A[i]) % MOD
return res % MOD
|
# @Time : 18-3-12 下午9:31
# @Author : DioMryang
# @File : Processor.py
# @Description :
import logging
from DioFramework.Base.Mixin.LoadClassToolMixin import LoadClassToolMixin
class Processor(LoadClassToolMixin):
"""
处理器通用继承类
处理json配置:
```
{
"id": 1, ... |
#!/usr/bin/env python
import numpy as np
from utils import wrapToPi
# Import message definition
import rospy
from std_msgs.msg import Float32
# command zero velocities once we are this close to the goal
RHO_THRES = 0.05
ALPHA_THRES = 0.1
DELTA_THRES = 0.1
class PoseController:
""" Pose stabilization controller... |
# -*- coding: utf-8 -*-
"""Runs the ranking of drug targets using the HumanBase data as PPI network."""
import logging
import os
import time
import traceback
import warnings
import matplotlib.pyplot as plt
import pandas as pd
from guiltytargets.pipeline import rank_targets, write_gat2vec_input_files
from guiltytarg... |
from requests import request
from ..models import (Scraper, ArticleSpider, ArticleThread,
Article, CrawlerSet, CrawlerItem, ScraperAnalysis)
from ..serializers import (ScraperSerializer, ArticleSpiderSerializer, ArticleThreadSerializer, ArticleSerializer,
CrawlerSetSeria... |
import tensorflow as tf
from tensorflow import keras
fashion_mnist = keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']
# # (60000, ... |
# Copyright (c) 2010-2012 Mitch Garnaat http://garnaat.org/
# Copyright (c) 2012 Amazon.com, Inc. or its affiliates. All Rights Reserved
#
# 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 wit... |
#
import pandas as pd
import requests as rq
import numpy as np
import re
def download_data(url,option='xls',gid=None):
"""
extrai planilha do google sheets utilizando a API google sheets.
EXEMPLO: download_data('https://docs.google.com/spreadsheets/d/1N6JFMIQR71HF5u5zkWthqbgpA8WYz_0ufDGadeJnhlo/',gi... |
from django.shortcuts import render
from .models import *
from django.http import JsonResponse
import json
# Create your views here.
def store(request):
products = Product.objects.all()
context={'products':products}
return render(request, 'store/store.html',context)
def cart(request):
if request.user.... |
"""
Access the main thread
This module allows you to run code on the main thread easely. This can be used for modifiying the UI.
Example:
.. highlight:: python
.. code-block:: python
from UIKit import UIScreen
import mainthread
def set_brightness():
inverted = int(not int(UIScreen.mainScreen.br... |
from django.urls import path
from django.contrib.auth.views import LogoutView
from . import views
app_name = "accounts"
urlpatterns = [
path("login/", views.SubmittableLoginView.as_view(), name="login"),
path("logout/", LogoutView.as_view(), name="logout"),
path("password-change/", views.SubmittablePasswo... |
# Pathfinding - Part 1
# Graphs
# KidsCanCode 2017
import pygame as pyg
from collections import deque
from queue import LifoQueue
import heapq
from math import pow
from os import path
import matplotlib.pyplot as plt
vector = pyg.math.Vector2
TILE_SIZE = 25
TILE_WIDTH = 20
TILE_HEIGHT = 20
GRID_WIDTH... |
import asyncio
from dffml import Model, Features, Feature, train
async def main():
# Load the model using the entrypoint listed on the model plugins page
SLRModel = Model.load("slr")
# Configure the model
model = SLRModel(
features=Features(Feature("Years", int, 1)),
predict=Feature(... |
from pose_estimation import PoseEstimation
import cv2
from args import get_args, show_args
import numpy as np
import pickle
from collections import deque
import time
import telegram_send
import threading
from concurrent.futures import ThreadPoolExecutor
class FallDetector:
"""A Class that sends an alert via Teleg... |
import numpy as np
from src.data import Case, Matter
def trivial_reducer(c: Case) -> np.array:
# pile up
# paste background
repr_values = np.ones(c.shape, dtype=np.int) * c.background_color
# collect values
m: Matter
for m in c.matter_list:
if not m.bool_show:
continue
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import homepilot_utils
import xbmc
class HomePilotBaseObject:
"""
class which represents a single device
"""
def __init__(self, device):
"""
constructor of the class
Arguments:
device -- dictionary with the device attrib... |
make_new_list=lambda l:[l[x]+l[x+1] for x in range(len(l)-1)]
'''
You get a list of integers. Return a new list by adding 2 elements
surrounding each comma in the list.
Examples
If you get [1, 1, 1, 1], return [2, 2, 2] because [1+1, 1+1, 1+1]
If you get [1, 2, 3, 4], return [3, 5, 7] because [1+2, 2+3, 3+4]
If you ... |
#!/usr/bin/env python
import logging
import numpy as np
from argparse import ArgumentParser
from theano import tensor
from blocks.algorithms import GradientDescent, Scale, Adasecant, AdaDelta, Momentum
from blocks.bricks import MLP, WEIGHT, Logistic
from blocks.bricks.cost import SquaredError, BinaryCrossEntropy
fr... |
import connexion
import six
import csv
import os, fnmatch
import numpy as np
from PIL import Image
from io import BytesIO
import base64
from swagger_server.models.enrollment import Enrollment # noqa: E501
from swagger_server import util
from swagger_server.face_vector.face_vector import FaceVector
faceVector = FaceV... |
import math
import numpy
# Flatten an array of n images to an array of n normalized vectors of pixels
# Input.shape : (n, x, y,)
# Output.shape : (n, x*y,)
def to_normalized_vector_list(images):
if len(images.shape) == 2:
return images/255
elif len(images.shape) == 3:
pixels_qt = images.shape[... |
from py2neo import Graph
#pip install py2neo
graph = Graph(password="test")
#Neo4j in esecuzione su cui è creato un grafo vuoto (in esecuzione, cliccare start) avente password test
graph.run("MATCH(n) DETACH DELETE n") #Cancello tutti i nodi in caso il grafo non è vuoto
graph.run("CREATE (p:Person {name: 'Giuseppe',... |
#**********LIBRARY IMPORTS************
#os for system calls , time for delays so user can read output
import os, time
#**********INSTALLATION AND UPDATES***************************
#This script utilizes ffmpeg, youtube-dl and cdrdao
print "Checking for youtube-dl and FFMpeg..."
time.sleep(3)
os.system("cd /usr/loca... |
# print(eval(input()))
while True:
try:
n1 = float(input('введите первое число\n'))
sign = input('введите знак\n')
n2 = float(input('введите второе число\n'))
if sign == '+':
s = n1 + n2
elif sign == '-':
s = n1 - n2
elif sign == '*':
... |
import boto3
import telemetry.telescope_ec2_age.desc_launch_conf as desc_launch_conf
import sys
from datetime import datetime
from telemetry.telescope_ec2_age.logger import get_app_logger
from botocore.exceptions import ClientError
logger = get_app_logger()
ec2_client = boto3.client('ec2', region_name='eu-west-2')
d... |
# -*- coding: utf-8 -*-
# author: inspurer(月小水长)
# create_time: 2021/8/24 8:25
# 运行环境 Python3.6+
# github https://github.com/inspurer
# 微信公众号 月小水长
# todo: add proxy
import requests
from lxml import etree
from time import sleep
HEADERS_LIST = [
'Mozilla/5.0 (Windows; ... |
from forex_python.converter import CurrencyRates
currencies = {"EUR":"Euro-Member-Countries","IDR":"Indonesia-Rupiah","BGN":"Bulgaria-Lev","ILS":"Israel-Shekel","GBP":"United-Kingdom Pound","DKK":"Denmark-Krone","CAD":"Canada-Dollar","JPY":"Japan-Yen","HUF":"Hungary-Forint","RON":"Romania-New-Leu","MYR":"Malaysia-Ring... |
import extract
import transform
import os
start_page = 1
end_page = 1
current_recipe_page = start_page
# create empty list for individual recipe urls to be saved in
recipe_links = []
# local path for xml files to be saved in
#print(output_path)
# Loop through each `all_recipe_pages`
while current_recipe_page <= en... |
from indicnlp.tokenize import indic_tokenize
from collections import Counter
indic_string='सुनो, कुछ आवाज़ आ रही है। फोन?'
x=[]
stopwords={"है","।","?"}
print('Input String: {}'.format(indic_string))
print('Tokens: ')
for t in indic_tokenize.trivial_tokenize(indic_string):
x.append(t)
print(t)
print(x)
my_doc... |
from common import Moons, total
m = Moons()
for i in range(1000):
m.iterate()
print(sum(total(moon) for moon in m.moons))
|
from fastapi import FastAPI
from algorithm.nl2color import predict
from algorithm.pre_process import pre_process
from fastapi.responses import JSONResponse
from algorithm.util import rgb2hex
from algorithm.classification import classification
app = FastAPI()
headers = {"Access-Control-Allow-Origin": "*"}
@app.get("... |
from model.drawable import Drawable
class HomeHeader(Drawable):
def update(self):
super().update()
def draw(self, view):
first_line = view.font_72.render("Ball Sort Puzzle", True, (255, 255, 255))
view.screen.blit(first_line, (view.width // 2 - first_line.get_width() // 2, view.height... |
# ------------------------------------------------------------------------------
# Access to the CodeHawk Binary Analyzer Analysis Results
# Author: Henny Sipma
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016-2020 Kestrel Technology LLC
#
#... |
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
#!/usr/bin/python
# coding:utf-8
import os.path
import sys
import logging
import shutil
import re
import subprocess
logging.getLogger().setLevel(logging.INFO)
search_path = str(sys.argv[1])
search_string_pattern= r'(.*)\.(\d\d\.\d\d\.\d\d)\.(.*)-.*\.mp4'
for parent, dirnames, filenames in os.walk(search_path):
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import MySQLdb
class cMySql:
conn = None
cur = None
conf = None
def __init__(self, **kwargs):
self.conf = kwargs
self.conf["keep_alive"] = kwargs.get("keep_alive", False)
self.conf["charset"] = kwargs.get("charset", "utf8")
self.conf["host"] = kwa... |
# -*- coding: utf-8 -*-
from django.db import models
class Cliente(models.Model):
codigo_cliente=models.IntegerField(unique=True)
nombre_completo=models.CharField(max_length=200)
apellido=models.CharField(max_length=100)
nombre=models.CharField(max_length=100)
tipo_documento=models.CharField(max_le... |
import os
from optparse import OptionParser
import pandas as pd
import numpy as np
import common
import cy_lda
import file_handling as fh
def main():
usage = "%prog data_dir model_dir"
parser = OptionParser(usage=usage)
(options, args) = parser.parse_args()
data_dir = args[0]
model_dir = args[... |
"""
Base spec for Forcepoint NGFW Management Center connections. This is a session
that will be re-used for multiple operations against the management
server.
"""
import inspect
import traceback
from ansible.module_utils.basic import AnsibleModule
from distutils.version import StrictVersion
try:
from smc import s... |
from django.db import models
# Create your models here.
class Poll(models.Model):
name = models.CharField(max_length=60, null=True, blank=True)
def __str__(self):
return '{}'.format(self.name)
class Meta:
verbose_name = "Poll"
verbose_name_plural = "Polls"
|
{
"nbformat": 4,
"nbformat_minor": 0,
"metadata": {
"colab": {
"name": "Untitled3.ipynb",
"provenance": [],
"authorship_tag": "ABX9TyP/t+bTW1yYGaPDicgL+K4r",
"include_colab_link": true
},
"kernelspec": {
"name": "python3",
"display_name": "Python 3"
},
"lang... |
import pytorch_lightning as pl
from pytorch_lightning.callbacks import LearningRateMonitor, ModelCheckpoint
from pytorch_lightning.loggers import TensorBoardLogger
from src.data import MNISTDataModule
from src.model import MLPMixerLightning
def main():
data_module = MNISTDataModule(data_dir="./data/", batch_size... |
#!/usr/bin/env python
import serial
import sys
def isBin(x):
try:
a = int(x,base=2)
except ValueError:
return False
else:
return True
if __name__ == '__main__':
# Parse arguments
argNum = len(sys.argv)
if (argNum != 5):
print >> sys.stderr,"Invalid number of... |
from abc import ABC
class QRCodeHandler(ABC):
"""
An interface describing an object that can handle the content of a detected QR code
"""
def handle_code(self, code_content: str):
# TODO: Implement a code filter
pass
|
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect
from django.forms import ChoiceField, MultipleChoiceField
from django.http import Http404
from django.contrib import messages
from ..controllers.groupcontroller import groupcontroller, is_in_group, return_group_from... |
# Funções
x = 2
y = 3
def somar(x, y):
resultado = x+y
return resultado
print('Soma: ' + str(somar(x,y)))
def subtrair(x,y):
return(y-x)
print('Subtração: ' + str(subtrair(x,y)))
def multiplicar(x, y):
return(x*y)
print('Multiplicação: ' + str(multiplicar(x,y)))
def dividir(x,y):
return(y/x)
pri... |
'''# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from modeltranslation.translator import TranslationOptions, translator
from pydaygal.speakers.models import Speaker
class SpeakerTranslationOptions(TranslationOptions):
fallback_languages = {'default': ('gl', 'es', 'ca', 'en')}
translator.regist... |
#https://www.hackerrank.com/challenges/closest-numbers/problem
n=int(input())
lst=[int(x) for x in input().split()]
sortedlst=sorted(lst)
difference=[]
for i in range(1,n):
difference.append(sortedlst[i]-sortedlst[i-1])
minimum=min(difference)
#print(sortedlst)
#print(difference)
for i in range(n-1):
if differ... |
import os
from keras.applications.vgg16 import VGG16
from keras.models import Sequential, Model
from keras.layers import Input, Activation, Dropout, Flatten, Dense
from keras.preprocessing.image import ImageDataGenerator
"""
学習済み重みをロードしてテストデータで精度を求める
"""
result_dir = 'results'
classes = ['Tulip', 'Snowdrop', 'LilyVa... |
"""
======================
Make a multiview image
======================
Make one image from multiple views.
"""
print __doc__
from surfer import Brain
sub = 'fsaverage'
hemi = 'lh'
surf = 'inflated'
brain = Brain(sub, hemi, surf)
###############################################################################
# S... |
import pymysql
import gevent
import time
"""
1.使用pymysql多行插入(提高效率)--executemany
2.使用python协程(遇到I/O操作就切换任务,无需等待,提高效率)gevent.spwan + gevent.joinall
30w条数据耗时8s
"""
class MyPyMysql:
def __init__(self):
self.host = 'localhost'
self.port = 3306
self.username = 'root'
self.password = 'xu13939201399@'
self.db = 'db... |
from rest_framework import serializers
from .models import *
from drf_role.models import *
from django.db import transaction
from django.contrib.auth.hashers import make_password, check_password
import datetime
from django.http import JsonResponse
class CoordinateSerializer(serializers.ModelSerializer):
class Me... |
#using my first module
import mymodule
mymodule.say_hi()
print('Version', mymodule.__version__)
print('Module name', mymodule.__name__)
|
from rest_framework import status
from rest_framework.test import APITestCase
from django.contrib.auth.models import User
from src.tasks.models import Task
class UsersTests(APITestCase):
def setUp(self):
user = User.objects.create(username='firstUser')
user.set_password('12345')
user.sav... |
# -*- coding: utf-8 -*-
{
'name' : 'LC Report Generator',
'summary': "LC report management",
'description': 'Simplly creat your LC report',
'author': "Metaporphosis.com.bd",
'website': "http://www.metamorphosis.com.bd/",
'version': '0.1',
'depends': [
'base',
'account',
... |
import time
import pyautogui
import keyboard
time.sleep(5) # execute paint
distance = 300
while distance > 0:
if keyboard.is_pressed('p'):
while True:
if keyboard.is_pressed('r'):
break
pyautogui.drag(distance, 0, duration=0.2) ... |
import numpy as np
import experiment as ex
import sys
sys.path.append('../marcos_client')
import matplotlib.pyplot as plt
import pdb
st = pdb.set_trace
def trapezoid(plateau_a, total_t, ramp_t, ramp_pts, total_t_end_to_end=True, base_a=0):
"""Helper function that just generates a Numpy array starting at time
... |
#!/usr/bin/python
import os # to get environment vars
import argparse # to deal with given arguments
import shutil # for copying files over
# function that returns the string of the input file corresponding to the given nodes and ppn
def get_input_file_name(nodes, proc_per_node, default=False):
if default:
... |
from pairSum import *
__author__ = 'Mohamed Fawzy'
arr = [2, 3, 4, 5, 6, 7, 8, 7]
print pair_sum(arr, 4)
print pair_sum(arr, 5)
print pair_sum(arr, 10)
print pair_sum(arr, 13)
print pair_sum(arr, 15)
print pair_sum(arr, 17)
|
words= 'cat', 'dog', 'hamster', 'chicken'.split()
# takes a string in python and converts it to a list variable. each space creates a new element list
def get_name():
#Ask user their name and return name.
name = input("What is your name?").capitalize()
return name
def long_name():
# Ask user ... |
# Generated by Django 3.2.4 on 2021-07-06 15:56
from django.db import migrations, models
import uuid
import zigida.core.utils
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Location',
fields=[
... |
from base import ControllerBase
from model.activity import Activity as ActivityModel
class AdminIndex(ControllerBase):
def get(self):
view_model = {}
self.template('admin/index', view_model)
class AdminActivity(ControllerBase):
def get(self):
vi... |
from pynput import keyboard
# The event listener will be running in this block
with keyboard.Events() as events:
for event in events:
if event.key == keyboard.Key.esc:
break
else:
print('Received event {}'.format(event))
|
# Ejercicio 3
# Crea un script llamado generador.py que cumpla las siguientes necesidades:
#
# Debe incluir una función llamada leer_numero().
# Esta función tomará 3 valores: ini, fin y mensaje.
# El objetivo es leer por pantalla un número >= que ini y <= que fin.
# Además a la hora de hacer la lectura se mostrará en ... |
"""
Todoist API 를 이용해서 대량의 Task 를 자동으로 추가합니다.
기본 사용 방법
=========================
python -m task_script --tasks TASKS
"""
import argparse
import yaml
from .constants import TODOIST_API_KEY
# fmt: off
parser = argparse.ArgumentParser()
parser.add_argument("--tasks", type=str, required=True, help="Task 목록 파일 위치")
# ... |
import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from brokenapp.lib.base import BaseController, render
log = logging.getLogger(__name__)
class XssController(BaseController):
def index(self):
# Return a rendered temp... |
# -*- coding: utf-8 -*-
from contracts import contract
from mcdp_hdb import DiskMap, Schema, SchemaString
from mcdp_hdb_tests.testcases import get_combinations
@contract(returns='dict(str:isinstance(DataTestCase))')
def testcases_arrays():
db_schema = Schema()
db_schema.list('alist', SchemaSt... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ***************************************************************************
# Copyright (c) 2019 西安交通大学
# All rights reserved
#
# 文件名称:Main.py
#
# 摘 要:针对G4问题的skco方法
#
# 创 建 者:上官栋栋
#
# 创建日期:2019年1月10号
#
# 修改记录
# 日期 修改者 版本 修改内容
# ------------- ------- ----... |
from django.contrib import admin
from .models import *
# Register your models here.
admin.site.register(Agent)
admin.site.register(Client)
admin.site.register(CustomUser)
admin.site.register(Pro)
admin.site.register(Specialty)
|
import sqlite3
conn = sqlite3.connect(r"C:\Users\Wizard\Documents\Python\Udemy\Python3Bootcamp\SQL\friends.db")
# create cursor object
c = conn.cursor()
# c.execute("SELECT * FROM friends WHERE first_name IS 'Cara'")
c.execute("SELECT * FROM friends WHERE closeness > 5 ORDER BY closeness DESC")
# Iterate over cursor... |
# https://atcoder.jp/contests/arc097/tasks/arc097_b
class UnionFind:
def __init__(self, elements):
self.elements = elements
def same(self, a, b):
return self.find(a) == self.find(b)
def find(self, a):
parent = self.elements[a]
if parent < 0:
return a
sel... |
from app.main.model.candidate_model import CandidateModel
from app.main.model.recruiter_model import RecruiterModel
from flask_restx.inputs import email
from app.main.util.response import response_object
from functools import wraps
from flask_jwt_extended import jwt_required
from flask_jwt_extended.utils import get_jwt... |
# ex 7 Circle Intersection. Created by SaidakbarP 12/24/2019
from graphics import *
def main():
#r = int(input("Enter Radius of the circle: "))
win = GraphWin("Circle Intersection", 640, 640)
win.setCoords(-10, -10, 10, 10)
# entry box for radius
radius_entry = Entry(Point(-3, 9), 10)
radius_en... |
from django.urls import include, path
from django.conf.urls import url
from tracking.views import update_view, allupdate_view, sticky_impression, clicks_impression
urlpatterns = [
url(r'^update_view/$', update_view, name='update_view'),
url(r'^allupdate_view/$', allupdate_view, name='allupdate_view'),
... |
verhoeff_table_d = (
(0,1,2,3,4,5,6,7,8,9),
(1,2,3,4,0,6,7,8,9,5),
(2,3,4,0,1,7,8,9,5,6),
(3,4,0,1,2,8,9,5,6,7),
(4,0,1,2,3,9,5,6,7,8),
(5,9,8,7,6,0,4,3,2,1),
(6,5,9,8,7,1,0,4,3,2),
(7,6,5,9,8,2,1,0,4,3),
(8,7,6,5,9,3,2,1,0,4),
(9,8,7,6,5,4,3,2,1,0))
verhoeff_table_p =... |
from uuid import UUID
from django.conf import settings
from django.contrib.auth import login as auth_login
from tokenauth.models import Token
def login(request, silence=False):
param_name = 'token'
if hasattr(settings, 'TOKENAUTH_PARAMETER_NAME'):
param_name = settings.TOKENAUTH_PARAMETER_NAME
... |
#!/bin/python3
import sys
a = [0]
for x in range(1, 200):
newTerm = x ^ a[x-1]
a.append(newTerm)
for x, y in enumerate(a):
print(x, y)
# Q = int(input().strip())
# for a0 in range(Q):
# L,R = input().strip().split(' ')
# L,R = [int(L),int(R)]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2017-05-01 09:04
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
def set_branch_creator(apps, schema_editor):
ProblemBranch = apps.get_model("problems", "Probl... |
"""
Test the `m.Bits` type
"""
import operator
import pytest
import magma as m
from magma import Bits
from magma.testing import check_files_equal
from magma.simulator import PythonSimulator
from hwtypes import BitVector
ARRAY2 = m.Array[2, m.Bit]
ARRAY4 = m.Array[4, m.Bit]
def test_bits_basic():
"""
Basic b... |
import re
t = int(input())
for _ in range(t):
s = input().strip().split(" ")
m = re.match(r'[a-z][\w\.-]+@[a-z]+\.[a-z]{1,3}$', s[1][1:len(s[1])-1])
if bool(m):
print(s[0], s[1])
|
import nose.tools
from angr import SimState, SimHeapPTMalloc
# TODO: Make these tests more architecture-independent (note dependencies of some behavior on chunk metadata size)
def chunk_iterators_are_same(iterator1, iterator2):
for ck in iterator1:
ck2 = next(iterator2)
if ck.base != ck2.base:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function, absolute_import, unicode_literals
import os
import sys
import subprocess
import platform
from six import PY2, string_types
import logging
logger = logging.getLogger(__name__)
TERM_ENCODING = getattr(sys.stdin, 'encoding', N... |
'''
Using sqlalchemy which the necessary code to:
- Select all the actors with the first name of your choice
- Select all the actors and the films they have been in
- Select all the actors that have appeared in a category of you choice comedy
- Select all the comedic films and that and sort them by rental rate
- U... |
import io
import os
from itertools import chain
from typing import List, Optional, Tuple, Union
import requests
from sending.parsers import Entry, parse_flatfile
from sending.curation_files import NewFiles, PepFiles, SubFiles, TrEMBLFiles
class NewAccessionChecker:
"""Checks secondary accessions in NewFiles.
... |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def booklist(request):
return render(request, 'booklist.html')
#return HttpResponse('<h1>Welcome to our store!</h1>') |
# Generated by Django 3.0.7 on 2020-06-28 15:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('OFFICE_PIS', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='address',
old_name='office_id',
... |
def addition_of_powers(a,b,c,d):
print(a**b+c**d)
if __name__ == "__main__":
a=int(input())
b=int(input())
c=int(input())
d=int(input())
addition_of_powers(a,b,c,d)
|
print("Please enter a number!")
first_number = float(input())
print("Please enter second number!")
second_number = float(input())
if second_number > first_number:
print("The second number is bigger!")
elif first_number < second_number:
print("The first is bigger!")
else:
print("Both numbers are equal")
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
version='0.3.0',
description='Ade, a templated file system manager',
author='Lorenzo Angeli',
name='ade',
author_email='lorenzo.angeli@gmail.com',
packages=find_packages(exclude=["test"]),
test_suite="test",
entry_... |
from django.contrib.auth.decorators import login_required
from opaque_keys.edx.keys import CourseKey
from xmodule.modulestore.django import modulestore
from course_api.blocks.api import get_blocks
def require_level(level):
"""
Decorator with argument that requires an access level of the requesting... |
"""Board URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based v... |
import sys, os, time, random
import serial
sys.path.append('..')
import ts_usb
if os.name == 'nt':
import dev_tools
TIMEOUT = 1
MAX_DELAY = 10
PORT = sys.argv[1]
dev = None
def open_port():
return serial.Serial(PORT, timeout=TIMEOUT, writeTimeout=TIMEOUT)
def send_req(com, req):
try:
com.write(ts_usb.cmd_seria... |
__author__ = 'kayzhao'
from pymongo import MongoClient
def getDBTypes():
from utils.typeutils import compare_types
print("typing")
client = MongoClient('mongodb://zkj1234:zkj1234@192.168.1.113:27017/disease')
db = client.disease.do
docs = []
for n, doc in enumerate(db.find()):
docs.ap... |
#! --*--coding:utf-8--*--
#正则表达式 regular expression
import re
# \d \转义 d data
string = '007899'
st = re.match('00\d',string).span()
print(string[st[0]:st[1]])
# span --- 跨度
print(re.match('www','www.baidu.com').span())
# math默认从其实位置开始匹配
print(re.match("com",'www.baidu.com'))
# group
line = "Cats are smarter tha... |
import functools
import sys
n = int(sys.argv[1])
def factorial(n):
if n == 0:
return 1
else:
#print(range(1, n+1))
return functools.reduce(lambda x, y: x * y, range(1, n+1))
print(f"Factorial of ({n}) is {factorial(n)}")
|
import re
import numpy as np
class Label:
# Constants
SPACE_TOKEN = '<space>'
SPACE_INDEX = 0
FIRST_INDEX = ord('a') - 1 # 0 is reserved to space
def __init__(self, transcription: str):
transcription = re.sub('[;:!@#$?.,_\'\"\-]', '', transcription)
self.__text: str = transcript... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.