text stringlengths 38 1.54M |
|---|
'''
方法一:字典
'''
'''
方法二:bit
'''
def isDup(strs):
lens=len(strs)
flage=[0,0,0,0,0,0,0,0]
i=0
while i<lens:
index=int(ord(list(strs)[i])/32)
shift=ord(list(strs)[i])%32
if (flage[index]&(1<<shift))!=0:
return True
flage[index]|=(1<<shift)
i+=1
return... |
class EyeSample:
def __init__(self, orig_img, img, is_left, transform_inv, estimated_radius):
self._orig_img = orig_img.copy()
self._img = img.copy()
self._is_left = is_left
self._transform_inv = transform_inv
self._estimated_radius = estimated_radius
@property
def o... |
# get modules
import numpy as np
import random
import sys
sys.setrecursionlimit(15000)
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from matplotlib.patches import Circle, PathPatch
from matplotlib.path import Path
import seaborn as sns
import gif
np.random.seed(42)
# sns.set(style='dark')
sns.set(s... |
import datetime
import requests
from fides.config import Config
DEFAULT_PROPERTIES_FILE_NAME = 'fides.ini'
ENV_FIDES_PROPERTIES_FILE = 'FIDES_PROPERTIES_FILE'
PROP_FIDES_SERVER_URL_NAME = 'FIDES_SERVER_URL'
PROP_FIDES_SERVER_URL_VAL = 'localhost'
PATH_AGENT_CONNECT = 'api/agent/connect'
PATH_AGENT_PING = 'api/agent/p... |
my_list = ["в", "5", "часов", "17", "минут", "температура", "воздуха", "была", "+5", "градусов"]
my_list2 = []
"""my_list.pop(1)
my_list.pop(-2),
my_list.insert(-1, "+05")
my_list.insert(1, "05")
my_list2 = my_list.copy()
my_list2.pop(0)
my_list2.insert(0, "05")
my_list2.pop(1)
my_list2.insert(1, "+05")
... |
# 删除小于指定大小的对象。
#
# 期望ar是带有标签对象的数组,并删除小于min_size的对象。 如果ar是bool,则首先标记图像。 这会导致布尔数组和0和1数组的行为可能不同。 |
import arcpy, os, random, xlrd, time
from arcpy import env
from arcpy.sa import *
start_time = time.time()
##################################################
##################################################
## Parameters or variables that need to be changed
## before running the script ###########
# Florid... |
# coding: utf-8
# compare the USNO and SDSS v-band data provided by 3LAC
# and the SDSS i-band data (SDSS_missing) provided by NED with each other.
# In[0]: read and parse data; 999 sources with known redshift
from __future__ import division
import csv
import numpy as np
import quasars as quas
from quasars import Qua... |
# This example script demonstrates how use Python to allow users to send SDK to Tello commands with their keyboard
# This script is part of our course on Tello drone programming
# https://learn.droneblocks.io/p/tello-drone-programming-with-python/
# Import the necessary modules
import socket
import threading
import se... |
from torchvision import transforms
from torch.utils.data import Dataset
import torch
import os
from PIL import Image
from math import log2
class Scalable_Dataset(Dataset):
def __init__(self, root, datamode = "train", transform = transforms.ToTensor(), latent_size=512):
super().__init__()
if datam... |
# Third-party imports
import pytest
from mxnet import nd
# First-party imports
from gluonts.block.encoder import HierarchicalCausalConv1DEncoder
nd_None = nd.array([])
@pytest.mark.skip()
def test_hierarchical_cnn_encoders() -> None:
num_ts = 2
ts_len = 10
test_data = nd.arange(num_ts * ts_len).reshape(... |
# nodenet/layers/nodes.py
# Description:
# "nodes.py" provide node layers.
# Copyright 2018 NOOXY. All Rights Reserved.
from nodenet.imports.commons import *
from .base import *
import nodenet.functions as func
import numpy
# Vector Nodes input: 2D vector, output: 2D vector
class Nodes1D(Layer):
def __init__(self... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('books', '0003_auto_20151118_2314'),
]
operations = [
migrations.RenameField(
model_... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
#step 1 load the data
dataframe = pd.read_csv('data.csv')
dataframe = dataframe.drop(['index' , 'price', 'sq_price' ], axis = 1) #drop the index column
dataframe = dataframe[0:10] # to read dataframe of rows from 0 ... |
# https://www.hardmob.com.br/forums/407-Promocoes?pp=30&sort=dateline&order=desc&daysprune=-1
import re
import requests
from win10toast import ToastNotifier
import time
import pickle
import os
import glob
from twilio.rest import Client
hardmob_filename = "https://www.hardmob.com.br/forums/407-Promocoes?pp=50&sort=dat... |
import sqlite3
class Database:
def __init__(self, db):
self.connect = sqlite3.connect(db)
self.cursor = self.connect.cursor()
self.cursor.execute("CREATE TABLE IF NOT EXISTS books (id INTEGER PRIMARY KEY, title TEXT, author TEXT, year INTEGER, isbn INTEGER)")
self.commit()
def... |
"""
Faça um programa que leia o preço de 10 produtos.
Ao final escreva o somatório dos preços.
"""
soma= 0.0
for cont in range (10):
preco = float(input('Digite o preço: '))
soma += preco
print('O valor total será {:.2f}' .format(soma))
|
def load_django_models():
try:
from django.db.models.loading import get_models
for m in get_models():
ip.ex("from %s import %s" % (m.__module__, m.__name__))
except ImportError:
print "Could not find Django. Sadface. D:"
def main():
load_django_models()
|
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
import pandas as pd
import math
import os
from matplotlib.font_manager import FontManager, FontProperties
plt.rcParams['figure.dpi'] = 300 #分辨率
with np.errstate(divide='ignore'):
np.float64(1.0) / 0.0
def getChineseFont():
... |
# Generated by Django 2.2.6 on 2019-11-11 20:33
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('find', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='query',
old_name='fasta',
new_name=... |
import torch
from nets import BaseEncoder
if __name__ == '__main__':
base_encoder = BaseEncoder()
print(base_encoder.backbone)
print(base_encoder.projection_head)
rand_input = torch.zeros((1, 3, 224, 224)).random_()
embeddings = base_encoder(rand_input) |
# -*- coding: utf-8 -*-
'''
Apache mod_isapi模块悬挂指针漏洞
author: lidq
created: 20170119
'''
# 导入url请求公用库
from engine.engine_utils.InjectUrlLib import returnInjectResult
from engine.engine_utils.common import *
from engine.engine_utils.yd_http import request
# 导入日志处理句柄
from engine.logger import scanLogger as logger
# 导入默... |
# Copyright 2019 Quantapix Authors. 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 l... |
# coding=utf-8
from django.http.response import HttpResponse
from django.utils import simplejson
from django.views.decorators.cache import cache_page
from django.views.decorators.csrf import csrf_exempt
from utilities import *
from health.models import *
from health.services.stats.services import HealthActivityDistrib... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 26 18:36:06 2018
@author: is2js
"""
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
#랜덤 시드 고정
np.random.seed(7)
# 넘파이의 loadtxt로 csv파일을 불러올 수 있다.
# 대신 구분자(delimiter)를 ","로 지정
dataset = np.loadtxt('./data/pima-indians-diabetes.csv',... |
from app.Controllers.DumpController import index, find, store, update, delete
from app.Services.DumpService import DumpService
service = DumpService()
def route_index(event, context):
return index(service, event)
def route_find(event, context):
return find(service, event)
def route_insert(event, context):
... |
def bubblesort(alist):
isSorted = False
count = 0
while(not isSorted):
isSorted=True
arrlen = len(alist) -1
for i in xrange(arrlen):
if alist[i] > alist[i+1]:
temp = alist[i]
alist[i] = alist[i+1]
alist[i+1] = temp
... |
def part1(pw):
pw = list(str(pw))
if pw != sorted(pw) or len(set(pw)) == len(pw):
return False
return True
def part2(pw):
return 2 in [str(pw).count(d) for d in str(pw)]
pws = [pw for pw in range(147981, 691423 + 1) if part1(pw)]
print(f"PART 1: {len(pws)}")
pws_2 = [pw for pw in pws if par... |
#Challenge: Write a Python function print_digits that takes an integer number
#in the range [0,100), i.e., at least 0, but less than 100. It prints the
#message "The tens digit is %, and the ones digit is %.", where the percent
#signs should be replaced with the appropriate values. (Hint: Use the
#arithmetic operators ... |
import sys
from collections import defaultdict
x = []
class Graph:
# Constructor
def __init__(self):
# default dictionary to store graph
self.graph = defaultdict(list)
# function to add an edge to graph
def addEdge(self, u, v):
self.graph[u].append(v)
# Functi... |
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
# Creates the screen
screen = Screen()
# Sets the screen size
screen.setup(width=600, height=600)
# Disable screen delays
screen.tracer(0)
# Creates the game components
player = Player(... |
# Copyright (c) 2020 KTH Royal Institute of Technology
#
# 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 appli... |
# Ghiro - Copyright (C) 2013-2016 Ghiro Developers.
# This file is part of Ghiro.
# See the file 'docs/LICENSE.txt' for license terms.
from django.core.management.base import NoArgsCommand
from users.models import Activity
class Command(NoArgsCommand):
"""Purge auditing table."""
help = "Purge auditing tab... |
#!/usr/bin/env python
# ########################################################
# This broadcaster will send the transform between the
# boat_frame --> world
#
# It will subscribe to the gps and imu on the boat
# and update the transform accordingly
# ########################################################
import ros... |
from setuptools import setup
import os.path as p
here = p.abspath(p.dirname(__file__))
with open(p.join(here, 'README.md')) as f:
long_description = f.read()
setup(
name='neuroswarms',
version='1.0.1',
description='NeuroSwarms: A neural swarming controller model',
long_description=long_description... |
import multiprocessing
class NoDaemonProcess(multiprocessing.Process):
def _get_daemon(self):
return False
def _set_daemon(self, value):
pass
daemon = property(_get_daemon, _set_daemon) |
import FWCore.ParameterSet.Config as cms
process = cms.Process("TopTree")
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring('root://cms-xrdr.sdfarm.kr:1094///xrd/store/group/CAT/ST_t-channel_top_4f_inclusiveDecays_13TeV-powhegV2-madspin-pythia8_TuneCUETP8M1/v8-0-6_RunIISummer16MiniAODv2-... |
#!/usr/bin/env python3
# coding:utf-8
# Author:Lee
# 2020/4/26 19:44
"""
题目:
给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标。
你可以假设每种输入只会对应一个答案。但是,数组中同一个元素不能使用两遍。
示例:
给定 nums = [2, 7, 11, 15], target = 9
因为 nums[0] + nums[1] = 2 + 7 = 9
所以返回 [0, 1]
思路:
1. 将nums组合为一个索引序列
2. 通过for循环取出索引和值
3. 用hashmap记录之前出... |
#!/usr/bin/env python
# coding: utf-8
'''
enumerate()循环返回给定列表和其对应的索引值
注意enumerate只能用于循环枚举,不能直接作为函数使用。
'''
list = [4,8,3,5,2,1,6,7,0,9,2]
li = [1,2,3,4]
def main():
for i in enumerate(list):
print i
if __name__ == '__main__':
main() |
import re
import tools
from database import Table, FieldTable, findTypeFromMysql, Entity
baseCommandeAnnotation = ['EntityName', 'FieldName', 'Column', 'GeneratedValue']
startAnnotationFormat = "# ###"
shortComment = "# "
appelFonction = "@ORM/"
callage1 = " "
callage2 = callage1 + callage1
callage3 = callage2 + c... |
import os
DEBUG = True
HOST = '0.0.0.0'
PORT = 5000
# MongoDB connection settings
DATABASE = {
'db': 'neomad',
'username': 'root',
'host': 'localhost',
'password': '',
'port': int(os.environ.get('DB_PORT', 27017))
}
PROJECT_PATH = os.path.abspath(os.path.dirname(__file__))
UPLOAD_PATH = '{}/static/uploads'... |
from fontTools.misc.transform import Identity
from fontTools.pens.hashPointPen import HashPointPen
import pytest
class _TestGlyph(object):
width = 500
def drawPoints(self, pen):
pen.beginPath(identifier="abc")
pen.addPoint((0.0, 0.0), "line", False, "start", identifier="0000")
pen.add... |
from flask import Flask, render_template, url_for, request
import pandas as pd
pd.set_option('display.max_columns', 25)
import numpy as np
import matplotlib.pyplot as plt
from surprise import Dataset
from surprise import Reader
from surprise import SVD
from surprise.prediction_algorithms import knns
from surprise.model... |
n = -1
max = 0
quantity = 0
while n != 0:
n = int(input())
if n > max:
max = n
quantity = 1
elif n == max:
quantity += 1
print(quantity)
|
#!/usr/bin/env python3
# Amir Refai
import readline
from termcolor import colored
def calculate(arg):
stack = []
tokens = arg.split()
for token in tokens:
try:
stack.append(int(token))
except ValueError:
val2 = stack.pop()
val1 = stack.pop()
if token == '+':
result = val1 + val2
elif token... |
import sys
import os
from subprocess import Popen, PIPE
import subprocess
from shlex import split
# 1. install develop library
#vi /etc/udev/rules.d/70-persistent-ipoib.rules
def installLibrary():
print( "##### install dev tools #####")
os.system("sudo yum -y groupinstall \"Development Tools\"")
print( ... |
import tkinter
import tkinter.messagebox as messagebox
# 窗口
root = tkinter.Tk()
'''
x: 相当于是 * ,生活中:500*500 宽度500 高度500
400x300: 窗口的高度为400,高度为300
+400: 窗口距离屏幕最左边400,如果是-400的话,说明窗口距离屏幕最右边400
+300:窗口距离屏幕最上边300,如果是-300的话,说明窗口距离屏幕最下边300
'''
root.geometry("400x300+400+300")
'''
这个是窗口的标题
'''
root.ti... |
import torch.nn as nn
class LayerLinearRegression(nn.Module):
def __init__(self):
super().__init__()
# Instead of our custom parameters, we use a Linear layer with single input and single output
self.linear = nn.Linear(1, 1)
def forward(self, x):
# Now it only ... |
#
# Created by OFShare on 2019-11-15
#
# This script tests speed of frozen pb and tflite model
# Usage:
# 1. run frozen pb:
# python benchmark.py --model models/input.pb --batch_size 1 --height 320 --width 320 1> log.std 2> log.err &
# 2. run tflite:
# python benchmark.py --model models/input.tflite 1> log.... |
# Xatamjonov Ulugbek
# 2021-01-07 / 14:26
# Dasturlash asoslari
# 6-dars Sonlar
# Amaliyot
#1
# Foydalanuvchi kiritgan istalgan sonnni kubi va kvadratini konsulga chiqaruvchi dastur tuzing:
# 1-usul
i_son=int(input( "Istalgan sonni kiriting. Biz uni Kvadratga va kubga ko'taramiz: "))
kv=(i_son**2)
kb=(i_son**3)
prin... |
#!/usr/bin/env python
from operator import add
from util import primes
if __name__ == "__main__":
target = 2000000
primes_lt_target = primes.filter_lt(target)
print reduce(add, primes_lt_target)
|
##################################################
# file: OIMStoreService_types.py
#
# schema types generated by "ZSI.generate.wsdl2python.WriteServiceModule"
# D:\workspace\digsby\Digsby.py --no-traceback-dialog --multi --server=api5.digsby.org
#
##################################################
import ZSI
impor... |
#CS 4400 Phase III Source Code
#Members - Mario Wijaya, Masud Parvez, Ousmane Kaba, Wenlu Fu
#Demo date/time: Tuesday 4/26/2016 2:15pm - 3:00pm
#Team #23
#We worked on this project only using stackoverflow.com and this semester's course materials.
from tkinter import *
import random
import csv
import re
import urllib.... |
from abc import ABC, abstractmethod
from torch.utils.data import Dataset
import torch.nn.functional as F
from sklearn.preprocessing import LabelEncoder
import pandas
import torch
from torch import nn
import somajo
import numpy as np
from utils import BertExtractor, StaticEmbeddingExtractor
def create_label_encoder(al... |
# -*- coding: utf-8 -*-
# __version__ = '0.1'
import argparse
import time
import os
import logging
import configparser
from datetime import datetime
import CloudFlare
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
import src.general as gen
import src.tenable as tnb
import src.gc... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-01-19 16:46
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='proyec... |
from flask import redirect, render_template, request, url_for, session, abort
from app.models.configuracion import Configuracion
from app.helpers.auth import authenticated, tiene_permiso
def update():
"""Actualiza configuracion de sitio"""
if not authenticated(session) or not tiene_permiso(session, "configur... |
# coding: utf-8
from . import utils
def backup(archive):
utils.archive_dirs(archive, "/etc/fuel", "version")
def restore(archive):
utils.extract_tag_to(archive, "version", "/etc/fuel/")
|
from django.db import models
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from Lunchbreak.mixins import CleanModelMixin
from ..managers import StaffManager
from ..mixins import NotifyModelMixin
from .abstract_password import AbstractPassword
class Staff(... |
"""Investing in Stock
Good work! As a store manager, you’re also in charge of keeping track of your stock/inventory."""
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
|
import numpy as np
import sys
def partition_labels(filepath, range_from, range_to, gap):
for p in np.arange(range_from, range_to, gap):
outFilePath = '{}.labels.{}'.format(filepath, p)
with open(filepath, 'r') as in_handler, open(outFilePath+'.train', 'w') as out_handler\
, open(outFilePath+'.test', 'w') as... |
import os
import time
with open('starwars.txt', 'r') as sw_file:
lines = sw_file.readlines()
_index = 0
for line in lines:
if _index == 0:
time_duration = int(line.strip())
_index += 1
continue
if _index < 13:
print(line, end='')
... |
import pp
def test_label_fiber_single():
"""Test that add_fiber single adds the correct label for measurements."""
c = pp.c.waveguide()
assert len(c.labels) == 0
c = pp.routing.add_fiber_single(c, with_align_ports=False)
assert len(c.labels) == 2
l0 = c.labels[0].text
l1 = c.labels[1].tex... |
import ROOT
import collections
### variable list
variables = {
"pth":{"name":"higgs_pt","title":"p_{T}^{H} [GeV]","bin":50,"xmin":0,"xmax":1000},
"pthl":{"name":"higgs_pt","title":"p_{T}^{H} [GeV]","bin":50,"xmin":0,"xmax":5000},
"mh":{"name":"higgs_m","title":"m_{H} [GeV]","bin":100,"xmin":50,"xmax":180},... |
# Short Palindrome
#######################################################################################################################
#
# Consider a string s, of n lowercase English letters where each character, si (0 <= i < n), denotes the letter at
# index i in s. We define an (a,b,c,d) palindromic tuple of... |
task1 = {"todo": "call John for AmI project organization", "urgent": True}
task2 = {"todo": "buy a new mouse", "urgent": True}
task3 = {"todo": "find a present for Angelina’s birthday", "urgent": False}
task4 = {"todo": "organize mega party (last week of April)", "urgent": False}
task5 = {"todo": "book summer holidays"... |
import sys
"""
이차원 배열에서 각 행의 최솟값들 중 최댓값을 찾는 문제
test cases
3 3
3 1 2
4 1 4
2 2 2
"""
n, m = map(int, sys.stdin.readline().split())
data = iter(map(int, sys.stdin.readline().split()) for _ in range(n))
print(max(map(min, data)))
"""
map(func, iterator)-> iterator의 값들을 func에 적용한 iterator을 return , max -> iterat... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 18 03:37:40 2019
@author: kunal
"""
import numpy as np
x = np.random.normal(150, 20, 1000)
print("Mean value is: ", np.mean(x))
print("Median value is: ", np.median(x))
print("Standard Deviation is: ", np.std(x))
from scipy import stats
pri... |
from funcs import *
import os
from matplotlib import pyplot as plt
##############################
# 0. parameter setting
f_fwd, f_bwd = 24, 24
nan_len = 5
##############################
# 1. load dataset
df = pd.read_csv('D:/202010_energies/201125_result_aodsc+owa.csv', index_col=0)
idx_detected_nor = np.where(df[... |
import q20
if __name__ == '__main__':
str = q20.picktxt("../../../data/jawiki-country.json", "イギリス")
for line in str.split("\n"):
if "Category" in line:
print(line)
|
'''
Module that handles creation of SKFiles that represent songs, having all relevant info from then.
@date: 9/25/18
@author: Cody West
'''
class SKFile(object):
'''
Class that contains metadata and index number of song
'''
def __init__(self, path, index, title, artist, album, time):
... |
def ft_len(z):
x = 0
for i in z:
x = x + 1
return x
def ft_rev_list(num):
for i in range(0, ft_len(num) // 2):
temp = num[i]
num[i] = num[-(i + 1)]
num[-(i + 1)] = temp
return num
|
#!/usr/bin/env python3
from aws_cdk import (
aws_ec2,
aws_ecs,
aws_iam,
aws_ssm,
aws_autoscaling,
core
)
from os import getenv
class ImportedResources(core.Construct):
def __init__(self, scope: core.Construct, id: str, **kwargs):
super().__init__(scope, id, **kwargs)
env... |
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.ensemble import RandomForestClassifier
from imblearn.over_sampling import SMOTE
from joblib import dump
from functions import load_data, prepare_and_clean_data, process_data
np.random.seed(500) #used to repro... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class Empresa(models.Model):
name = models.CharField(max_length=255)
def __str__(self):
return f"{self.name}"
class Departamento(models.Model)... |
# -*- coding: utf-8 -*-
from nbs.models import db
from nbs.models.entity import Entity
class Place(Entity):
__tablename__ = 'place'
place_id = db.Column(db.Integer, db.ForeignKey('entity.id'),
primary_key=True)
name = Entity._name_1
responsible_id = db.Column(db.Integer, db.... |
from __future__ import print_function
from pygarl.classifiers import SVMClassifier, MLPClassifier
import sys
def train_classifier(classifier, dataset_dir, output_file, n_jobs=1, **kwargs):
"""
Train a model using the passed classifier from the given dataset and save it to a file.
:param classifier: C... |
def escreva(texto):
tamanho = len(texto) + 4
print('~' * tamanho)
print(f' {texto}')
print('~' * tamanho)
# Main Program
escreva(str(input('Digite algo:')))
|
from time import sleep
import library_mqtt as mqtt
import tkinter
from tkinter import ttk
class MyDelegate(object):
def print_message(self, message):
print("Message received:", message)
def loop1():
#sleep(10)
root = tkinter.Tk()
root.title("Thể thao")
main_frame = ttk.Frame... |
# Simulated Annealing
"""
Created on Fri Aug 9 19:16:09 2019
@author: Salam Saudagar
"""
import numpy as np
#import pandas as pd
import matplotlib.pyplot as plt
def Rosenbrock(x,y, a=1, b=100):
return( (a-x)**2 + b*(y - x**2 )**2 )
x_initial , y_initial = np.random.uniform(-5, 5, size = 2)
EN_in... |
from cloudshell.cli.command_template.command_template import CommandTemplate
from cloudshell.networking.juniper.command_templates.generic_action_error_map import (
ACTION_MAP,
ERROR_MAP,
)
CREATE_VIEW = CommandTemplate(
"set snmp view SNMPSHELLVIEW oid .1 include",
action_map=ACTION_MAP,
error_map... |
from .lib.air_quality_pb2 import DataPoint
class Default:
channel = "/AirQuality"
rpcURL = "127.0.0.1:5555"
class Type:
PM2_5 = DataPoint.PM2_5
PM10 = DataPoint.PM10
NO = DataPoint.NO
NO2 = DataPoint.NO2
NOX = DataPoint.NOX
NH3 = DataPoint.NH3
SO2 =... |
# -*- coding: utf-8 -*-
# @Time : 2018/7/3 14:09
# @Author : LI Jiawei
# @Email : jliea@connect.ust.hk
# @File : main.py
# @Software: PyCharm
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import logging
from argparse import ArgumentParser
from datetime import ... |
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
start = None
end = None
max_value = None
min_value = None
for i in range(len(nums)):
if i > 0 and start == None and num... |
message_start = '''
{}, это бот для учета твоих затрат
для начала введи название валюты в которой ты будешь ввести учет
'''
message_set_valute = '''
{}, вы ввели валюту {}
теперь в ней будут вестись все ваши финансы
'''
message_unknown_command = '''
{}, я не понял что делать ?!
'''
message_category = '''
{}, вы п... |
import sqlite3
import argparse
import sys
import hashlib
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Copy tables from existing SQLite3 databases into a new one. Accepting '<database_filename> <table_name>' pairs as line-seperated from stdin")
parser.add_argument("-o", "--output", r... |
from .sym import S, E
class TreeWalk:
def __init__(self, rules):
self.rules = rules
def __call__(self, expr, data=None):
for is_match, replace in self.rules:
if not is_match(expr):
continue
return replace(expr, self, data)
return expr
class ... |
from firebase import firebase
import json
import numpy as np
data = json.load(open("data.json"))['data']
cols = []
lbls = []
labelsValues = [
"red-ish",
"green-ish",
"blue-ish",
"orange-ish",
"yellow-ish",
"pink-ish",
"purple-ish",
"brown-ish",
"grey-ish"
]
for submission in data:
... |
import math
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# LSTM for sequence classification in the fall dataset
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
from keras.preprocessing import sequence
from skle... |
import RPi.GPIO as GPIO
from mfrc522 import MFRC522
from threading import Thread
from time import sleep, monotonic, time
class DeviceMFRC522:
READER = None
KEY = [0xFF,0xFF,0xFF,0xFF,0xFF,0xFF]
BLOCK_ADDRS = [8, 9, 10]
def __init__(self, id):
self.READER = MFRC522(device=id)
def read(self):
... |
#!/usr/bin/env python
# coding=utf-8
import time
import urllib
import requests
def thinkphp_checkcode_time_sqli_verify(url):
pocdict = {
"vulnname":"thinkphp_checkcode_time_sqli",
"isvul": False,
"vulnurl":"",
"payload":"",
"proof":"",
"response":"",
"excepti... |
from turtle import *
shape ("turtle")
speed(-1)
pensize(4)
color('DarkOliveGreen2')
goc_nhon = 55 #int(input("Dien goc nhon cua hinh thoi vao day: "))
goc_tu = 180 - goc_nhon
goc_quay = (180-2*goc_nhon)/2
left(goc_nhon/2)
for i in range(4):
forward(100)
right(goc_nhon)
forward(100)
righ... |
"""
Given an array of integers, find the first missing positive integer in linear
time and constant space. In other words, find the lowest positive integer that
does not exist in the array. The array can contain duplicates and negative
numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, ... |
from typing import List
class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
m = len(board)
n = len(board[0])
visit = [[False] * n for _ in range(m)]
def dfs(board,y,x):
d... |
import streamlit as st
import pickle
import joblib
import bz2
import _pickle as cPickle
from sklearn.ensemble import RandomForestClassifier
import pandas as pd
# Instantiate the model
X_train_df = pickle.load(open('X_train_df.pkl', 'rb'))
y_train_df = pickle.load(open('y_train_df.pkl', 'rb'))
rf_clf = pickl... |
# ROBOT CAR PROJECT
# WRITEN BY: Lucas Everts
# WRITEN FOR: WMU Raspberry Pi Clubs Fall 2015 Sumo Robot Compitition
# LAST EDITED: August 21, 2015
# DESCRIPTION:
# The following Python code was writen for a sumo compition robot. The robot is powered by a Raspberry Pi B+, two L298N H-Bridges,
# and four 18650 ... |
def box2frame(box, apoint=[0.5, 0.5]):
'''
Convert [y1, x1, y2, x2] to [x, y, w, h]
'''
return [
(box[1] + apoint[1]*(box[3]-box[1])),
(box[0] + apoint[0]*(box[2]-box[0])),
(box[3] - box[1]),
(box[2] - box[0])
] |
# File to run GUI menu before live plotting and provide a front end to the user
# Author: Daniel Williams
# Date Created: 9/15/2021 9:26PM
import os
import matplotlib.pyplot as plt
import PySimpleGUI as sg
import plot_loc as pl
def run_gui():
"""Creates a simple gui prior to plotting to allow user to select fi... |
import math
from rpi_ws281x import PixelStrip, Color
import sys
import time
from config import *
LED_COUNT = get_led_count()
LED_PIN = 18 # GPIO pin connected to the pixels (18 uses PWM!).
LED_FREQ_HZ = 800000 # LED signal frequency in hertz (usually 800khz)
LED_DMA = 10 # DMA channel to use for generating signal ... |
# coding:utf-8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import pyttsx
import re
import urllib2
import random
data_sel = []
data_raw = []
def mixurl(input):
return 'http://fanyi.youdao.com/translate?&i=' + input + '&doctype=xml&version'
def trans(input):
request = urllib2.urlopen(mixurl(input... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.