text stringlengths 38 1.54M |
|---|
"""
Copyright (c) 2012 The GoSublime Authors
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, publish, dist... |
#!/usr/bin/env python
import glob
import os
import tarfile
import zipfile
import time
import datetime
def FindBundleRootDirs(dir):
bundleDirs = []
for root, dirs, files in os.walk(dir):
for file in files:
if "PUBLIC" in file:
bundleDirs.append(root)
return bundleDirs
de... |
import sys
import numpy as np
from PyQt4 import QtGui, QtCore
from main_window_base import Ui_MainWindowBase
from mode_choice_form import ModeChoiceForm
from scan_spectral_analysis_form import ScanSpectralAnalysisForm
from file_spectral_analysis_form import FileSpectralAnalysisForm
from classif_form import ClassifForm... |
#------------Naive Partition
#arr=[10,50,30,40,20]
def Naive(arr,n,p):
l=0
h=n-1
temp=[]
for i in range(n):
if arr[i]<p:
temp+=[arr[i]]
for j in range(n):
if arr[j]==p:
temp+=[arr[j]]
for z in range(n):
if arr[z]>p:
temp+=[arr[z]]
... |
"""
1. download list of kospi 200
"""
import csv
import requests
import re
from bs4 import BeautifulSoup
BASE_URL = 'http://finance.naver.com/sise/entryJongmok.nhn?&page='
for i in range(1, 22):
try:
url = BASE_URL + str(i)
r = requests.get(url)
soup = BeautifulSoup(r.text, 'lxml')
... |
from django.db import models
class Location(models.Model):
latitude = models.DecimalField(
max_digits=8,
decimal_places=6,
db_index=True,
)
longitude = models.DecimalField(
max_digits=8,
decimal_places=6,
db_index=True,
)
latitude_uke = models.CharFi... |
from numpy import *
a=array(eval(input("digite: ")))
b =zeros(shape(a)[0], dtype=int)
c=1
for i in range(shape(a)[0]):
for j in range(shape(a)[1]):
c = a[i,j] * c
b[i] = c / shape()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class FamilyArchiveDetail(object):
def __init__(self):
self._address = None
self._archive_id = None
self._area = None
self._birthday = None
self._cert_no = None
... |
import re,itertools
def solution(expression):
c=re.split(r'(\D)',expression);ret=[]
for oset in [[*x]for x in itertools.permutations([i for i in['*','-','+']if i in expression])]:
t=c[:]
for o in oset:
while o in t:i=t.index(o);t[i-1]=str(eval(t[i-1]+o+t[i+1]));t=t[:i]+t[i+2:]
... |
n=1
while n<=100:
if n>10:
break
print(n)
n=n+1
print('END')
m=0
while m<10:
m=m+1
if m%2==0:
continue
print(m) |
from typing import List
import numpy as np
import torch
from generators.nazari_generator import generate_nazari_instances
from generators.uchoa_generator import generate_uchoa_instances
from instances import VRPInstance
def generate_instance(n_customers: int,
distribution: str = 'nazari',
... |
#
# author: Cosmin Basca
#
# Copyright 2010 University of Zurich
#
# 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 a... |
from api.EComponent import EComponent
class EDevice(EComponent):
"""
A class representing an electrical device.
For example, an EDevice may be an LED, a servo, a light sensor, etc.
It stores the name of the device and the type of pin(s) it needs.
@cvar PIN_TYPES: A list of possible pin types... |
#! /usr/bin/python3
# -*- coding:utf-8 -*-
# @Time: 2020/6/14
# @Author: Lingchen
# @Prescription: 确定大学校园多样性
import pandas as pd
college = pd.read_csv('../data/college.csv', index_col='INSTNM')
college_ugds = college.filter(like='UGDS_')
print(college_ugds.head())
print(college_ugds.isnull().sum(axis=1).sort_values(a... |
# -*- coding: utf-8 -*-
from sqlalchemy import and_
from sqlalchemy import func
from models import db
from models import ItemComment
from models import Item
from models import Hospital
from ops.utils import get_page
from ops.utils import... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.contrib.contenttypes.models import ContentType
from django.contrib.contenttypes import generic
#==============================================================================
class Featured(models.Model):
created... |
import argparse
parser = argparse.ArgumentParser(description="Payload experiment to perform a 3-point bending test on a self-healing material",
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-b", "--runb", action="store_true", help="Select second experiment to run")
args... |
import json
import unittest
from crassus.deployment_response import DeploymentResponse
from crassus.output_converter import OutputConverter
from mock import call, patch
from utils import load_fixture_json
cfn_event = load_fixture_json('cfn_event.json')
cfn_event_different_termination = load_fixture_json(
'cfn_eve... |
# Chris DeBoever
# cdeboeve@ucsd.edu
import sys, argparse, pdb, glob, os, re
import numpy as np
### helper functions ###
p_match = re.compile('\.|,') # regular expression that matches characters that indicate a match in the pileup file
p_alt = re.compile('[ATCG]',flags=re.IGNORECASE) # regex that matches alternate b... |
from torch.utils.data import DataLoader
from protozoo.datasets import Fluo_N2DH_SIM
from protozoo.trainer import get_trainer
from exampleupload.modelzoo import get_entry
if __name__ == "__main__":
model_zoo_entry = get_entry()
trainer = get_trainer(model_zoo_entry)
dl = DataLoader(Fluo_N2DH_SIM())
... |
import logging
__version__ = "0.1.0"
# Configure logging
log = logging.getLogger(__name__)
log.addHandler(logging.StreamHandler())
from .core import RemoteTessImage
from .targetpixelfile import TargetPixelFile
from .bite import bite, bite_header, bite_ffi, bite_asteroid
__all__ = [
"bite",
"bite_header",
... |
from keras.layers import Flatten, Dense, Input
from keras.models import Model
import numpy as np
import os
import tensorflow as tf
from tensorflow import keras
import pickle
import cv2
import keras
from keras.applications.resnet50 import ResNet50
from keras.models import model_from_json
from sklearn.model_selection imp... |
from socket import *
import sys
import os
id = 20153235
name = 'Jungkeun Cho'
print('Student ID : ' + str(id))
print('Name : ' + name)
serverPort = int(sys.argv[1])
serverSocket = socket(AF_INET, SOCK_STREAM)
serverSocket.bind(('',serverPort))
serverSocket.listen(1)
while( True ):
print()
c... |
from genes import *
from geneticOptimizer import *
inputs = [[0, 0], [0, 1], [1, 0], [1, 1]]
outputs = [0, 1, 1, 0]
class XorFitness:
def calculateFitness(self, population, _):
for list in population:
for ind in list["individuals"]:
error = 0
for input, output i... |
# whisper 18.mp3 --language Chinese --initial_prompt "以下是普通话句子"
import whisper
model = whisper.load_model("large")
result = model.transcribe("18.mp3")
print(result["text"])
|
#!/usr/bin/env python2
"""ROS Node for publishing desired positions."""
from __future__ import division, print_function, absolute_import
# Import ROS libraries
import roslib
import rospy
import numpy as np
from geometry_msgs.msg import PoseStamped
from std_msgs.msg import String, Bool
from tf.transformations impor... |
import shutil
import os
from PyQt4 import QtGui, QtCore
from widget.DialogCopyFiles import DialogCopyFiles
def copy_with_dialog(project, path):
media_directory = os.path.join(unicode(project.directory), "medias")
if not os.path.exists(media_directory):
os.mkdir(media_directory)
direct... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# (c) 2012 Bright Interactive Limited. All rights reserved.
# http://www.bright-interactive.com | info@bright-interactive.com
import os.path
import sys
# put parent dir on sys.path so that "import bright_vc" will work
sys.path.append(os.path.dirname(os.path.dirname(os.path... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-11-24 01:32
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_depende... |
import pymzn
print("Nurse/Doctor Rostering: \n "
"1.Prepare a Nurse Roster. \n "
"2.Prepare a Doctor Roster.\n")
choice = input("Enter Your Choice: ")
if choice == '1':
print("Nurse Rostering: \n "
"1.Prepare a Nurse Roster in which every nurse has an equal number of day, night and of... |
#from __future__ import print_function
import struct
import datetime
from time import sleep
from datetime import tzinfo, timedelta
import IdList
import zipfile
import os
import sys
import threading
import logging
class LoggerWriter:
def __init__(self, level):
self.level = level
def wri... |
import discord
from discord.ext import commands
import random
import time
import asyncio
from pymongo import MongoClient
import pymongo
import json
from datetime import datetime, timedelta
prefixos = ["c.","!","@","/"]
python = ['python', 'py']
javascript = ['javascript','js']
kotlin = ['kotlin','kt']
java = ['java'... |
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from __future__ import unicode_literals
from charlesxlogminmax.extract_data import extract_log_data
from charlesxlogminmax.plot_min_max import plot_log_data
if __name__ == "__main__":
# Test with csv input... |
class BlendFrame(object):
RENDER_SUCCESS = 0
RENDER_FAILED = 1
RENDER_PENDING = 2
RENDER_ACTIVE = 3
def __init__(self, frame_num, state, file_name):
self.file_name = file_name
self.frame_num = frame_num
self.state = state
def completed_rendering(self, state):
self.state = state
def get_state(self):
... |
from db import session as db
from db_setup import Category, Item
from flask import flash, url_for, redirect
from functools import wraps
def validate_record(table_name):
'''View decorator that validates record existance.
Record is valid if it exists.
Args:
table_name: Table (model) to look in.
... |
from xml.dom import minidom
# Build DOM
doc = minidom.parse("xml_tim_small.xml")
# Get list op operations
operations = doc.getElementsByTagName("operation")
# Iterate over operations and process each operation
for operation in operations:
# operationId
operationId = operation.getElementsByTagName("oper... |
import urllib, urllib2, base64, socket, smtplib, ssl, sys, cookielib, json, os
from tools.format import readable_json
from tools.apis import get_apis_list, get_api_info
from tools.auth_token import get_csrf_token
from tools.licenses import get_licenses_for_api, add_licenses, get_resources_for_api, get_scopes_for_api, g... |
# Learnings
# Kadane's algorithm
# http://theoryofprogramming.com/2016/10/21/dynamic-programming-kadanes-algorithm/
# How I converted suboptimal O(n^2) to O(2^n)
# https://docs.google.com/document/d/1aACr9Aztz5dfMyhow0UAFuMRujVMGjWu-uY-mpRcwxM/edit
# Given an integer array nums, find the contiguous subarray (contain... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '18/6/13 21:35'
"""
工厂模式
举例,改功能并不复杂,实际写一个类即可解决
"""
# 运算类基类
class Operation(object):
def __init__(self):
self.numberA = None
self.numberB = None
def get_result(self):
result = 0
return result
# 具体运算类(... |
import sys
def solution(k, pages):
table = [[float('inf')]*k for _ in range(k)]
for i in range(k):
table[i][i] = 0
# 15
# 1 21 3 4 5 35 5 4 3 5 98 21 14 17 32
for i in range(k):
for j in range(i, k):
left = j - i
s = sum(pages[left:j+1])
for d in range(left, j):
mid = d
# print(left, mid, j)
... |
from abydos.phonetic import NRL
def word_phonetics(word) -> 'phonetical_representation':
phonetical_algorithm = NRL()
return {'value': phonetical_algorithm.encode_alpha(word['value'])}
|
#BINARY CLASSIFICATION MODEL
# MLP in Keras
# Import all the necessary libraries
from keras.models import Sequential
from keras.layers import Dense
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from keras.callbacks import EarlyStopping
from keras.callbacks import ModelCheckpoint
from sklearn im... |
from revizor2.cloud import ExtendedNode
from revizor2.conf import CONF
def assert_cloudinit_installed(node: ExtendedNode):
cmd = 'coreos-cloudinit --version' if CONF.feature.dist.id == 'coreos' else 'cloud-init -v'
with node.remote_connection() as conn:
out = conn.run(cmd).status_code
if out !... |
import string, glob
import numpy as np
import matplotlib.pyplot as plt
from pprint import pprint
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
ep_c = np.genfromtxt('carbon.txt', delimiter = '\s+', unpack=True, dtype=None, encoding=None)
ep_h = np.genfromtxt('ld2.txt' , delimiter = '\s+', unpack=True,... |
import tensorflow as tf
NUM_CHANNELS=1
FEATURE_SHAPE=[12,3665]
CONV1_DEEP=32
CONV1_SIZE=5
CONV2_DEEP=64
CONV2_SIZE=5
FC_SIZ=512
NUM_LABELS=21
WORD_LEN=200
def inference(input_tensor,train,regularizer):
with tf.variable_scope('layer0-embedding'):
input_tensor=tf.reshape(input_tensor,[-1,FEATURE_SHA... |
#!/usr/bin/env python
# encoding: utf-8
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Vers... |
import CleanedData as CD
def get_Look_And_Feel():
"""
get_Look_And_Feel checks plasma directories for look and feel themes
Returns:
(list): list of look and feel themes
"""
UserThemes = CD.files_In_Path("/.local/share/plasma/look-and-feel/")
SystemThemes = CD.files_In_Path("/usr/share... |
#!/usr/bin/env python3
import subprocess
import time
import os
with open(os.environ['MOUNT_SCRIPT']) as f:
host_script = f.read()
assert 'FILESERVERS' in os.environ
assert 'MOUNT_PATH_TEMPLATE' in os.environ
while True:
try:
subprocess.check_call([ 'nsenter',
# nseenter on alpine wants it... |
grid1 = [
["1", "1", "1", "1", "0"],
["1", "1", "0", "1", "0"],
["1", "1", "0", "0", "0"],
["0", "0", "0", "0", "0"]
]
grid2 = [
["0", "0", "0"],
["0", "1", "1"],
["0", "0", "0"]
]
def numIslands(grid):
count = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
... |
# Uses python3
def edit_distance(s, t):
T = [[100]*(len(s)+1) for _ in range(len(t)+1)]
for i in range(len(s)+1):
T[0][i] = i
for j in range(len(t)+1):
T[j][0] = j
for i in range(1,len(t)+1):
for j in range(1,len(s)+1):
diff = 0 if s[j-1]==t[i-1] else 1
T[i][j] = min(T[i-1][j]... |
#TV Release Module by o9r1sh September 2013
import urllib,urllib2,re,xbmcplugin,xbmcgui,xbmcaddon,sys,main,xbmc,os
net = main.net
artwork = main.artwork
base_url = 'http://tv-release.org'
settings = main.settings
def TV_CATEGORIES():
main.addDir('XVID Episodes',base_url + '/index.php?page=1&cat=TV-XviD','tvre... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: abhijit
"""
import numpy as np
import pandas as pd
df1 = pd.DataFrame({'A': ['a'+str(i) for i in range(4)],
'B': ['b'+str(i) for i in range(4)],
'C': ['c'+str(i) for i in range(4)],
'D': ['d'+str(i) for i in range(4)]})
df2 = pd.DataFrame({'A'... |
def is_prime_num(num):
for i in range(2, num):
if (num % i) == 0:
return False
else:
return True
prime_numbers = [i for i in xrange(2, 10000) if is_prime_num(i)]
def get_largest_prime(num):
result = 0
for i in prime_numbers:
if num % i == 0:
result = i... |
"""Utility functions to load data from different sources."""
# Standard imports
import glob
import logging
import os
import random
import math
# Dependency imports
import numpy as np
from osgeo import gdal # pylint: disable=E0401
# Local imports
from visualization import pim
def load_file_paths(data_dir, match_dir_... |
'''
理解Python的yield与send()语句
https://blog.csdn.net/levon2018/article/details/82492240
next()跟send()不同的地方是,next()只能以None作为参数传递,而send()可以传递yield的值
n = yield r可以理解为yield在发送n的同时也在接收r值
通过produce(c)调用后,一旦有n值,则切换到 consumer去执行。执行完了后生成器关闭
'''
def cf(x):
for i in range(x):
print('before yield, x={0}, i={1}'.format(x... |
from astropy.tests.helper import remote_data
from beast.physicsmodel.grid import SEDGrid
from beast.observationmodel.noisemodel import generic_noisemodel as noisemodel
from beast.fitting.trim_grid import trim_models
from beast.tests.helpers import download_rename, compare_hdf5
from beast.observationmodel.observations ... |
print "陳顗丞"
y=10
print "陳顗丞y歲"
print "陳顗丞%d歲" % y
print "陳顗丞"
y=10
print "陳顗丞y歲"
print "陳顗丞%d歲" % y
|
#!/usr/bin/env python
import CPAC
CPAC.pipeline.cpac_runner.run('22_roi_config.yml', 'release1_CPAC_subject_list.yml')
|
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File: LinuxBashShellScriptForOps:threadingExample.py
User: Guodong
Create Date: 2016/11/1
Create Time: 18:14
"""
import threading
import time
def fn_timer(func):
from functools import wrap... |
import pandas as pd
import os
import numpy as np
import datetime as dt
def read_data():
# This function is called by each individual visualization script to read the data from
# the csv's and do some processing used by all
os.chdir('C:/Users/jesse/Documents/Grad_School/Other/Data Visualization Challenge')
... |
"""
-------------------What are generators in Python?----------------------------------
There is a lot of overhead in building an iterator in Python; we have to implement a class with __iter__() and
__next__() method, keep track of internal states, raise StopIteration when there was no values to be returned etc.
This ... |
#1
##n=int(input("enter a number:"))
##c=0
##for i in range(1,n+1):
##if n%i==0:
##c+=1
##if c==2:
##print(n,"is a prime")
##else:
##print(n,"is not a prime")
#2
##n=int(input("enter a number:"))
##c=0
##for i in range(1,n+1):
##if n%i==0:
##c+=1
##print(i... |
import datetime
import json
import requests
from unswtools.login import load_credentials
login_url = "https://aims.unsw.edu.au/page.php?pg=common.Login"
auth_url = "https://aims.unsw.edu.au/_basic/auth/doLogin.php"
portfolio_url = "https://aims.unsw.edu.au/page.php?pg=common.Portfolio"
service_url = "https://aims.u... |
from stl import mesh
from matplotlib import pyplot
from mpl_toolkits import mplot3d
figure = pyplot.figure()
axes = mplot3d.Axes3D(figure)
my_mesh = mesh.Mesh.from_file("untitled.stl")
axes.add_collection3d(mplot3d.art3d.Poly3DCollection(my_mesh.vectors))
scale = my_mesh.points.flatten(-1)
axes.auto_scale_xyz(scale... |
import numpy as np
import matplotlib.pyplot as plt
import scipy
from scipy.stats import norm
n=100
a=np.arange(n)
#Centrar
sigma=0
#Escala
escala = 100
alpha = 4*escala
pqc=10*escala
#Pto a evaluar
pto=1000
x_1 = np.linspace(scipy.stats.norm(sigma, alpha).ppf(0.01), scipy.stats.norm(sigma, alpha).ppf(0.99), 100)
... |
from django.urls import path
from django.contrib.auth.views import LogoutView
from . import views
urlpatterns = [
path('', views.MyLoginView.as_view(), name='login'),
path('home/', views.home, name='home'),
path('logout/', LogoutView.as_view(), name='logout'),
path('account/register/', views.register,... |
from flask_wtf import FlaskForm
from flask_login import current_user
from wtforms.fields import StringField, PasswordField, SubmitField
from wtforms.validators import InputRequired, DataRequired, ValidationError
from models.model import User
class SignUpForm(FlaskForm):
name = StringField('Name', validators=[Inpu... |
import os
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow_hub as hub
from sklearn import preprocessing
import spacy
EN = spacy.load('en_core_web_sm')
import logging
logging.getLogger('tensorflow').disabled = True
data = pd.read_csv('models/Preprocessed_data.csv')
import fasttext
fast... |
from auxt.expt.result.m2 import M2ResultTableFactory
from auxt.directory.expt.outdir import EnsembleR2LRerankOutDir
from auxt.expt.score.run import ScoreRunScriptInterface
from auxt.util.prod import make_train_indices
from auxt.script.run import RunScript
from .util import ErrantJobScript
class FMValidErrantJobScript(... |
"""Code that handles logging for the project."""
import logging
import logging.handlers
import sys
import colorclass
class ColorFormatter(logging.Formatter):
"""Custom logging formatter that introduces console colors if not verbose."""
SPECIAL_SCOPE = __package__
def __init__(self, verbose, colors):
... |
#Ricahrd Deegan
# Ask user for input of three variables.
x = float(input("Please enter petal_lenght: "))
y = float(input("Please enter petal_width: "))
#Isolate Setosa measurements first taking largets petal lenght value.
#Isolate Virsicolor measurements second, everything else is likely veriginica.
if x... |
from flask import Flask, request, render_template, send_from_directory, \
jsonify, stream_with_context, Response
import json
from app.controllers.concerns import naive_bayes, \
b2_storage, local_storage, \
airbnb_crawler
import os
from dotenv import load_dotenv
import threading
import time
import gevent
fro... |
# python 3 required - python3 generate_files.py
import csv, math, os
from printer import print_challenge_pdfs, print_general_pdfs, print_teams_in_room, merge_pdfs
from split_teams import split_teams
from team import Team
import companies as c
import rooms as r
JUDGES_COUNT = int(input('Number of judges: '))
JUDGE_PAIR... |
from mcpi.minecraft import Minecraft
import time
mc=Minecraft.create()
stayed_time=0
while True:
time.sleep(0.5)
pos=mc.player.getTilePos()
mc.postToChat("please goto home x=-21 y=14 z=74 for 15s to fly")
mc.postToChat("x:"+str(pos.x)+"y:"+str(pos.y)+"z:"+str(pos.z))
if pos.x==-21 and pos.y==14 ... |
from operator import itemgetter
class Pagination:
@classmethod
def paginate_list(cls, items, page_size, page_index, sort_key=None, reverse=True):
"""
对所有查询结果进行分页处理
:param items:
:param page_size: 每页多少个条目
:param page_index: 当前查询哪一页
:param sort_key: 用哪个key排序
... |
from base.PT import PTWorker, test_intercomm
from base.client import Client
import numpy as np
class Async_PTWorker(Client,PTWorker):
'''
Asynchronous Worker class
'''
def __init__(self, port, config, device):
Client.__init__(self, port = port)
PTWorker.__init__(s... |
# Generated by Django 2.1.1 on 2018-11-21 01:13
import datetime
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('pessoal_quadro', '0004_auto_20181115_1742'),
]
operations = [
migrations.CreateModel(
... |
# -*- coding: utf-8 -*-
###############################################################################
# Nicolas Pécheux <nicolas.pecheux@limsi.fr>
# Thursday Jun 28, 2012
###############################################################################
#
# Possible improvements :
# For the moment for coredundancy I che... |
import sys
from collections import namedtuple
Student = namedtuple('Student', ['firstname', 'surname', 'id'])
def show_student(student):
print ('{:>10s}: {:<s}'.format('First name', student.firstname))
print ('{:>10s}: {:<s}'.format('Surname', student.surname))
print ('{:>10s}: {:<d}'.format('ID', student.id... |
from collections import deque
def atomize(l):
return deque(
map(
lambda x: deque([x]),
l if l is not None else []
)
)
def merge(l, r):
res = deque()
while (len(l) + len(r)) > 0:
if len(l) < 1:
res += r
r = deque()
elif len... |
#!/usr/bin/env python
import sys
import os
import os.path
import time
import numpy
import cv2
import argparse
import decode
import getopt
DEBUG = False
LEFT_GUARD = "101"
RIGHT_GUARD = "101"
RIGHT_GUARD_UPCE = "010101"
CENTER_GUARD = "01010"
CODE_LEN = 7
EAN13_SYMBOL_NUM = 12
UPC_E_SYMBOL_NUM = 6
EAN8_SYMBOL_NUM = 8
C... |
import copy
import os
from typing import overload
import numpy as np
from replication.preprocess.condition import Condition
STRESSED_PREFIX = "stressed"
UNSTRESSED_PREFIX = "unstressed"
class User:
stressed_condition: Condition
unstressed_condition: Condition
name: str
def clean_data(self):
... |
#!/usr/bin/env python
import rospy
from sensor_msgs.msg import CameraInfo
from std_msgs.msg import Header, String , Int8
if __name__ == '__main__':
rospy.init_node('caliberation', anonymous=True)
pub = rospy.Publisher('/iris/CameraInfo', CameraInfo, queue_size=10)
rate = rospy.Rate(25) # 10h
pos = CameraInfo()... |
from os import environ
from flask import Flask, jsonify
app = Flask(__name__)
# app.config['API_KEY'] = environ.get('STRIPE_KEY')
# app.config['DB_NAME'] = environ.get('DB_NAME')
# app.config['DB_USER'] = environ.get('DB_USER')
# app.config['DB_PWD'] = environ.get('DB_PWD')
# app.config['DB_HOST'] = environ.get('DB_H... |
temp = float(input('Qual a temperatura atual em ºC?: '))
f = (temp * 9/5) + 32
print('A temperatura de {}ºC corresponde a {}ºF.'.format(temp, f))
|
# GABRIEL DIAS DE OLIVEIRA, RA: 176495
# LAB04: CRIAÇÃO DE UM PROGRAMA QUE CALCULA O QUANTO UMA "APLICAÇÃO" RENDE A UMA TAXA DE JUROS MENSAL.
from decimal import Decimal
# CRIAÇÃO DAS VARIAVEIS BASES DO PROGRAMA, APLICAÇÃO INICIAL (CAPITAL),
# JUROS MENSAIS E
# QUANTOS MESES ESSA APLICAÇÃO RENDERÁ
capital = Decimal(... |
# Validating Postal Codes
#######################################################################################################################
#
# A postal code P must be a number in the range of (100000 - 999999).
# A postal code P must not contain more than one alternating repetitive digit pair.
# Alternati... |
#!/usr/bin/python3
import argparse
import pocket_api
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--dir", default="/")
args = parser.parse_args()
namenode_ip = "10.1.0.10"
p = pocket_api.connect(namenode_ip, 9070)
listed = pocket_api.list_dir(p, args.dir, "")
for f i... |
try:
2 + 's'
except TypeError:
print "There was a type Error"
except Exception as ex1:
print (ex1)
print (type(ex1))
finally:
print "This is the final statement"
###########################################################################
try:
s = 1/0
except TypeError:
print "There was a ty... |
from activityio.gpx._reading import read_and_format as read
from activityio.gpx._reading import gen_records
|
3.Python Program to Count the Number of Digits in a Number
n=int(input("Enter the number"))
num=n
count=0
while(n!=0):
n=n//10
count+=1
print("Number of digits in ",num," is ",count)
|
from flask import Flask, render_template, request, jsonify, session, redirect, url_for, Blueprint, flash, current_app
from collections import defaultdict
from . import helper_functions as helpFunc
from .db import get_db
import requests
import json
from iexfinance.stocks import Stock, get_historical_data
from datetime i... |
from application import app, db, admin_required, login_manager
from flask import render_template, request, url_for, redirect, flash
from application.models import Ryhma
from application.forms.ryhmat import RyhmaTiedotForm
from application.helpers.autorisointi import ryhma_autorisaatio
@app.route("/ryhmat/uusi/")
@adm... |
import sys
sys.path.append("..")
from floodberry import floodberry_ed25519
import timeit
from benchmark_constants import ED_REPEAT as REPEAT_NUM
"""
Benchmarks the elliptic curve arithmetic.
"""
#scale base point
setup = "from floodberry_ed25519 import GE25519 as ge; from random import randint"
statement = "a = ge(... |
import simpletable as st
css = """
table.mytable {
font-family: times;
font-size:12px;
color:#000000;
border-width: 1px;
border-color: #eeeeee;
border-collapse: collapse;
background-color: #ffffff;
width=100%;
max-width:550px;
table-layout:fixed;
}
table.mytable th {
border-... |
#!/usr/bin/env python
# coding=utf-8
import tornado.ioloop
import tornado.web
import shutil
import os
import json
class FileUploadHandler(tornado.web.RequestHandler):
def get(self):
self.render("file.html")
def post(self, *args, **kwargs):
print(self.get_argument("user"))
print(self.... |
# Generated by Django 3.1.3 on 2021-03-17 16:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0011_remove_foodrequest_img'),
]
operations = [
migrations.CreateModel(
name='shopper',
fields=[
... |
class Solution:
def spiralOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if len(matrix) == 0 or len(matrix[0]) == 0:
return []
T = 0
R = len(matrix[0]) - 1
B = len(matrix) - 1
L = 0
result = ... |
#!/usr/bin/env python
from pprint import pprint
import kaboom.api
import kaboom.vm
def walk_blocks(api):
block = api.last_block()
parent_hash = block['hash']
nr = int(block['number'])
while parent_hash != "0000000000000000000000000000000000000000000000000000000000000000":
block = api.block(p... |
for row in range(7):
for col in range(7):
if(col==0 or col==6)or((col==row) and (col in [1,2,3,4,5] and row in [1,2,3,4,5] )):
print("*",end="")
else:
print(end=" ")
print()
"""
* *
** *
* * *
* * *
* * *
* **
* *
"""
for row in range(7):
for... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.