text stringlengths 38 1.54M |
|---|
'''
Created on July 18, 2016
@author: jalalvand
this code computes the zscored feature matrix.
egs:
zscored = compute_zscore( input_matrix )
'''
import argparse
import math
import sys
import numpy as np
def main(in_mat):
out_mat = np.zeros(in_mat.shape)
means = np.mean (in_mat, axis=0)
stds = np.std (i... |
#!/usr/bin/python
import storm, os, sys, time, json, zlib
class PyBolt(storm.BasicBolt):
def initialize(self, stormconf, context):
self.modules = {}
# Import/Reload each module
def define_rule(self, fn):
module = fn.split('.')[0]
if module not in self.modules: self.modules[module] = __import__(modu... |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pandas.compat import lmap
import exercise.ex01.stock_data as sd
def get_autocrrelation_dataframe(series):
def r(h):
return ((data[:n-h] - mean) * (data[h:] - mean)).sum() / float(n) / c0
n = len(series)
data = np.asarray... |
from __future__ import print_function
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim import lr_scheduler
from torchvision import transforms
import pickle
import os
import os.path
import datetime
import numpy as np
from data.rotationloader... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 22 12:48:30 2020
@author: Paul
"""
import serial
import time
import csv
import os
import subprocess
import re
import paho.mqtt.client as mqtt
import sys
import logging
import argparse
import getpass
import random
import platform
# Configure logging
logging.basicConfig(f... |
import pickle
import glob
import json
import torch
import torch.nn.functional as F
from pathlib import Path
import numpy as np
import pandas as pd
from tqdm import tqdm
from pycocotools import mask
from eval import iou_seg
from eval_constants import LOCALIZATION_TASKS
from argparse import ArgumentParser
def pkl_to... |
"""
Written by Ari Bornstein
"""
import mlpn
import random
import utils
import pickle
def accuracy_on_dataset(dataset, params):
# in case of no data set, like xor
if not dataset:
return 0
good = bad = 0.0
for label, features in dataset:
y_prediction = mlpn.predict(features, params)
... |
class SoftwareVersion(tuple):
def __new__(cls, major: int, minor: int, patch: int) -> PygameVersion: ...
def __repr__(self) -> str: ...
def __str__(self) -> str: ...
major: int
minor: int
patch: int
class PygameVersion(SoftwareVersion): ...
class SDLVersion(SoftwareVersion): ...
SDL... |
{u'account_info': [{u'email': u'magnolio-aws+alpha-syseng-eu-central-1-adam@amazon.com',
u'id': u'603395325992',
u'type': u'fleet'},
{u'email': u'magnolio-aws+alpha-syseng-eu-central-1@amazon.com',
u'id': u'327732690974',
u'type': u'hyperfleet'},
{u'email': u'magnolio-aws+canary-gamma-eu-central-1-adam@... |
class Retangulo:
def __init__(self, base, altura):
self.base = base
self.altura = altura
def area(self, area):
self.area = self.base * self.altura
def perimetro(self, perimetro):
self.perimetro = (self.base * 2) + (self.altura * 2)
r1 = Retangulo(0, 0)
r1.b... |
# Create your views here.
from __future__ import unicode_literals
from django.conf import settings
from django.shortcuts import render
import json
import smtplib
import base64
from django.http import HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import get_list_or_404, get_ob... |
from copy import deepcopy
from itertools import chain
from utensor_cgen.backend.base import BackendPart
from utensor_cgen.logger import logger
from utensor_cgen.utils import Configuration, class_property
class uTensorGraphLowerBase(BackendPart):
TARGET = 'utensor'
def handle_default(self, ugraph):
logger.wa... |
from .libgen import GeneratorReader
from .vectors import Vector3
def read_link(reader: GeneratorReader):
token = reader.read_token()
vals = token.split(" ")
return int(vals[0]), float(vals[1]), int(vals[2]), int(vals[3])
class Waypoint(object):
def __init__(self, index, id, position, radius):
... |
""" Calculate correlations between stocks """
import numpy
from stock_sourcer import StockSourcer
from threading import Thread
class CorrCalcThread(Thread):
def __init__(self, prcs_df, symbol, compare_syms, stagger, threshold):
super(CorrCalcThread, self).__init__()
self.prcs_df = prcs_df
... |
import nest
import numpy as np
import visualize
import data_analysis
import control_flow
msd = 123456
N_vp = nest.GetKernelStatus(['total_num_virtual_procs'])[0]
nest.SetKernelStatus({'grng_seed' : msd+N_vp})
nest.SetKernelStatus({'rng_seeds' : range(msd+N_vp+1, msd+2*N_vp+1)})
n,T_ms,R = control_flow.common_args()
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016-2023 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
import argparse
import os
import shutil
import tempfile
from multiprocessing import cpu_count
import pytest
from pandapower.test... |
from utils.consolecolor import ConsoleColor
def show_menu() -> str:
ConsoleColor.print_warning("Liste des functions :")
return input("1: Liste de tous les acteurs\n"
"2: Liste de tous les tournois\n"
"3: Modifier le classement d'un acteur\n"
"4: Créer un nouv... |
#!/usr/bin/env python
__author__ = 'krajcovic'
a, b = 0, 1
while b < 10000:
print b,
a, b = b, a + b
i = 256 ** 2
print '\nHodnota i je = ', i
|
from django.contrib import admin
from .models import Post, User, Comment, Clap
admin.site.register([Post, User, Comment, Clap])
# can also register models individually
# admin.site.register(Post)
# admin.site.register(User)
# admin.site.register(Comment)
# admin.site.register(Clap)
|
def cntr(hnd):
h = {} # Dictionary
for i in hnd:
h[i[0]] = h.get(i[0], 0) + 1
ret = [(h[i], '23456789TJQKA'.find(i)) for i in h]
return sorted(ret, reverse=True)
def handScr(hnd):
scr = list(zip(*cntr(hnd)))
scr[0] = [(1, 1, 1, 1, 1), (2, 1, 1, 1), (2, 2, 1), (3, 1, 1), (), (), (3, 2),... |
import time
import pytest # type: ignore
import pipx.animate
from pipx.animate import (
CLEAR_LINE,
EMOJI_ANIMATION_FRAMES,
EMOJI_FRAME_PERIOD,
NONEMOJI_ANIMATION_FRAMES,
NONEMOJI_FRAME_PERIOD,
)
# 40-char test_string counts columns e.g.: "0204060810 ... 363840"
TEST_STRING_40_CHAR = "".join([f"... |
import sqlite3
import time
import datetime
conn=sqlite3.connect('spot_db.db')
c=conn.cursor()
def create_table():
c.execute('CREATE TABLE IF NOT EXISTS result(count TEXT, face_time REAL)')
def data_entry():
c.execute("INSERT INTO st VALUES ('athul',5)")
conn.commit()
# ()
stop=0
def entry():
from count_test imp... |
# http://www.pythonchallenge.com/pc/def/0.html
'''It's simply to calculate 2^38 and change the URL'''
print(2**38)
|
#!/usr/bin/env python
import os, glob, sys
SMS = "T1tttt"
from ROOT import *
def combineCards(f , s ):
try:
os.stat('combinedCards')
except:
os.mkdir('combinedCards')
cmd = 'combineCards.py ' + f + '/BDT*txt > ' + f.replace(s,'combinedCards') +'/' + s + '.txt'
print cmd
... |
class People:
def __init__(self, name, age):
self.__name = name
self.__age = age
@property
def name(self):
#格式的规范,比如调用字符串的大写
return self.__name.upper()
@property
def age(self):
return self.__age
@name.setter
def name(self, name):
#do some le... |
# Generated by Django 3.1.7 on 2021-03-16 11:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AgentRef',
fields=[
... |
from day_two_input import puzzle_input
def get_invalid_password_count() -> int:
return sum([1 for line in puzzle_input if _is_valid(*line.split(":"))])
def _is_valid(policy, password) -> bool:
password = password.strip()
first_second_policy, letter = policy.split(" ")
first, second = first_second_... |
import _functions
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import peakutils as pku
# from scipy.optimize import leastsq
import scipy.signal
from lmfit import Parameters
from lagacy import _plot_functions
plt.style.use('bmh')
# Input sample name or names as str, case sensitive
_input_ele... |
from flask import Blueprint, jsonify, request
from infra.validacao import validar_campos
from infra.to_dict import to_dict, to_dict_list
from datetime import datetime
from services.mensagem_service import \
listar as service_listar, \
localizarRange as service_localizar, \
criar as service_criar, \
remo... |
#!/usr/bin/python3
from pprint import pprint as pp
import os, requests, time, json
from influxdb import InfluxDBClient
from config import *
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
client = InfluxDBClient(host=inf_cfg['h... |
import re
import argparse
import numpy
import random
import math
def get_args():
parser = argparse.ArgumentParser(description="Find kmers that uniquely define a satellite array in a genome")
parser.add_argument("-wgs1")
parser.add_argument("-wgs2")
parser.add_argument("-k")
parser.add_argument("-a... |
class ATM(object):
def __init__(self,card_number,pin_number):
self.card_number = card_number
self.pin_number = pin_number
def balanceEnquiry(self):
print("Your balance is more than your income. It is INR 35,000.")
def cashWithdrawl(self,money):
balance = 35000 - ... |
def solution1(arg):
return [i * 4 for i in arg]
def solution2(arg):
return [v * (i + 1) for i, v in enumerate(arg)]
def solution3(arg):
return [i for i in arg if i % 3 == 0 or i % 5 == 0]
def solution4(arg):
return [i for j in arg for i in j]
def solution5(arg):
return [
(x, y, z)
... |
# Generated by Django 3.2.6 on 2021-08-29 04:45
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Penerbit',
fields=[
... |
import os
BASE_DIR = os.path.abspath(os.path.dirname(__file__)) # 路径
class BaseConfig(object):
#object是python中所有类的父类,默认可以不写
# URI统一资源匹配符;配置数据连接的参数#app.config返回类字典对象,里面用来存放当前app的配置
SQLALCHEMY_COMMIT_ON_TEARDOWN = True
# sqlalchemy commit teardown请求结束后自动提交数据库修改
SQLALCHEMY_TRACK_MODIFICATIONS = True... |
# import sys, math
import numpy as np
# from scipy import misc
import Box2D
from Box2D.b2 import (polygonShape, circleShape, staticBody, dynamicBody, vec2, fixtureDef, contactListener, dot)
import gym
from gym import spaces
from gym.utils import colorize, seeding
import pyglet
from pyglet import gl
# This is a 2-D ... |
import unittest.mock as mock
from unittest import TestCase
from esrally import racecontrol, config, exceptions
class RaceControlTests(TestCase):
def test_finds_available_pipelines(self):
expected = [
["from-sources-complete", "Builds and provisions Elasticsearch, runs a benchmark and reports ... |
from scapy.layers.dns import DNS
from scapy.layers.inet import UDP
from scapy.layers.l2 import Ether
from Base import *
class NetworkDataExtractor(object):
def __init__(self):
self.devs_fea = {}
def process(self, devs, cache):
self.devs_fea = DevFeatures.copy_from_devdata(devs)
... |
from Entity import Entity
from Button import Button
class Victory(Entity):
def __init__(self, world=None, x=0, y=0, sprite=None, depth=0):
super().__init__(world, x, y, depth)
if sprite == None:
self.sprite = self.world.assetLoader.victory
else:
self.sprite = sprite
... |
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
from MessageReceiver import messageReceiver
from Constants import *
ADDR = (HOST, PORT)
client_socket = socket(AF_INET, SOCK_STREAM)
client_socket.connect(ADDR)
if __name__ == "__main__":
messageReceiver.read_incoming_messages(client_soc... |
import sys
from collections import OrderedDict
from bokeh.plotting import figure
from bokeh.models import GraphRenderer, StaticLayoutProvider, Oval
from bokeh.palettes import Spectral8
from bokeh.io import show, output_file
from bokeh.models import ColumnDataSource, Range1d, LabelSet, Label
import pprint
pp = pprint.... |
def marshal(n):
temp = n
mid = []
while True:
init = 0
while len(mid) > 0:
mid.pop()
outputValue = list(map(int, input().rstrip().split()))
if outputValue[0] == 0:
return None
for element in outputValue:
while init < temp and init != element:
if len(mid) > 0 and mid[-1] == element:
bre... |
from django.conf.urls.defaults import patterns, url
from webapp.views import *
urlpatterns = patterns('webapp.views',
# temporary url for YC
url(r'^yc/$', 'yc_no_login'),
url(r'^yc/(?P<extra>[-\w]+)', 'yc_no_login'),
#### end ####
url(r'^$', index,
#{'backend' : 'registration.b... |
import math
n,n1=map(int,input().split())
mul=n*n1
if math.sqrt(mul)==n or math.sqrt(mul)==n1:
print("yes")
else:
print("no")
|
'''Simon Graham Immunology Model
Model is initiated with an initial population of T-cells and cancer cells. This diversiy can be regulated by
changing sigma for both cancer and T-cell population when sampling from the log-normal distribution.
Here, there is no adoptive process and all sites are filled up correpondin... |
"""
至少有 K 个重复字符的最长字串
链接:https://leetcode-cn.com/problems/longest-substring-with-at-least-k-repeating-characters
找到给定字符串(由小写字符组成)中的最长子串 T ,要求 T 中的每一字符出现次数都不少于 k 。输出 T 的长度。
示例 1:
输入:
s = "aaabb", k = 3
输出:
3
最长子串为 "aaa" ,其中 'a' 重复了 3 次。
示例 2:
输入:
s = "ababbc", k = 2
输出:
5
最长子串为 "ababb" ,其中 'a' 重复了 2 次, 'b' 重复了 3 次。
... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
# 递归函数:fact(n) = fact(n -1) * n
# 理论上 所有的递归函数都可以写成循环方式
# 使用递归函数,需要防止栈溢出
def fact(n):
if n==1:
return 1
return n * fact(n - 1)
print(fact(10))
# 如果递归调用的层数过深,会造成栈溢出
# 解决递归调用栈溢出的方法是 尾递归优化
# 尾递归指,函数在返回的时候,调用自身,并且return语句不能包含表达... |
import mysql.connector
f=open("employee","r")
db=mysql.connector.connect(
host="localhost",
user="root",
password="Mathews@123",
database="pythonfeb",
auth_plugin="mysql_native_password"
)
cursor=db.cursor()
for lines in f:
line=lines.rstrip("\n").split(",")
sql="insert into employee(eid,ena... |
#coding=utf-8
from pykafka import KafkaClient
import codecs
import logging
logging.basicConfig(level = logging.INFO)
client = KafkaClient(hosts = "cdh-master-slave1:9092")
#生产kafka数据,通过字符串形式
def produce_kafka_data(kafka_topic):
with kafka_topic.get_sync_producer() as producer:
for i in range(4):
... |
import main
import helper
import clean
import pandas as pd
# for figure 1 select lambda and D_rot with below indices
lambda_index = 2
D_rot_index = 4
#
def load_data_for_figure1(): # run only once. Run again if lambda_index, D_rot_index (defined globally) changes
from inputs import Lambda_list, D_rot_list
# ... |
# -*- coding: utf-8 -*-
{
'name': "Quickbooks Odoo Connector",
'summary': """
QuickBooks Odoo Connector """,
'description': """
Export and import data to and from Quickbooks
""",
'author': "Techspawn Solutions",
'website': "http://www.techspawn.com",
# Categories can be u... |
# Generated by Django 3.2.16 on 2022-12-28 10:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("shop", "0034_product_active"),
]
operations = [
migrations.AlterField(
model_name="product",
name="slug",
... |
from .models import *
def get_tablet_brands():
brands=[]
for item in Tablet.objects.all():
if item.brand in brands:
continue
brands.append(item.brand)
return brands
def get_phone_brands():
brands=[]
for item in Phone.objects.all():
if item.brand in brands:
... |
import string
import time
def palindrome_checker(word): #checks if word is palindrome. Returns True if palindrome, else returns False.
length= len(word)
if length==0:
return False
if length==1:
if word== "a" or word=="i":
return True
else:
retur... |
from pwn import *
r = process("./smashme")
#r = remote("smashme_omgbabysfirst.quals.shallweplayaga.me", 57348)
raw_input("")
l = r.recvuntil("Welcome to the Dr. Phil Show. Wanna smash?\n")
print l
elf = ELF("./smashme")
addr_read = elf.symbols["read"]
bss = elf.bss()+0x100
log.info("[+]"+hex(addr_read))
shellcode = "\x... |
"""
@author: Julian Sobott
@created: 21.12.2018
@brief: Build project to release
@description:
create_release() is the relevant method.
copy all files except html and ignored files
html files: check if export
True: -> include all includes -> export
False: -> ignore
@external_use:
To INCLUDE a html fil... |
"""
Este modulo ofrece facilidades para el calculo de
integrales basandose en el Metodo de Monte Carlo.
Haremos una funcion para calcular una integral
de forma general y compararemos los resultados
con los devueltos por el modulo scipy.integrate.quad
"""
from math import inf
from numpy.random import random
def integ... |
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.conf import settings
def handler404(request, template_name='404.html'):
"""
Loads 404 page while passing scope
"""
scope = settings.CURRENT_SCOPE
return render_to_response(template_name, RequestC... |
if __name__ == '__main__':
score = 73
if score in range(60, 70):
print("C")
elif score in range(70, 80):
print("B")
elif score in range(80, 101):
print("A")
else:
print("error")
|
import os
import json
five_candidates=[]
ten_candidates=[]
not_working = []
missed=0
path = os.environ.get("tonic_dataset")
# all_songs = os.listdir("/home/kodhandarama/Desktop/Raga/Code/Audio_Analysis/lolol")
all_songs = os.listdir(path)
# all_songs.remove('.ipynb_checkpoints')
all_songs.sort()
for i in all_songs:
c... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Guifibages auth client for Squid
#
# Copyright 2012 Associació d'Usuaris Guifibages
# Author: Ignacio Torres Masdeu <ignacio@xin.cat>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... |
"""
Programmer: William Stobaugh, 9/9/21
Application: A practice on reading data from files
"""
#import other classes
from graph import Graph
from node import Node
from dataReader import Reader
from matplotlib import pyplot as plt
#init variables
heartFileReader = Reader("heartFailureDataset.csv")
heartF... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2017-12-28 23:24
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('product_app', '0011_auto_20171229_1210'),
]
operations = [
migrations.RemoveField(
... |
import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtWebEngineWidgets import *
class BrowserSettings(QWebEnginePage):
def userAgentForUrl(self, url):
return 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'
class MainWindow(QMai... |
import random
import math
N = 11
M = 3
K = 4
def init_random_list(list_size):
list = []
while list_size > 0:
list.append(random.randint(-100, 100))
list_size = list_size - 1
return list
lst = init_random_list(N)
print("source array:", lst)
del lst[K:K+M]
print("modified array:", lst)
|
import json
import re
def cleanhtml(raw_html):
cleanr = re.compile('<.*?>')
cleantext = re.sub(cleanr, '', raw_html)
return cleantext
def main():
src_path = "outputs/app_info.json"
src_file = open(src_path, 'r')
src_json = json.load(src_file)
out_path = "outputs/app_info_cleaned.csv"
out_fi... |
import sqlite3
import datetime
from numpy.core.records import record
def connect ():
try:
sqliteConnection = sqlite3.connect('car.db')
cursor = sqliteConnection.cursor()
print("Database created and Successfully Connected to SQLite")
except sqlite3.Error as error:
print... |
# coding:utf-8
import cv2 as cv
import numpy as np
import os
import re
import scipy.io as scio
import matplotlib.pyplot as plt
# src = cv.imread('/home/z840/dataset/UCF_Crimes/test/RoadAccidents002_x264/000001.jpg', cv.IMREAD_GRAYSCALE)
def pic_sub(dest):
white_num=0
height, width = dest.shape
for i in ran... |
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import base64
from odoo.tests.common import SavepointCase
from odoo.modules.module import get_module_resource
class TestProductConfiguratorCommon(SavepointCase):
@classmethod
def setUpClass(cls):
super().setUpClass()
... |
#!/usr/bin/python2
"""
This script is made to maintain the htc-dictionary.json file.
If you want to add or remove words, please use this script
instead of modifying the .json file directly.
"""
import os
import sys
import argparse
import logging
import textwrap
from src.linguist import Linguist
from src.utils import... |
import binascii
import os
import time
import base64
import hashlib
from Crypto import Random
from Crypto.Cipher import AES
from secretsharing import PlaintextToHexSecretSharer
from secretsharing import SecretSharer
BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS).encode()
unpad = la... |
# 用有序字典来记录每个字符即出现的次数
from collections import OrderedDict
def occur_once(strings):
if not strings:
return None
dt = OrderedDict()
for s in strings:
if s in dt.keys():
dt[s] = dt[s] + 1
else:
dt[s] = 1
# 或者
# dt[s] = dt[s]+1 if dt.get(s) else 1... |
#!/usr/bin/env python
from __future__ import absolute_import
from __future__ import division
import _init_paths
from datasets.factory import get_imdb
from model.test import test_net
from nets.vgg16 import vgg16
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="2"
os.environ['... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import serial
class Microscope():
def __init__(self, serial_port = "/dev/ttyACM0"):
self.brightness = 0
self.ser = serial.Serial(serial_port, 9600, timeout=3)
#possibly change the above line to be relevant to the arduino serial port
def __de... |
"""
MIT License
Copyright (c) 2021 Pablo Marquez Tello
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, pu... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import HtmlResponse
from jobparser.items import JobparserItem
class SjruSpider(scrapy.Spider):
name = 'sjru'
allowed_domains = ['superjob.ru']
start_urls = ['https://www.superjob.ru/vacancy/search/?keywords=Python&geo%5Bc%5D%5B0%5D=1']
def parse(s... |
# Import re : Regular Expression
import re
from string import maketrans
from sets import Set
osm_file = open("map.osm.xml", "r")
phone_number_format_CH = re.compile(r'\S+\.?$', re.IGNORECASE)
street_types = defaultdict(int)
phone_format = {}
# Audit Phone Numbers:
def phone_cleaning(phone_raw):
'''
:param ... |
#coding:utf-8
import os.path
import wx
import wx.lib.agw.aui as aui
import wx.stc
from drText import DrText
import drEncoding
import config, EpyGlob, utils
#*******************************************************************************************************
class DocNotebook(aui.AuiNotebook):
def __init__(s... |
from __future__ import annotations
from slay.entity.structure.base import Structure
from slay.rank import Rank
class PalmTree(Structure):
cost = 0
rank = Rank.TREE
|
import datetime
import glob
import math
import numpy as np
import os
import pandas as pd
import rasterio
import statsmodels.api as sm
import time
import xarray as xr
import sys
sys.path.append('../')
from functools import reduce
from scipy.interpolate import interp1d
from utils import power_curve
from utils import w... |
import numpy as np
# a = np.array([1,2,3])
# print(type(a))
# print(a.shape)
# print(a[0], a[1], a[2])
# a[0] = 5
# print(a)
# b = np.array([[1,2,3], [4,5,6]])
# print(b.shape)
a = np.zeros((2,2))
print(a)
b = np.ones((1,2))
print(b)
c = np.full((2,2,), 7)
print(c)
# Create a 2x2 identity matrix
d = np.eye(2)
pri... |
from book import Book
from kivy.app import App
from kivy.lang import Builder
from kivy.uix.button import Button
from kivy.properties import StringProperty
class DynamicBookApp(App):
status_text = StringProperty()
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.book_list = []
... |
import csv
import tensorflow as tf
import numpy as np
from sklearn import preprocessing
from midas import logger
import pandas as pd
class Gold:
def __init__(self):
logger.debug("Initialized a Gold object, {}".format(repr(self)))
def test(self):
train_data = pd.DataFrame(pd.read_csv("data/gold... |
#!usr/bin/python3
"""
字串文字接龍
"""
outstr=""
print('失敗就會退出遊戲!')
inputstr = input('請輸入一個接龍字串:')#python
while(True):
outstr += inputstr #outstr = python
print("上一個字串是:",outstr)
keyin = (input("請輸入-"+inputstr[-1]+"-開始的字串:"))
if(keyin[0]!=inputstr[-1]):
print("遊戲失敗")
... |
# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.db import models
from django.utils.translation import ugettext as _
MENU_TYPE_CHOICES = (
('APPETIZER', _(u'Appetizer')),
('ENTREE', _(u'Entrée')),
('DESSERT', _(u'Dessert')),
)
class Activity(models.Model):
name = models.CharFiel... |
from django.shortcuts import render, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import Group
from .forms import NewUserForm, StudentInfoForm, CompanyInfoForm
from django.views.generic import View
class IndexView(View):
template_name = 'home/home.html'
... |
def getDigits(x):
return sorted(list(str(x)))
x = 0
done = False
while not done:
x += 1
digits = getDigits(x)
for i in range(2,6):
done = True
n = x*i
n_digits = getDigits(n)
if(n_digits != digits):
done = False
break;
print(x)
... |
import numpy as np
from numpy.random import rand
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import matplotlib as mpl
import pandas as pd
import json
from skimage import exposure,img_as_ubyte
import time
import argparse
import os
import glob
import re
from scipy.interpolate import griddata
... |
import os
import cv2
from sklearn.metrics import recall_score, roc_auc_score, accuracy_score, confusion_matrix
from keras.callbacks import ModelCheckpoint
import scipy.misc as mc
import math
import numpy as np
from util import *
data_location = ''
testing_images_loc = data_location + 'RC_SLO/test/image/'
testing_label_... |
import pandas as pd
import numpy as np
import sys, os
sam1=sys.argv[1]
sam2=sys.argv[2]
asm1 = pd.read_table("process/"+sam1+".sort.mid",index_col=0).rename(columns={'Scaffold':sam1+"_scf",'Scaffold_Pos':sam1+"_pos"})
asm2 = pd.read_table("process/"+sam2+".sort.mid",index_col=0).rename(columns={'Scaffold':sam2+"_scf",... |
# q1 print something
print("jai bhadrakali")
# q2 concatinate strings
a=("jai ")
b=("bhadrakali")
print(a+b)
# q3 print 3 user variables
x=input("enter 1st var")
y=input("enter 2nd var")
z=input("enter 3rd var")
print(x,y,z)
# q4 print lets get started
a1="Let's Get Started"
print(a1)
# q5 print given value using p... |
import json
from django.test import TestCase, RequestFactory
from django.contrib.auth.models import Group
from django.urls import reverse
from rest_framework import status
from hs_core import hydroshare
from hs_core.views import get_supported_file_types_for_resource_type
class TestResourceTypeFileTypes(TestCase):
... |
import fileinput
import glob
cloudlist = []
value=0
for line in fileinput.input(glob.glob("part-r-0000*")):
lineseg=line.split();
''' line = line.replace(")","").replace("(","").replace(",","")
lineseg = line.split()
for l in lineseg:
l=l.strip()
'''
'''if lineseg[0].split(",")[0]==("love"): '''
... |
x,y=map(int,input().split())
z=list(map(int,input().split()[:x]))
if (z[y]%2!=0):
print(z[y])
else:
print(z[y-1])
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import zipfile
import subprocess
import os.path
import os
import shutil
import time
#拷贝文件并且修改依赖
def copyandmodifydepend(originpath,substratePath,injectDylibPath,insertToolPath):
dependPathPrefix = '@executable_path%sFrameworks' % os.sep
for dirpath, dirnames, filenames ... |
from django.views.generic import TemplateView
from django.conf import settings
from swagger_render.exceptions import IndexFileNotSetException
class SwaggerUIView(TemplateView):
template_name = 'swagger_render/index.html'
def get(self, request, *args, **kwargs):
try:
index_filename = geta... |
import torch
class ObjectDetectionBatch:
'''
This object wraps a single "batch"
consisting of images, boxes, and labels for the boxes.
The constructor (__init__) accepts a list "example_list", which are individual samples
loaded from the loader (fbs_loader)
It then then collates (batches) ... |
"""le_resto URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/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-base... |
from app import app
from flask import render_template
import sys
# sys.path.append('/pages')
from .pages import mainPage, indexPage
@app.route('/')
@app.route('/home')
def home():
return mainPage.render()
@app.route('/index')
def index():
return indexPage.render() |
# 1)Написать приложение, которое собирает основные новости с сайтов mail.ru, lenta.ru, yandex.news
# Для парсинга использовать xpath. Структура данных должна содержать:
# *название источника,
# *наименование новости,
# *ссылку на новость,
# *дата публикации
# 2)Сложить все новости в БД
from pprint import pprint
from l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.