text stringlengths 8 6.05M |
|---|
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 5 21:30:56 2016
@author: wilson
"""
#===============================================
#
# plate with hole - tri
#
#===============================================
import matplotlib.pyplot as plt
import numpy as np
myfontsize = 20
labelfontsize = 14
#==========... |
from bcrypt import gensalt, hashpw
import pytest
from .conftest import check_for_docker
from core.db import session_close
from core.structure import UserClass
from core import utils
DOCKER_RUNNING = check_for_docker()
def _get_password_hash(username, email):
"""Return the password hash for the given user, or No... |
import pika
import json
import threading
import functools
import time
import loggerHelper
import database as db
import dataProcessing as dp
import configparser
def connect():
conf = configparser.ConfigParser()
conf.read("config.ini")
user = conf["rabbitmq"]["user"]
password = conf["rabbitmq"]["passwor... |
seperator = "--------------------------------------------------------"
def report(remotes):
print()
print (
"{0:4}\u2502{1:8}\u2502{2:8}\u2502{3:7}\u2502{4:12}\u2502{5:6}\u2502{6:6}\u2502{7:24}"
.format("id", "name", "langauge", "watched","status", "pid", "errors", "path")
)
print ... |
Q1 = '''SELECT P.player_id, `MatchCaptain`.team_id, P.jersey_no, P.name, P.date_of_birth, P.age
FROM Player AS P JOIN MatchCaptain ON captain = P.player_id
WHERE EXISTS(SELECT player_id FROM Player JOIN MatchCaptain ON captain = `Player`.player_id AND `Player`.player_id = P.player_id)
AND
... |
def pandigitalStr(s):
return ''.join(sorted(s)) == "123456789"
h = 10**8
for x in range(1, 10**4):
s = ''
f = 1
while len(s) < 9:
s += str(x*f)
f += 1
if pandigitalStr(s):
h = max(h, int(s))
print(x)
print(h)
|
import numpy as np
import scipy.io as sio
import operator
import math
K=13 #for running in different parameters, modify this K
def euclideanDistance(instance1, instance2, length):
distance = 0
for x in range(1,length+1):
#distance+=pow((instance1[x]-instance2[x]),2)
distance += abs(instance1[... |
#michelia's python playground****************
#num = [8,5,3]
#num = [3, 1, 2]
#num=[11100989089080211, 1122001231231, 1121389798646546546565465]
#num = [12, 6, 4, 3, 5]
num=['elephants','lunch','can','ants','for','eat']
#print(num[0])
my_len = len(num)
# for count1 in range(0,len(num)):
# for count2 in range(0,le... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/12 16:14
# @Author : WangWei
# @File : func.py
# @Software: PyCharm
import socket
import fcntl
import struct
from conf import settings
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
return socket.inet_ntoa(
fcntl... |
import sys
testCase = int(sys.stdin.readline())
# dfs 탐색 함수
def dfs(node, cnt):
check[node] = 1
for n in graph[node]:
if check[n] == 0:
cnt = dfs(n, cnt+1)
return cnt
for _ in range(testCase):
# n: 나라 수, m: 비행기 종류
N, M = map(int, sys.stdin.readline().split())
# 그래프
... |
from django.shortcuts import render
from rest_framework.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from rest_framework.response import Response
from django.contrib.auth.models import User
from accounts.permissions import Faci... |
# coding=utf-8
import urllib
import urllib2
import cookielib
import sys
import poststatus
import time
import login
from StringIO import StringIO
def zhuanfa():
html=login.login()
index=html.find('写日志')
html=html[index:]
index=html.find('转自')
#print html
while index>=0:
time.sleep(3)
html=html[index:]
ind... |
import pandas as pd
from catboost import CatBoostClassifier
from sklearn.model_selection import train_test_split
df = pd.read_csv("x_train_cat.csv")
test = pd.read_csv("x_test_cat.csv")
##########################################################################################################
# model wm(7.06... |
from django.apps import AppConfig
class LandingConfig(AppConfig):
label = "landing"
name = f"applications.{label}"
|
tupla = 'Jaca', 'Python', 'Bola'
for x in range(0,len(tupla)):
print(f'Na palavra {tupla[x]} temos:')
for vogal in tupla[x]:
if vogal in 'aeiou':
print(vogal)
|
#coding:utf-8
__author__ = 'zhangbin'
python -m json.tool
python -m timeit
dict
dictMerged1=dict(dict1.items()+dict2.items())
dictMerged2=dict(dict1, **dict2)
dictMerged=dict1.copy()
dictMerged.update(dict2)
|
from hashlib import sha1
from threading import Thread, Timer
from time import time
from utils import random_node_id
from bencode import bencode, bdecode, BTFailure
from dht_node import Node
from dht_routetable import R_table
import SocketServer
from threading import Lock, Thread
class DHTRequestHandler(SocketServer.B... |
#!/usr/bin/python3
""" Module for testing file storage"""
from models import storage
import os
from models.place import Place
import unittest
from sqlalchemy.orm.collections import InstrumentedList
from datetime import datetime
import models
from models.engine.db_storage import DBStorage
from models.engine.file_storage... |
#App
HOST = '0.0.0.0'
PORT = 6000
DEBUG = False
#AWS
BUCKET = 'fastermlpipeline'
ACCESS_KEY = 'sorry_itsasecret'
SECRET_KEY = 'sure_itsasecret'
#Extract Data
URL_DATA = 'http://api:5000/credits'
#Preprocessors
NUMERICAL_FEATURES = ['age', 'job', 'credit_amount' ,'duration']
CATEGORICAL_FEATURES = ['sex', 'housing... |
import numpy
n, m = map(int, input().split())
a = []
for _ in range(n):
a.append([int(x) for x in input().split()])
arr = numpy.array(a)
numpy.set_printoptions(sign=' ', legacy='1.13')
print(numpy.mean(arr, axis=1))
print(numpy.var(arr, axis=0))
print(numpy.std(arr, axis=None))
|
'''
Created on Nov 7, 2016
@author: Dayo
'''
import greenswitch
from decimal import Decimal, ROUND_DOWN
from uuid import uuid4
from django.conf import settings
import phonenumbers
from core.exceptions import InvalidPhoneNumberError, NotEnoughBalanceError, FailedDialOutError, MissingCallRateError
from go... |
"""
Module for gocdapi Agents class
"""
from gocdapi.agent import Agent
from gocdapi.gobase import GoBase
from gocdapi.custom_exceptions import GoCdApiException
class Agents(dict, GoBase):
"""
Class to hold information on a collection of Agent objects
This class acts like a dictionary
"""
def ... |
# def sum(x, y):
# return x + y
#
# def subtract(x, y):
# return x - y
# def multiplication(x,y):
# return x * y
# def division(x, y):
# return x / y
#
#
# x = 50
# y = 10
# print(sum(x,y),subtract(x,y),multiplication(x,y),division(x,y))
file = open("myfile.py", "x")
|
import asyncio
import logging
from sqlalchemy.orm import Session
from collector_app import orm
from collector_app import task
from collector_app import worker_queue
from collector_app.configs import collector as config
from rzd_client import models
logger = logging.getLogger(__name__)
class Collector:
_active_... |
#coding:utf-8
#! /usr/bin/env python3
"""Import, get the position, resize and set the transparent background"""
import pygame
from fonction.get_file import get_file_path
def texture_for_sprite(file="", folder="", pos_x=0, pos_y=0, size_x=30, size_y=30, alpha=0):
""" import a texture, get the sprite position and... |
import json
def lambda_handler(event, context):
# TODO implement
sqs = boto3.client('sqs')
sqs_json = {
"message-type":"tar-extract-image"
, "bucket":"bucket"
, "key":"key"
, "image":"image"
, "image_member_name":"image_member_name"
}
sqs.send_message(QueueUrl=os.environ['SqsUrl'], MessageBody=json.d... |
import base64
import hashlib
from Crypto import Random
import Crypto
from Crypto.Cipher import AES
import argparse
import base64
from getpass import getpass
class AESCipher(object):
def __init__(self, key):
self.bs = AES.block_size
self.key = key
def encrypt(self, raw):
pad_key = self... |
from django.shortcuts import render
from django.views.generic import TemplateView, CreateView, FormView
from django.contrib.auth.models import User
from .forms import UserForm
from django.urls import reverse, reverse_lazy
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRe... |
from os.path import getmtime, exists
from datetime import datetime
from matplotlib import pyplot as plt
import seaborn as sns
tt = []
for i in range(100):
path = "{:02}.py".format(i)
if not exists(path):
path = "{:02}.jl".format(i)
assert exists(path)
dt = datetime.fromtimestamp(getmtime(path))... |
#!/usr/bin/env python
"""
Preprocess images and save as uint8 npyz for upload and serving in Heroku app.
Disk space is limited so this script will handle lack of disk space gracefuly
and may be run several times to process/upload/delete the stacks in parts.
"""
import json
import sys
from pathlib import Path
import... |
# -*- coding: utf-8 -*-
import Tkinter as tk
from robotparser import Entry
from pydoc import gui
class InicioSesion:
def __init__(self,master):
self.master=master
self.marcoingreso()
self.marcosalida()
self.mostrarsalida()
self.master.geometry("300x300")
... |
numberOfColours = 11
colours = [[0,0,0],[255,0,0],[0,255,0],[0,0,255],[255,255,0],[255,0,255],[0,255,255],[255,100,100],[100,255,100],[100,100,255],[255,255,255]]
gridSize = 16
norm = True #false if qr is inverted
class thisapp:
def inputReceived(self, list):
x = list[0]
y = list[1]
oldColour = self.colour... |
import sys
#import stdin
import random
import string
import os
#import MySQLdb
def randomword(length):
return ''.join(random.choice(string.lowercase) for i in range(length))
cars = ""
maxCars = ""
timestamp = ""
filename = ""
cars = sys.argv[1]
maxCars = sys.argv[2]
timestamp = sys.argv[3]
filename = sys.argv[4]
... |
from flask_pymongo import PyMongo
mongo = PyMongo()
def initDb(app):
mongo.init_app(app)
# Created Compound text Index for name search feature
mongo.db.users.create_index([('first_name', 'text'), ('last_name', 'text')], default_language='english') |
import os
import copy
import collections
import sys
import yaml
from os import listdir
from config import MODEL, KNOWLEDGE_NET_DIR
from prepare_data import is_in_gold, is_in_gold_uri
import run
import evaluator
filename = "train.json"
from config import MODELS_DIR
path = MODELS_DIR
# Find threshold for models given... |
#!env python3
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
html = '''
<html lang="ja">
<head>
<meta charset="utf-8">
<title> test </title>
</head>
<body>
<h1>test h1</h1>
<ul id="link-list">
<li>
<a href="http://example.com/1">test1</a>
</li>
<li>
<a hre... |
from flask import jsonify, request
from shapely import wkb, wkt, geometry
from geojson import Feature, FeatureCollection, Polygon, MultiPoint
import logging
from . import api
from .. import db, get_db_conn
@api.route('/points/<string:lat>/<string:lng>/<string:radius>', methods=['GET'])
def get_points_by_radius(lat, ... |
#ACTION CLASS
import EntityStorage
import Character
class Action:
"""Object which holds all functions regarding actions in the game"""
def __init__(self):
pass
def update_properties(self): #Updates different properties which are not directly altered through other functions
Enti... |
import requests
from bs4 import BeautifulSoup as bs
url = "https://search.daum.net/search?nil_suggest=btn&w=tot&DA=SBC&q=%EC%86%A1%ED%8C%8C+%ED%97%AC%EB%A6%AC%EC%98%A4%EC%8B%9C%ED%8B%B0"
res = requests.get(url)
res.raise_for_status() # 200 OK 코드가 아닌 경우 에러 발동
soup = bs(res.text, "html.parser")
# with open("quiz.html"... |
class Solution:
def longestPalindrome(self, s):
"""
:type s: str
:rtype: str
"""
mstr = ''
for i in range(len(s)):
tmp = self.findLogest(s,i,i)
if len(tmp) > len(mstr):
mstr = tmp
tmp = self.findLogest(s,i,i+1)
... |
import os
class Estacion:
def __init__(self, codigo, descripcion, latitud, longitud, direccion, cp, poblacion, provincia, pais, cercanias, feve):
self.codigo = codigo
self.descripcion = descripcion
self.latitud = float(latitud.replace(",", "."))
self.longitud = float(longitud.replac... |
Name,Abbr.,Molecular Weight,Molecular Formula,Residue Formula,Residue Weight,pKa,pKb,pKx,pl
Alanine,Ala,A,89.10,C3H7NO2,C3H5NO,71.08,2.34,9.69,–,6.00
Arginine,Arg,R,174.20,C6H14N4O2,C6H12N4O,156.19,2.17,9.04,12.48,10.76
Asparagine,Asn,N,132.12,C4H8N2O3,C4H6N2O2,114.11,2.02,8.80,–,5.41
Aspartic acid,Asp,D,133.11,C4H... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 7 21:00:03 2021
@author: 43739
"""
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import norm
import math
import datetime
from statsmodels.graphics.tsaplots import plot_acf
import data_proce... |
"""Advent of Code 2019 Day 8 - Space Image Format."""
def check_corruption(layers):
"""Return one count * two count of layer with the least zeros in it."""
least_zeros = (None, None)
for layer, values in layers.items():
zeros = values.count(0)
if not least_zeros[0] or zeros < least_zeros[0... |
#!/usr/bin/env python
import io
import os
from setuptools import setup
# Package meta-data.
NAME = "Research"
DESCRIPTION = "My short description for my research project."
URL = "https://github.com/pennpolygons/cv-boilerplate"
EMAIL = "jane@institution.com"
AUTHOR = "Jane Doe"
REQUIRES_PYTHON = ">=3.6.0"
VERSION = "... |
if __name__ == "__main__":
age = int(input("What yous your age? "))
amount = 0;
if age < 3:
amount = 0
elif 3 < age < 12:
amount = 10
elif 12 < age:
amount = 15
print("You have to pay " + str(amount) + " for your movie ticket!") |
class Solution:
def maxRotateFunction(self, A):
"""
:type A: List[int]
:rtype: int
"""
f0 = 0
for i in range(len(A)):
f0 += i*A[i]
my_max = f0
last_result = f0
my_sum = sum(A)
for i in range(len(A)-1, 0, -1):
te... |
my_list = [1,2,3]
my_list = ["STRING", 100, 23.2]
len(my_list) # 3
my_list = ['one', 'two', 'three']
my_list[0] # 'one'
my_list[1:] # ['two', 'three']
another_list = ['four', 'five']
my_list + another_list # ['one', 'two', 'three', 'four', 'fiver']
new_list = my_list + another_list
new_list[0] = new_list[0].upper()
... |
pmenor = 0
pmaior = 0
for c in range(1, 6):
peso = float(input('Digite o {}º peso: '.format(c)))
if c == 1:
pmenor = peso
pmaior = peso
else:
if peso > pmaior:
pmaior = peso
if peso < pmenor:
pmenor = peso
print('O menor peso é {}kg'.format(pmenor))
p... |
## @package perlin_demo
# Illustrates some functions in the perlin_noise module.
from __future__ import division
from __future__ import with_statement
from PIL import Image
from perlin_noise import *
from gradient import *
from image import *
def demo_2d():
w = h = 512
octaves = 9
persistence = 0.5
print 'Mak... |
import csv
import cv2
import numpy as np
from keras.callbacks import ModelCheckpoint, Callback
import random
import sklearn
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense, Flatten,Cropping2D
from keras.layers import Conv2D
from keras.layers import... |
# Find all words which contain exactly two vowels in any list in the table.
# Import your libraries
import pandas as pd
# Start writing code
df = google_word_lists
df['split1']=df.words1.apply(lambda x: x.split(','))
df['split2']=df.words2.apply(lambda x: x.split(','))
df['both_splits'] = df['split1']+df['split2']
l... |
import zmq
ctx = zmq.Context.instance()
server = ctx.socket(zmq.ROUTER)
server.bind('inproc://foo')
clients = [ctx.socket(zmq.REQ) for i in range(10)]
for i, client in enumerate(clients):
client.connect('inproc://foo')
client.send_string('FOO%d' % i)
messages = []
while server.poll(0):
messages.append(ser... |
import sys
from backslant import PymlFinder, BackslantFinder
def print_render(func, *a, **kw):
index = 0
for chunk in func(title='The Incredible'):
if chunk.startswith('</'):
index = index - 1
print(' ' * index, chunk)
if chunk.startswith('<') and not chunk.startswith('<... |
#!/usr/bin/env python3
# Kebechet
# Copyright(C) 2018, 2019 Kevin Postlethwait
#
# This program is free software: you can redistribute it and / or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any late... |
"""
This is just a file I used to test parts of the other projects such as the splitting and replacing of the calculator
equations.
"""
from datetime import datetime
import random
import urllib.request
from random_word import RandomWords
import yaml
import requests
def retNumbers(equat, ope, op):
num = []
n... |
def solution(skill, skill_trees):
answer = 0
for item in skill_trees:
flag = 0
ski = list(skill)
for i in item:
if i in ski:
if i == ski[0]:
ski.pop(0)
else:
flag = 1
break
if ... |
#!qerqera
#1sfg
print("asd&")
|
from netmiko import ConnectHandler
from datetime import datetime, date
import ast
device_list=[]
with open('source.txt', 'r') as inFile:
device_list=ast.literal_eval(inFile.read())
def add_vlan(dev):
vlan_num = input("Give me the vlan number you want to add: ")
command_1 = 'vlan ' + vlan_num
... |
#!/usr/bin/env python3
import pandas as pd
def growing_municipalities(df):
0.0
def main():
return
if __name__ == "__main__":
main()
|
n1=int(input("enter 1st number :"))
n2=int(input("enter 2nd number :"))
n3=int(input("enter 3rd number :"))
if n1>n2 and n1>n3:
print("big number is :",n1)
elif n2>n3:
print("big number is :",n2)
else:
print("big number is :",n3)
|
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
num = sum = 0
sign = 1
stack = []
for i in s:
if i == ' ':
continue
elif i == '+':
sum += sign*num
... |
from demos.setup import np, plt, demo
from compecon import BasisChebyshev, NLP
from compecon.tools import nodeunif
__author__ = 'Randall'
# DEMAPP08 Compute function inverse via collocation
# Residual function
def resid(c, F, x):
F.c = c
f = F(x)
return f ** -2 + f ** -5 - 2 * x
# Approximation struct... |
from conftest import app_client, STANDARD_USER, ADMIN_USER, db
from utils import create_user, get_admin_user, get_standard_user
from reporter_app.models import Role, User
import pytest
from flask_security import current_user
from sqlalchemy.exc import IntegrityError, SQLAlchemyError
@pytest.mark.parametrize("user_par... |
from django.contrib import admin
from .models import JobCre
# Register your models here.
admin.site.register(JobCre) |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
"""
1->2->2->1
输出: t... |
def main():
file = input("file:\n")
bits = text_to_bits(file)
len_t = int(len(bits) / 8)
while(len(bits) % 6 != 0):
bits += '0'
sharp = 0
n = 6
bits6 = [bits[i:i + n] for i in range(0, len(bits), n)]
while ((len_t + sharp) % 3 != 0):
sharp+=1
bits6 = [two_to_ten(elem) for elem in bits6]
name = f'base64_{... |
# price a call option on the average price of two shares
# plot result as a function of the correlation coefficient
import numpy as np
from numpy import random as rn
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
S10 = 15;
S20 = 30;
r = 0.05;
sigma1 = 0.1 ;
sigma2 = 0.08;
rho = np.linspace(-1... |
#!/usr/bin/env python
#-*- encode:utf-8 -*-
import sqlite3
db_name = None
db = None
cursor = None
def connect():
global db, cursor
db = sqlite3.connect("testing.db")
cursor = db.cursor()
def init_table():
global cursor
query = (
'CREATE TABLE IF NOT EXISTS "{}" ('
'id INTEGER... |
# File_name: stop_emr.py
# Purpose: Stop emr cluster that are running
# Problem:
# Author: Søren Wandrup-Bendixen
# Email: soren.wandrup-Bendixen@cybercom.com
# Created: 2019-07-01
# Called from lambda_function.py
import boto3
def stop_clusters(instance_type,region_name_,RunningInstances) :
client = boto3.client(... |
class Node(object):
def __init__(self, item):
self.item = item
self.lchild = None
self.rchild = None
class Tree(object):
def __init__(self):
self.root = None
def add(self, item):
node = Node(item)
if self.root is None:
self.root = node
e... |
import argparse
import random
import torch
import torch.backends.cudnn as cudnn
from data import create_dataset
parser = argparse.ArgumentParser()
parser.add_argument('--mode', default='train', help='train or test')
parser.add_argument('--split', default=8855, type=int, help='the number of images splitted to training ... |
from flask import Flask, render_template, url_for
from flask.json import jsonify
import os.path, urllib, urllib2, json
app = Flask(__name__)
KEYS = open('./keys').readlines()
@app.route('/')
def index():
return render_template('index.html')
@app.route('/explore')
@app.route('/explore/')
def explore():
data =... |
from quickbats.qbo import QBO
qbo = QBO()
qbo.connect()
def test_get_item_by_name():
item = qbo.get_item_by_name("Design")
assert item.Name == "Design"
assert "Item:Design" in qbo._cache
|
from bcrypt import hashpw, gensalt
import MySQLdb
class PassPhrase:
def __init__(self, uname, PwdAttempt):
self.uname = uname
self.HashPhrase = ()
self.PwdAttempt = PwdAttempt
self.uaccess = int()
self.accessdb()
def accessdb(self):
try:
db = MySQLd... |
class Solution:
def toLowerCase(self, str: str) -> str:
return str.lower()
# not unsing the builtin method:
# A = string.ascii_uppercase
# a = string.ascii_lowercase
# for i,ch in enumerate(str):
# if ch in A:
# str = str.replace(ch, a[A.index(ch)... |
from db import db
class Videos(db.Model):
id = db.Column('id', db.Integer(), primary_key = True)
name = db.Column('name', db.String(100))
path = db.Column('path', db.String(100))
def __init__(self, name, path):
self.name = name
self.path = path
|
from flask import Flask, render_template, request
from datetime import datetime
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html',time=datetime.now())
@app.route('/name', methods=["GET","POST"])
@app.route('/name/<name>')
def name():
return render_template('name.html',args=... |
#-*- coding:utf8 -*-
import json
import time
import datetime
from celery.task import task
from django.db.models import Q
from shopback import paramconfig as pcfg
from shopback.trades.models import MergeTrade,MergeBuyerTrade
from shopback.orders.models import Order,Trade
from shopapp.memorule.models import RuleMemo,Trad... |
# 延时计算
class LazyProperty:
def __init__(self,func):
print("======>",func)
self.func = func
def __get__(self, instance, owner):
print('get',instance,owner)
# instance 类 owner:实例 对象
if instance is None:
return self
res = self.func(instance)
#... |
# -*- coding: utf-8 -*-
# @Author : 赵永健
# @Time : 2019/12/26 15:04
|
import progressbar
import seaborn as sb
from tempfile import NamedTemporaryFile, TemporaryFile, TemporaryDirectory
from functools import reduce
import multiprocessing as mproc
import numpy as np
import matplotlib as mpl
import pdb
import pickle
import subprocess
import os
import pyximport; pyximport.install(
setup_... |
import os
import utils
import nltk
from gensim.models import Word2Vec
from gensim.test.utils import get_tmpfile
from loguru import logger
class WordToVec():
def __init__(self, dataset_name) -> None:
input_file_path = 'input/' + dataset_name + '/raw.txt'
if not os.path.isfile(input_file_path):
... |
from ..base import *
from ..button import *
from ..toolbar import *
from .history_dialog import HistoryDialog
class HistoryToolbar(Toolbar):
def __init__(self, parent):
Toolbar.__init__(self, parent, "history", "History")
self._btns = {}
btn_data = {
"undo": ("icon_undo", "... |
#!/usr/bin/env python
import ROOT
import os
import argparse
from RootTools.core.Sample import Sample
argParser = argparse.ArgumentParser(description = "Argument parser")
argParser.add_argument('--logLevel', action='store', default='INFO', nargs='?', choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'D... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import subprocess
def authenticate(fn):
def wrapper(*args, **kwargs):
euid = os.geteuid()
if euid != 0:
print 'This command requires privliged mode. Enter password..'
os.execvp('sudo', ['sudo', 'python'] + sys.argv)
... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from cleaner_data import *
from sklearn.ensemble import RandomForestClassifier as RFC
from sklearn.metrics import classification_report
from football_func import *
from pprint import pprint
import pickle
plt.style.use('fivethirtyeight')
def add_en... |
"""
For example, the following two linked lists:
A: a1 > a2
c1 > c2 > c3
B: b1 > b2 > b3
begin to intersect at node c1.
"""
import sys
sys.path.append('../')
from leetCodeUtil import ListNode
class Solution(object):
def getIntersectionNode(self, headA, headB):
"""
... |
"""
@author:ming
@file:猪八戒网抓取saas数据.py
@time:2021/10/26
"""
import requests
from lxml import etree
import csv
"""
在搜索栏搜索saas抓取搜索结果
"""
kw = "saas"
url = f"https://nanchong.zbj.com/search/f/?kw={kw}"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/9... |
click("1372269002074.png")
wait(2)
type("www.facebook.com" + Key.ENTER)
wait(2)
click("1372269666798.png")
click("1372269175860.png")
click("1372269967072.png")
type("Aneta Naydenova")
click("1372269986842.png")
type("automotive test message, baby. Ignore it." + Key.ENTER)
type("Angel Elenkov")
click("1372269986842.png... |
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 1 20:04:50 2019
@author: Neha
"""
import random
import math
import encode
import sys
import copy
"""
def transProb(corpus):
tranProbTable = [[0 for i in range(27)] for j in range(27)]
space = ' '
temp = ' '
for ch in corpus:
if ch == space:
... |
import logging
import re
from xml.dom import minidom
from androguard.core.bytecodes.apk import AXMLPrinter
logger = logging.getLogger(__name__)
# populate fields with field id and name pairs
# populate field_refs with field id and field reference pairs
def get_fields(rids):
fields = {}
field_refs = {}
f... |
# program sprzedawca samochodów
# oblicza za jaką kwotę sprzedać samochód
print(
"""
Program do obliczenia ceny sprzedaży auta
Program umożliwia wpisanie podstawowych danych na temat samochodu, podatków itp. w celu ustalenia
optymalnej ceny sprzedaży.
Poniżej wpisz określone z dokładnością ... |
def get_animals(database, species):
return None
from datetime import datetime
from unittest.mock import Mock
mock = Mock(spec=get_animals)
expected = [
('A', datetime(2018, 5, 3, 11, 5)),
('B', datetime(2010, 6, 5, 12, 1)),
('C', datetime(2019, 3, 4, 10, 2))
]
mock.return_value = expected
database = object()... |
from itertools import chain, repeat
import torch
import torch.nn.functional as F
from img2pose.utils.pose_operations import plot_3d_landmark_torch, pose_full_image_to_bbox
def fastrcnn_loss(
class_logits,
class_labels,
box_regression,
labels,
dof_regression_targets,
box_regression_targets,
... |
numero_x = int(input('Digite um número inteiro: '))
numero_y = int(input('Digite outro número inteiro: '))
numero_z = int(input('Digite mais um número inteiro: '))
# Verificando qual foi o menor valor digitado
menor = numero_x
if numero_y < numero_x and numero_y < numero_z:
menor = numero_y
if numero_z < numero_x and... |
#coding:utf-8
__author__ = 'love_huan'
a = []
n = int(raw_input('请输入总共有多少数据'))
for i in range(0,n):
print("请输入第%s个数据" % (i+1) )
t = int(raw_input())
a.append(t)
for i in range(0,n-1):
for j in range(0,n-1):
if a[j] < a[j+1]:
t=a[j]
a[j] = a[j+1]
a[j+1]=t
for... |
from setuptools import setup
setup(
name='agentes_actuadores',
version='1.0.0',
description='Modulos que interfacean actuando sobre el ambiente',
author='VOV',
packages=['agentes_actuadores'],
install_requires=['entidades', 'servicios_aplicacion'],
)
|
som = 0
cont = 0
for c in range(1, 7):
n = int(input('Insira 6 números inteiros:'))
if n %2 == 0:
som += n
cont += 1
print('Considerando somente os {} números pares inseridos a soma é: {}'.format(cont, som)) |
import numpy as np
from sklearn.multiclass import OneVsRestClassifier
from sklearn.metrics import f1_score
from sklearn.preprocessing import MultiLabelBinarizer
from time import time
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
from sklearn.svm import LinearSVC
from sklearn.metrics i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.