text stringlengths 8 6.05M |
|---|
# Python Imports
from xml.dom import minidom
import httplib
# Local Imports
import globals
from helpers import *
def do_xml(self, xml, **kwargs):
"""
Base function to send/receive xml using either GET or POST
Optional Parameters:
timeout, ip, port, return_result, print_error, close_xml, print_xml, re... |
import sys
print(sys.version_info)
age = input("Enter age:\n")
age = int(age)
if age < 5:
print("To young for school")
elif age == 5:
print("Go to Kindergarten")
elif (age > 5) and (age <= 17):
grade = age - 5
print("Go to {} grade".format(grade))
else:
print("Go to college")
|
{
"targets": [
{
"target_name": "collective_jl",
"sources": [
"src/server/lib/collective_jl.cpp"
],
"include_dirs": [
"<!@(node -p \"require('node-addon-api').include\")",
"/opt/julia/include/julia"
],
"dependencies": [
"<!(node -p \"require('nod... |
'''
given a folder of disk image, calculate the cdr of each images and save cdr to a file.
'''
from MNet_CDR_Seg import *
from utils import *
from config import get_config
from joint import resize_and_joint
import tensorflow as tf
import sys
from glob import glob
import os
import argparse
import tensorflow as tf
imp... |
vc = float (input ('Digite o valor da casa que você deseja comprar.'))
vs = float (input ('Digite o seu salario mensal.'))
a = float (input ('Digite um numero em anos que você ira pagar tudo '))
a1 = a * 12 # calcular quantos meses ira pagar
a2 = vc / a1 # calcular o valor do pag por mes.
sa... |
def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
r = a % b
if r == 0:
return b
else:
return gcdIter(b, r)
print gcdIter(6,12)
|
# Copyright (c) 2017-2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
# fmt: off
# isort: skip_file
import builtins as _builtins, sys, typing as _typing
from google.protobuf.descriptor import EnumDescriptor
from google.protobuf.internal.containers... |
'''
Check if glyphs are missing outlines or composites.
Only works on glyphs which have unicodes
'''
import unicodedata as uni
IGNORE_GLYPHS_OUTLINE = [
'uni0000'
]
def check(font):
print '***Check Glyphs have outlines or components***'
masters = font.masters
for i, master in enumerate(masters):
bad_glyphs =... |
# -*- coding: utf-8 -*-
import base64
import hashlib
import logging
import re
from typing import Iterable
from .base import Fetcher, Item
# noinspection PyProtectedMember
logger = logging.getLogger(__name__)
class JandanFetcher(Fetcher):
URL = 'http://jandan.net/ooxx'
def __init__(self, count=5, browser='... |
from django import forms
from forum.models import Topic, Post
from django.forms import ModelForm, Textarea
class PostForm(ModelForm):
class Meta:
model = Post
fields = (
'text',
)
widgets = {
'text': Textarea(attrs={'rows': 4, 'cols': 60}),
}
class... |
import os.path
from os import path
file_path = "E:\\temp\\names.txt"
def write_to_file():
# create file if not exist and open for write OR open file if exists for append mode 'a'
if (path.exists(file_path)):
f = open(file_path, "a", encoding='utf-8')
else:
f = open(file_path, "x", encodin... |
import numpy as np
import clify
import argparse
from config import cnn_config as config
grid = (
[{'curriculum:-1:n_train': 1, 'curriculum:-1:do_train': False}] +
[{'curriculum:-1:n_train': n} for n in 2**np.arange(0, 18, 2)]
)
config = config.copy(
n_controller_units=512,
)
parser = argparse.ArgumentPa... |
"""
Examples of decorated functions to use for testing.
- Function with decorator with no parameters
- Function with decorator with ordered parameters
- Function with decorator with keyword parameters
"""
from .decorators import no_params, with_params, add_one, add_two
@no_params
def dictionary(*args, **kwargs):
... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
# @File:distributiion-example.py
# @Author: Michael.liu
# @Date:2019/2/12
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
#####################
#二项分布
#####################
def binom_pmf_test():
'''
为离散分布
二项分布的例子:抛掷100次硬币,恰好两次正面朝上的概率是多少?
'''
... |
from selenium.webdriver.remote.webdriver import WebDriver
from selenium.webdriver.remote.webelement import WebElement
def error(driver,message):
from main import testLog,test_id,enableScreenshots,detail,FolderLocation
if enableScreenshots:
driver.screenshot(FolderLocation+'/screenshots/test%s.png' % (t... |
# Copyright (c) 2017-2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
from pygments.lexer import inherit
from pygments.lexers.haskell import HaskellLexer
from pygments.token import Keyword
class DAMLLexer(Haske... |
def countX(lst, x):
count = 0
for ele in lst:
if (ele == x):
count = count + 1
return count
lst = [7, 5, 6, 1, 9, 10, 6, 88, 6]
x = 6
print('{} has occurred {} times'.format(x, countX(lst, x)))
|
'''import flask, os, sys
import requests
app = flask.Flask(__name__)
counter = 12345672
@app.route('/<path:page>')
def custome_page(page):
if page == 'favicon.ico': return ''
global counter
counter += 1
try:
template = open(page).read()
except Exception as e:
template = str(e)
template += "\n<!-- page: %s... |
import json
cached_contact_data = {}
def search(query):
contact_data = get_contact_data()
if contact_data and query:
return json.dumps(search_by_all_fields(query, contact_data))
else:
return ''
def search_by_name(query, contact_data):
result = []
for contact in contact_data:
... |
import numpy as np
def main():
input_np = np.loadtxt(fname = "input")
fuels = [calc_fuel(x) for x in input_np]
print(calc_fuel(12))
print(calc_fuel(1969))
print(np.sum(fuels))
def calc_fuel(x, fuels = np.array([])):
fuel = x // 3 - 2
if fuel > 0:
fuels = np.append(fuels, fuel)
... |
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer
def is_there_nan_values(df):
"""
Check if there are NaN values in Dataframe
:param df: Dataframe to analyze
:return: True if NaN values encounted else False
"""
return False if np.sum(df.isnull()... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Validators for labman2 data model and labman2 data form fields"""
from django.utils.translation import ugettext as _
from django.core.validators import RegexValidator, slug_re
import re
#from django.core.exceptions import ValidationError
# pylint: disable=C010... |
oldsize=3024
newsize=442
combined_rule="/Users/mengqizhou/Desktop/datamining/assignment5/algorithm2/14/combinedrules/11"
new_rule="/Users/mengqizhou/Desktop/datamining/assignment5/algorithm2/14/prunedrules3/11"
old_rule="/Users/mengqizhou/Desktop/datamining/assignment5/algorithm2/14/combinedrules/11"
oldrules=[]
dest=o... |
from selenium.common.exceptions import NoSuchElementException
from .base import FunctionalTest
class LoginTest(FunctionalTest):
def setUp(self):
super(LoginTest, self).setUp()
# Create users to login
self.assistant_data = {'username': 'assistant', 'password': 'demo'}
self.operator_... |
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="uddup",
version="0.9.3",
author="Rotem Reiss",
author_email="reiss.r@gmail.com",
description="URLs Deduplication Tool.",
long_description=long_description,
long_desc... |
import nltk
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
from nltk.stem.snowball import SnowballStemmer
from builtins import str
import csv
import sys, getopt
import xml.etree.ElementTree as ET
from xml.dom.minidom import parse, Node
import xml.dom.minidom
from num... |
from django.conf.urls import url
from info import views
urlpatterns = [
url(r'^$', views.info, name='info'),
url(r'inj/(?P<slug>[\w\-]+)/$', views.info_inj, name='info_inj'),
url(r'cri/(?P<slug>[\w\-]+)/$', views.info_cri, name='info_cri'),
url(r'pre/(?P<slug>[\w\-]+)/$', views.info_pre, name='info_pr... |
from django.contrib import admin
from .models import Book, Author, BookOrder, Cart, Review
class BookAdmin(admin.ModelAdmin):
list_display = ('title', 'author', 'price', 'stock')
class AuthorAdmin(admin.ModelAdmin):
list_display = ('last_name', 'first_name')
class BookOrderAdmin(admin.ModelAdmin):
lis... |
import pymysql.cursors
from fixture.db import DbFixture
#from fixture.orm import ORMFixture
#from model.group import Group
connection = pymysql.connect(host="127.0.0.1", database="bugtracker", user="root", password="")
db = DbFixture(_host="127.0.0.1", _database="bugtracker", _user="root", _password="")
try:
lis... |
import json
import urllib
serviceurl = raw_input('Enter location: ')
if not serviceurl: serviceurl = 'https://python-data.dr-chuck.net/comments_42.json'
#if not serviceurl: serviceurl = 'https://python-data.dr-chuck.net/comments_283750.json'
print 'Retrieving', serviceurl
uh = urllib.urlopen(serviceurl)
data = uh.rea... |
from src import get_timed_loop_from_config, currencies_list_from_config, get_exchange_data, convert_dic_to_list
from module import CurrencyExchangeRepository
import threading
LOOP_TIME = get_timed_loop_from_config()
def fetch_and_upload_to_db():
threading.Timer(LOOP_TIME, fetch_and_upload_to_db).start()
curr... |
#!/usr/bin/python3
'''
global
'''
x = 9
def example():
#declare global variables
global x
print(x)
x+=9
print(x)
# local variables
s= x+90
print(s)
example();
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2019-04-30 15:39
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user_input', '0057_dailyactivity_start_time_in_seconds'),
]
operations = [
... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import absolute_import, division, print_function, unicode_literals
from wadebug import results
from wadebug.wa_actions.base im... |
import cv2
import matplotlib.pyplot as plt
img = cv2.imread('bird.png', 1)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
R, G, B = cv2.split(img)
output1_R = cv2.equalizeHist(R)
output1_G = cv2.equalizeHist(G)
output1_B = cv2.equalizeHist(B)
output1 = cv2.merge((output1_R, output1_G, output1_B))
# clahe = cv2.cre... |
import csv
from termcolor import colored
from collections import defaultdict
import datetime
from taxutils import *
basis_prices = defaultdict(list)
basis_dates = defaultdict(list)
basis_sizes = defaultdict(list)
basis_fees = defaultdict(list)
def buy(product, price, tran_date, size, fee = 0):
# print("BUY {} tran... |
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD)
Motor1A = 22
Motor1B = 21
Motor1E = 18
LED1 = 8
GPIO.setup(LED1,GPIO.OUT)
GPIO.setup(Motor1A,GPIO.OUT)
GPIO.setup(Motor1B,GPIO.OUT)
GPIO.setup(Motor1E,GPIO.OUT)
print "LED"
GPIO.output(LED1,GPIO.LOW)
print "Turning motor on"
GPIO.output(... |
import numpy as np
import cv2 as cv
import matplotlib.pyplot as plt
from skimage.util import random_noise
# path of images
img_path = '.\\Images\\Gaussian.jpeg'
# read image form file
img = cv.imread(filename=img_path, flags=cv.IMREAD_GRAYSCALE)
# different standard deviations
stds = [0.01, 0.05, 0.1, 0.... |
#####################################################
## librealsense T265 to MAVLink ##
#####################################################
# This script assumes pyrealsense2.[].so file is found under the same directory as this script
# Install required packages:
# pip install pyrealsense2
# ... |
import io
import requests
import zipfile
f = io.StringIO()
#f = io.BytesIO()
f.write('string io')
# f.write(b'string io')
f.seek(0) # 先頭へ
print(f.read()) # string io
# read zip file
f = io.BytesIO()
url = 'https://drive.google.com/file/d/1qRibiuruk3u3dv531N5iHazkdzsmoxi6/view?usp=sharing'
res = requests.get(url)
f... |
from key_expansion import subWord, rotWord
from utils import combine_byte, separate_bytes, mix_matrix, get_rounds, sub_byte, shift_row, create_state_block, print_state_block, convert_block_to_stream, block_to_text
from ff_algorithm import ff_multiply, ff_add
import logger
def subBytes(state):
for i in range(len(st... |
from ..extensions import cache
from .models import InvCategory, InvMarketGroups, DgmTypeEffects
from .consts import dogma_effects_slots, market_groups_filter
class EVEStaticDataService(object):
@cache.memoize()
def get_types_by_category(self, category_id):
category = InvCategory.query.filter_by(cate... |
#!usr/bin/env python
# -*- coding:utf-8 -*-
# import numpy as np
import numpy as np
from scipy.optimize import minimize, linprog
def slice(lowbound=1, upbound=10):
'''
:param lowbound: 比例的下界
:param upbound: 比例的上界
:return:
'''
rho1, rho2, rho3 = np.random.uniform(lowbound, upbound, 3)
sum =... |
# Thanks to ChristianECooper's comments about the regex and findall problems
from itertools import groupby
from re import split
VOWELS = set('aeiouAEIOU')
def flesch_kincaid(text):
sentences = syllables = words = 0.0
for sentence in split(r'[!.]', text):
if not sentence:
break
for... |
year = int(input("请输入年份:"))
month = int(input("请输入月份:"))
day = int(input("请输入日:"))
months = (0,31,59,90,120,151,181,212,244,273,304,334)
if 0 < month <=12:
sum = months[month - 1]
else:
print("输入错误!")
sum += day
flag = 0
if (year %400 == 0) or (year % 100 == 0 and year % 4 ==0):
flag = 1
if (flag ==... |
# !/usr/bin/python
# -*- coding: UTF-8 -*-
from helloworld.runoob1 import runoob1
from helloworld.runoob2 import runoob2
runoob2()
runoob1()
|
from django.db import models
from django.conf import settings
from django.template.defaultfilters import slugify
from django.utils.html import strip_tags
from tinymce import HTMLField
from filebrowser.fields import FileBrowseField
# Create your models here.
class Category(models.Model):
category_name = models.CharFi... |
"""Entry point for TwitOff Flask application."""
from twistoff.app import create_app
APP = create_app() |
from xml.etree import ElementTree
import csv
import io
import os
import mechanize
from bs4 import BeautifulSoup
#pasta onde encontra os xmls
diretorio = 'BDTD_USP/'
#array para armazenar todos os arquivos encontrado no diretorio
files = []
for file in os.listdir(diretorio):
if file.endswith(".xml"):
files.... |
import math
from utils import *
import numpy as np
import random
from numpy.core.numeric import normalize_axis_tuple
class Bird:
def __init__(self, x, y):
self.pos_x, self.pos_y = x, y
self.angle = random.random() * math.pi * 2
self.dir = np.array([math.cos(self.angle), math.sin(self.ang... |
from selenium import webdriver
link = "http://suninjuly.github.io/find_xpath_form"
try:
browser = webdriver.Chrome()
browser.get(link)
browser.find_element_by_tag_name('input').send_keys("Ivan")
browser.find_element_by_name('last_name').send_keys("Petrov")
browser.find_element_by_class_name('city... |
# 변수의 선언과 할당
# a = 1
# b = 1.1
#변수를 선언하고 변수에 들어 있는 데이터 확인하는 방법
# print(a + b)
# 다양한 형태로 선언과 할당
# c, d = 1, 1.1
# print(c + d)
# x, y = 12, 30
# print(x, y)
# x = y
# print(x, y)
# x, y = 12, 30
# x, y = y, x
# print(x, y)
# 영어, 숫자로 구성(한글도 가능)
# a123 = 1
# 한글가능 = 2
# print(a123 + 한글가능)
# 띄어쓰기 금지. 언더바(_)로 표시
#한글 가능 ... |
from django.db import models
class PageCounter(models.Model):
objects = models.Manager()
count = models.IntegerField(verbose_name="방문자수")
# 나라별 검색 및 총 좋아요 랭킹
class Nation(models.Model):
nation_list = (
('Afghanistan', '아프가니스탄'),
('Albania', '알바니아'),
('Algeria', '알제리아'),
('... |
import time, pytest,sys,os
sys.path.insert(1,os.path.abspath(os.path.join(os.path.dirname( __file__ ),'..','..','lib')))
from clsCommon import Common
import clsTestService
from localSettings import *
import localSettings
from utilityTestFunc import *
class Test:
#============================================... |
import math, random, sys, fileinput
inputs = fileinput.input()
# Main Class
class Main():
def __init__(self, inputs):
stack = []
quote_queue = []
open_braces = ["{","["]
close_braces = ["}","]"]
quotes = ["\'","\"",":",","]
floating_point = ['a','b','c']
for line in inputs:
print_line = True
f... |
from redis_queue import RedisQueue
from redis_dictionary import RedisDictionary
import redis
from lxml.html import fromstring
from urllib.parse import urlparse
import json
import re
import os
import requests
class BeletagCallback:
def __init__(self):
self.q_pages_name = 'beletag_pages'
self.q_eleme... |
""" Constants file for Auth0's seed project """
JWT_PAYLOAD = 'jwt_payload'
ACCESS_TOKEN = 'access_token'
USER_EMAIL = 'user_email'
USER_ID = 'user_id'
PERMISSION = 'permission'
ROLE = 'role'
|
# 扑克牌初始化
import abc
import random
class Card:
"""卡牌基类."""
def __init__(self, rank, suit):
"""
:param rank: 大小.
:type rank: str
:param suit: 花色.
:type suit: str
"""
self.suit = suit
self.rank = rank
self.hard, self.soft = self._points()
... |
import random
import numpy as np
p_n = 50
n_dimensions = 30
n_iter = 1000
def population():
pop = [np.random.choice([0, 1], size=(n_dimensions)) for i in range(p_n)]
return pop
def fitness(pop):
pop.sort(key=sort_key, reverse=True)
return pop
def selection(pop):
r1 = np.random.randint(0, len(... |
from django.shortcuts import render
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.contrib.auth.decorators import login_required
im... |
import numpy as np
from copy import deepcopy
''' Some kinds of SGD algorithms
Our target is to decide how to update theta
'''
class SGD:
''' Stochastic Gradient Descent:
g[t] = ∇[θ[t−1]]f(θ[t−1])
θ[t] = θ[t-1] - η * g[t]
'''
def update(self, g):
return g
class Momentum... |
import multiprocessing
import adns
import logging
rr = adns.rr.A
def worker(q, c, f, n):
print q.qsize()
with n:
if q.empty():
print "Nothing in the queue"
f.set()
else:
host = q.get()
# print host
c.submit(host, rr)
n.notify... |
from re import compile, match
REGEX = compile(r'^(?P<h>\d{2}):(?P<m>[0-5]\d):(?P<s>[0-5]\d)\Z')
def to_seconds(time):
m = match(REGEX, time)
if m:
hms = m.groupdict()
return int(hms['h']) * 3600 + int(hms['m']) * 60 + int(hms['s'])
|
import pandas as pd
df = pd.read_csv("..\data\ordersList.csv",encoding="utf-8",header = 0)
print(df.pivot_table(index="品名",columns="客戶名稱", values="金額", \
fill_value=0, margins=True, aggfunc="sum")) |
"""
Run multiple parameter with multiple GPUs and one python script
Usage: python run_all.py
Author: Xu Zhang
Email: xu.zhang@columbia.edu.cn
"""
#! /usr/bin/env python2
import numpy as np
import scipy.io as sio
import time
import os
import sys
import subprocess
import shlex
import argparse
######################... |
class Reservation:
def __init__(self, location, time_block, spots_available):
self.location = location
self.time_block = time_block
self.spots_available = spots_available
def dictify(self):
return {
'location' : self.location,
'time_block' : self.time_... |
from classes.ListNode import ListNode
class Solution(object):
ListNode: ListNode
def mergeTwoLists(self, l1, l2):
"""
attempt to learn linked list in python. could not solve.
"""
result = curr = ListNode(0)
while(l1 or l2):
if not l2:
... |
#
# author : Omid Sharghi (omid.sharghi@sjsu.edu)
#
from pandas import ExcelWriter
from sklearn.preprocessing import Imputer
from sklearn.preprocessing import MinMaxScaler
import numpy as np
import pandas as pd
def sanitize_and_scale(file_name):
if file_name.endswith('.csv'):
df = pd.read_csv(file_name)
... |
import os
import shutil
import subprocess
import tarfile
# Used this function for compatibility issues (subprocess.run) don't work for all Python versions
def run(*popenargs, **kwargs):
input = kwargs.pop("input", None)
check = kwargs.pop("handle", False)
if input is not None:
if 'stdin' in kwargs... |
from typing import Dict
from src.contracts.ethereum.multisig_wallet import MultisigWallet
from src.signer.eth.impl import EthSignerImpl
from src.contracts.ethereum.erc20 import Erc20
from src.util.common import Token
from src.util.config import Config
from src.util.web3 import web3_provider
class _ERC20SignerImpl(Et... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
def lee_entero():
""" Solicita un valor entero y lo devuelve.
Mientras el valor ingresado no sea entero, vuelve a solicitarlo. """
while True:
valor = raw_input("Ingrese un número entero: ")
try:
valor = int(valor)
retur... |
import pandas as pd
import numpy as np
from tqdm import tqdm
"""计算每张图片中的box与其它框的iou"""
def box_area(boxes):
"""
Computes the area of a set of bounding boxes, which are specified by its
(x1, y1, x2, y2) coordinates.
Arguments:
boxes (Tensor[N, 4]): boxes for which the area will be computed. The... |
from flask import Blueprint,render_template
users=Blueprint('users',__name__)
@users.route('/')
def index():
user={'username':'sarpong'}
return render_template('index.html',user=user)
@users.route('/profile/')
def profile():
return render_template('profile.html')
|
from django.conf.urls import url
from progress_analyzer import views
# from quicklook.views import export_users_xls
urlpatterns = [
url(r'^user/report$',views.ProgressReportView.as_view(),
name="progress_analyzer_report"),
url(r'^user/report/(?P<year>\d{4})/(?P<month>\d{1,2})/(?P<day>\d{1,2})$$',views.Prog... |
"""
Josh Rudolph
BIMM185
4/6/17
"""
with open("TCDB.faa", "r") as rfile:
headers = []
protSeq = ""
proteins = []
x=0
for line in rfile:
if x==98:
break
if line[0] == '>':
splitHeader = line.rstrip('\n').split('|')
headers.append(splitHeader)
if x == 0:
continue
proteins.append(protSeq)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
"""
import facebook
def send_the_post(msg):
"""
Ecrit un post facebook
:param msg: le message que l'on veut écrire
:return:
"""
# Fill in the values noted in previous steps he... |
import pygame
from random import randint
class Snow:
def __init__(self):
"""self.xpos = [0,100, 200, 300, 400, 500, 600, 700, 800, 900, 1000,
50, 150, 250, 350, 450, 550, 650, 750, 850, 950, 1050,
25, 125, 225, 325, 425, 525, 625, 725, 825, 925, 1025,
... |
#!/usr/bin/env python
# Copyright 2014 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies building a project hierarchy created when the --generator-output=
and --depth= options is used to put the build configuration files... |
#!/usr/bin/env python
#coding:utf-8
'''
用来协助调试发送邮件
Test data
Let's populate the database with the example.org domain, a john@example.org email account and a forwarding of
jack@example.org to john@example.org. Open a MySQL shell and issue the following SQL queries:
INSERT INTO `mailserver`.`virtual_domains` (
... |
from scapy.all import *
import subprocess
from flux_led import WifiLedBulb, BulbScanner
import datetime
import os
import sys
version = "1.0.3 " # assign version number for debugging
bulb = WifiLedBulb('192.168.XX.XX') # assign bulb IP
#bulb.refreshState() # refresh state to collect accurate staus
logfile = r"/home/p... |
import pyglet
from pyglet.gl import *
from gauge import gauge_parent
import common
import variable
import math, time
import text
class gauge_c(gauge_parent):
def __init__(self, *args, **kwds):
super(gauge_c, self).__init__(*args, **kwds)
self.x = 300
self.y = 300
... |
import scipy.stats as st
p = 0.2
for i in range(0, 10):
u = st.uniform(0, 1)
if u.rvs() < p:
print "bellow", p
|
#!/usr/bin/python
'''
Usage: jokebot.py [--debug] [-p <port>] [-H <host>]
Options:
-p, --port=<port> The port number on which to run Flask [default: 5000]
-H, --host=<host> The host to listen to [default: 127.0.0.1]
--debug Flag to determine debug mode [default: False]
'''
import json, req... |
import sys
sys.path.append('.')
import torch
import torch.nn as nn
from ModelWrapper import *
from functions import get_para
from libs.random_fault import *
def train_test():
Conf.load(filename="configs/cfg.yaml")
net = ModelWrapper(net_name='VGG', dataset_name='cifar100')
net.train()
_, acc = net.ve... |
from SignalGenerationPackage.SignalTransformer import SignalTransformer
from SignalGenerationPackage.Point import Point
class ExperimentScheduleTransformer(SignalTransformer):
def __init__(self, SignalData):
super().__init__(SignalData)
# overridden
def TransformSignal(self):
# В функции ... |
import numpy as np
def accuracy_score(y_true: np.ndarray, y_pred: np.ndarray):
diff = y_true - y_pred
acc = len(np.where(diff == 0)[0])
return acc / len(y_true)
def sn_sp(y_true: np.ndarray, y_pred: np.ndarray):
"""
需要输入为 1 or -1
:param y_true:
:param y_pred:
:return:
"""
t,... |
#!/usr/bin/env python
# -----------------------------------------------------------------------
# runserver.py
# Author: Sophie Li, Connie Xu, Jayson Wu
# -----------------------------------------------------------------------
from sys import argv, exit, stderr
from rebook import app
def main(argv):
if len(arg... |
import maya.cmds as cmds
class Toolbox():
def __init__(self):
self.myWin = 'amToolbox'
self.createWin()
def createWin(self):
self.delete()
self.myWin = cmds.window(self.myWin, title='amToolbox')
self.myColl = cmds.columnLayout(parent=self.myWin, adjustable... |
def solution(spell, dic):
answer = 2
for i in dic:
sub = list(i)
if len(sub) == len(set(sub)) and set(sub) == set(spell):
return 1
return answer |
s=input()
l=[]
for x in s:
l.append(x)
l.sort()
for x1 in l:
print(x1,end="")
|
def validar_entrada1( texto ):
try:
return str(long(texto))
except ValueError:
return ""
def validar_entrada2( texto ):
try:
return str(float(texto))
except ValueError:
return ""
def pelas_a_euros( entrada ): #Aquí viene lo que han tecleado
return... |
import boto3
import sys
region = sys.argv[1]
access_key = sys.argv[2]
secret_key= sys.argv[3]
client = boto3.client('ec2',
region_name = region,
aws_access_key_id = access_key,
aws_secret_access_key = secret_key)
myvpc = client.create_vpc(
CidrBlock='192.168.0.0/16',
Instanc... |
import unittest
from simulator.schedulers import SJF
from simulator.tests.base import SchedulerTest
from simulator.tests.test_utils import create_processes
class SJFTest(unittest.TestCase, SchedulerTest):
def setUp(self):
self.scheduler = SJF()
def tearDown(self):
self.scheduler.reset()
... |
#To find the average of five numbers
a=input("__Enter first number = ")
b=input("__Enter second number = ")
c=input("__Enter third number = ")
d=input("__Enter fourth number = ")
e=input("__Enter fifth number = ")
av=(a+b+c+d+e)/5
print"____________The average is = ",av
|
import urllib2
def download(url):
print 'Downloading: ', url
try:
html = urllib2.urlopen(url).read()
except urllib2.URLError as e:
print 'Download error: ', e.reason
html = None
return html
#download('http://httpstat.us/500'); |
from gmssl import sm3, func
if __name__ == '__main__':
y = sm3.sm3_hash(func.str_to_list("abc"))
print(y)
|
from django.db import models
from django.core.exceptions import FieldDoesNotExist
from django.http import Http404
from django.db.models import Q
from django.urls import reverse
from .utils import unique_slug_generator, random_string_generator
class ProductQuerySet(models.query.QuerySet):
def search(self, ... |
"""empty message
Revision ID: 1cb5073ef9b1
Revises: fd0fb00bfd08
Create Date: 2019-06-02 23:57:07.332506
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '1cb5073ef9b1'
down_revision = 'fd0fb00bfd08'
branch_labels = None
depends_on = None
def upgrade():
# ... |
from lll.exceptions import (
FormattedError,
)
SOURCE_CODE = """
(seq
(def 'test-const 0xxff)
)
"""[1:-1]
def test_formatted_error_mark_placement():
assert str(FormattedError(
'test error',
SOURCE_CODE,
0, 0,
mark_size=1,
file_name=None,
)) == """
line 1:1: ... |
#!/usr/bin/python3
# -----------------------------------------------------------------------------
# Structures.py
# Custom data structures for gadgets and instructions.
# Author: Eval
# GitHub: https://github.com/jcouvy
# -----------------------------------------------------------------------------
class Gadget:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.