text stringlengths 38 1.54M |
|---|
def igualLista(lista1,lista2):
if len(lista1) == 0:
return True
else:
return igualLista(lista1[1:],lista2[1:]) and lista1[0]==lista2[0]
l1 = [1,2,3,4]
l2 = [2,1,3,4]
print(igualLista(l1,l2)) |
#!/usr/bin/env python3
import random
class Gun:
def __init__(self, name, damage):
self.name = name
self.damage = damage
def __repr__(self):
return "%s (%d damage)" % (self.name, self.damage)
# example: prints "AWP (100 damage)"
class CSGOPlayer:
# class variables
num_players = 0
def __in... |
#Latest Python Feature for Asynchronus Programming
import asyncio
import time
async def waiter(n):
await asyncio.sleep(n)
print(f"Waited for {n} seconds")
async def main():
# print("HEllo")
# await asyncio.sleep(1)
# print("world")
task1 = asyncio.create_task(waiter(2))
task2 = asyncio.... |
from pyspark import SparkContext
from pyspark.sql import SQLContext
from pyspark.sql.types import *
sc = SparkContext.getOrCreate()
'''
1. loads the text datafile to pyspark
2. apply schema and create DataFrame table
'''
financial_suite = sc.textFile("file:///data/staging/final/financial_suite.txt")
financial_suite... |
from distutils.spawn import find_executable
from gwemlightcurves.KNModels import table
from gwpy.table import EventTable
from gwpy.plotter import EventTablePlot
import astropy.units as u
import astropy.constants as C
G = C.G.value; c = C.c.value; msun = u.M_sun.to(u.kg)
plot = EventTablePlot(figsize=(20.5, 10.5))
EOS... |
# -*- coding: UTF-8 -*-
import os
import xml.etree.ElementTree as ET
import unicodedata
import operator
import re
from nltk.tokenize import sent_tokenize
def get_link(pdfPath):
pwd = os.path.dirname(os.path.abspath(__file__))
father_path = os.path.abspath(os.path.dirname(pwd) + os.path.sep + ".")
... |
import png
cols = 40
rowSize = cols*2
rows = 20
def printText(vmem, px, py, s, fg, bg):
addr = py*rowSize + px*2
for i in range(len(s)):
vmem[addr + i*2] = ord(s[i])
vmem[addr + 1 + i*2] = fg*16+bg
fg+=1
bg+=1
if (fg == 16):
fg = 0
if (bg == 16):
... |
import numpy as np
import torch
from os.path import join, split, isdir, isfile, split, abspath, dirname
import os
import torch.nn as nn
from dataload.dataset import rec_chroma
from torch.optim import lr_scheduler
from models.nrcnn import NRCNN, Extened_NRCNN
import torch.nn.functional as F
import argparse
imp... |
from Builder.Relation import *
import json
import os
import datetime # For observation grouping #Delta Time Creation
class Controller:
def __init__(self):
self.relationships_main = []
self.dependencies_main = []
self.project_name = None
def update(self, project):
# Clear pre... |
from calcular import Calcular
def start(pontos):
pontos: int = 0
jogar(pontos)
def jogar(pontos: int):
dificuldade: int = int(input('Qual o nivel de dificuldade [1, 2, 3 e 4]: '))
calc: Calcular = Calcular(dificuldade)
calc.mostra_calc
resultado: int = int(input('Resultado: '))
if calc.res... |
import base64
import copy
import datetime
import os
from decimal import Decimal
from unittest.mock import patch
import django
import pytest
import pytz
from django.core.exceptions import ValidationError
from django.test import TestCase, override_settings
from rest_framework import serializers
from rest_framework.field... |
# Generated by Django 3.0.7 on 2020-07-01 10:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('account', '0003_remove_userinfo_age'),
]
operations = [
migrations.CreateModel(
name='addapps',... |
# hashtable
from hashtable import HashTable
from time import time
class CheckPrice(object):
def __init__(self, file_path):
# instance variables
self.number_and_cost = self.store_routes_cost(file_path)
# store cost of routes into the hash table
def store_routes_cost(self, file_path):
... |
# -*- coding: utf-8 -*-
from sqlalchemy import *
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import func
from sqlalchemy import update
from datetime import datetime
from config import mysql
# from SQLAlchemy.pool import NullPool
# 安装的扩展库SQLAlchemy
co... |
import numpy as np
import tflite_runtime.interpreter as tflite
import open_myo as myo
from kulka import Kulka
import time
isReadyToRegisterData = False
samplesPerSeconds = 0
dataRecollectedPerIteration = list()
ADDR = '68:86:e7:00:ef:40'
#interpreter = tf.lite.Interpreter(model_path="myLittleModel.tflite")
interprete... |
# -*- coding: utf-8 -*-
import pandas as pd
import random
import operator
class Monster_In_A_Box:
def __init__(self, index, data_frame):
self.idx = index
self.generate_from_df(data_frame)
'''
self.readable_name (name of the encounter of this box (as of 4/2/2019 this is empty, need ... |
# wd.py
# WikiData things
import csv
from pprint import pprint
from time import sleep
from qwikidata.entity import WikidataItem, WikidataLexeme, WikidataProperty
from qwikidata.linked_data_interface import get_entity_dict_from_api
from qwikidata.sparql import (get_subclasses_of_item,
re... |
from packages_model import *
def get_packages( p_id_client, p_id_branch ):
packages_list = get_packages_by_id_client( p_id_client, p_id_branch )
def make_response( p_status, p_data ):
return 0
|
"""This will draw the plant loop for any file """
import pydot
import sys
sys.path.append('../EPlusInputcode')
from EPlusCode.EPlusInterfaceFunctions import readidf
import loops
iddfile = "../iddfiles/Energy+V6_0.idd"
# fname = "/Applications/EnergyPlus-6-0-0/Examples/DualDuctConstVolGasHC.idf"
# fname = "../idffiles... |
"""Adding column ex_date to daily_stock_data.
Revision ID: 63c962ea0422
Revises:
Create Date: 2021-06-03 14:35:30.262401
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '63c962ea0422'
down_revision = None
branch_labels = No... |
from django.core.management.base import BaseCommand
from io import BytesIO
import pandas
import requests
import json
import os
from decaptcha.models import Image
class Command(BaseCommand):
OBJECT_JSON = '/Users/leohentschker/de-captcha/backend/data/objects_test.json'
METADATA_JSON = '/Users/leohentschker/de... |
# -*- coding: utf-8 -*-
from gnet.protocol import TCPServerFactory, ReconnectingClientFactory, Protocol
from gnet.util import shorten
import gevent
import logging
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format='[%(asctime)-15s %(levelname)s:%(module)s] %(message)s')
class EchoSe... |
#!/usr/bin/env python3
import argparse
import sys
import requests
import tabulate
import json
class Mondo:
# 0: title
INDEX_TITLE = 0
# 1: icon
# 2: type
INDEX_TYPE = 2
# 3: containerType
# 4: containerPlayable
# 5: personType
# 6: albumType
# 7: imageType
# 8: aud... |
file = [int(l.strip()) for l in open("data.txt")]
file.sort()
file.append(max(file) + 3)
file.insert(0, 0)
counts = [0] * 3
for x in range(len(file)-1) :
counts[file[x+1] - file[x] - 1] += 1
print "P1: " + str(counts[0] * counts[2])
def recurseCombinations(x) :
if x <= 1 :
return 0
if x == 2 :
return 1
retur... |
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk, Gdk
from controller import Controller
from viewer import MainView
from gaphas import Canvas, GtkView
from gaphas.painter import DefaultPainter
def main():
builder = Gtk.Builder()
builder.add_from_file("AppWindow.glade")
graph_vie... |
import pymongo
connection = pymongo.MongoClient()
db = connection.drugdb
file_path = "/home/ubuntu/flaskapp/"
#Open the temporary file populated in parse_xml
f = open(file_path+"temp_out.txt")
doc = []
#populate the content of the file to a temporary dictionary.
for line in f:
temp_list = []
for word in line.s... |
# Generated by Django 3.1.7 on 2021-06-25 06:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hospital', '0023_auto_20210625_1006'),
]
operations = [
migrations.AlterField(
model_name='doctor',
name='mobile',
... |
__author__ = 'fernando.ormonde'
def maxsum(bets):
maximum = None
for i in range(len(bets)):
for j in range(i, len(bets)):
maximum = max(maximum, sum(bets[i:j+1]))
return maximum
print maxsum([20, -10, 3])
#testes
import unittest
class TestMaxSum(unittest.TestCase):
def test_... |
# The MIT License (MIT)
#
# Copyright (c) 2020 Cian Byrne for Robotics Masters Limited
#
# 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 ... |
#coding=utf-8
'''
test flask framework
by yan-bin-lin
'''
import os
from linebot.models import TextSendMessage,ImageSendMessage
from linebot import LineBotApi
from linebot.exceptions import LineBotApiError
from flask import Flask, request, Blueprint, url_for
from blueprint_pf.pf import PF,count_Chain
from help... |
from django.urls import path
from apps.cart.views import CartListView, CartAddView, CartDeleteView
app_name = 'cart'
urlpatterns = [
path('list/', CartListView.as_view(), name='list'),
path('add/', CartAddView.as_view(), name='add'),
path('delete/', CartDeleteView.as_view(), name='delete'),
] |
from datetime import datetime
from ems.datasets.case.case_set import CaseSet
from ems.generators.duration.duration import DurationGenerator
from ems.generators.location.location import LocationGenerator
from ems.generators.event.event_generator import EventGenerator
from ems.models.cases.random_case import RandomCas... |
from django import forms
# Selectores de genero
GENERO_CHOICES = (
('masculino', 'Masculino',),
('femenino', 'Femenino',),
)
#FORMATS = ['%Y-%m-%d', # '2006-10-25'
# '%m/%d/%Y', # '10/25/2006'
# '%m/%d/%y'] # '10/25/06'
FORMATS = ['%d/%m/%Y']
# Formulario de Paciente
class ... |
import json
# serializing JSON
data = {
"president": {
"name": "Zaphod Beeblebrox",
"species": "Betelgeusian"
}
}
with open("data_file_.json", "w") as write_file:
json.dump(data, write_file)
json_string = json.dumps(data)
json_string_2 = json.dumps(data)
# deserializing JSON
blackjack_... |
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
url = 'https://raw.githubusercontent.com/mathav95raj/Learning-Content/master/Phase%203%20-%202020%20(Summer)/Week%201%20(Mar%2028%20-%... |
t = int(raw_input())
for i in range(t):
s = raw_input()
pre = '#'
ans = 0
for c in s:
if (c != pre):
pre = c
ans += 1
if (s[-1] == '+'):
ans -= 1
print "Case #{}: {}".format(i + 1, ans)
|
from shape import IShape
class Circle(IShape):
def draw(self):
print("Inside Circle::draw() method.")
|
from twisted.internet import reactor as reactor
from twisted.internet.protocol import ClientFactory, Protocol
from twisted.internet.task import LoopingCall
from twisted.internet.error import CannotListenError
from twisted.internet.defer import DeferredQueue
import pickle
import pygame
import sys
from maps import Maps... |
import sys
import librosa as lbs
import numpy as np
from matplotlib import pyplot as plt
from scipy.io import wavfile
from scipy.signal import butter, lfilter
np.set_printoptions(threshold=sys.maxsize)
class NoiseReductionNew:
def bandpass(self, lowCut, highCut, fs, order=5):
nyq = 0.5 * fs
low... |
class Solution:
def sumSubseqWidths(self, a):
"""
:type A: List[int]
:rtype: int
"""
p = (10**9) + 7
l = len(a)
a.sort()
ans = 0
for i, v in enumerate(a):
left = 1 << i
right = 1 << (l-i-1)
ans += (left - right) * v
... |
from django.shortcuts import render, redirect, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from repository import models
import json, hashlib, time
# Create your views here.
def login(request):
if request.method == "GET":
return render(request, 'web/login.html')
elif request.meth... |
from typing import Callable, Dict, List, Optional, Sequence, Union
import numpy as np
from assertpy import assert_that
from bokeh import plotting
from bokeh.models import (
BasicTicker,
ColorBar,
ColumnDataSource,
HoverTool,
LinearColorMapper,
PrintfTickFormatter,
)
from bokeh.plotting import F... |
# DF model used for non-defended dataset
from keras.models import Sequential
from keras.layers import Conv1D, MaxPooling1D, BatchNormalization
from keras.layers.core import Activation, Flatten, Dense, Dropout
from keras.layers.advanced_activations import ELU
from keras.initializers import glorot_uniform
class D... |
from plotly.offline import plot
from plotly.graph_objs import *
from django.shortcuts import render
from django.http import HttpResponse
from django.utils.translation import gettext as _
no_margin = Margin(l=0, r=0, b=0, t=0, pad=0)
no_margin_with_padding = Margin(l=60, r=0, b=0, t=30, pad=0)
def plot_web(xys, titl... |
# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")
# https://app.codility.com/demo/results/trainingUHZUU8-3XB/
def solution(A):
# write your code in Python 3.6
right_map = dict()
for data in A:
if data in right_map:
right_map[data] = right_map... |
str = 'X-DSPAM-Confidence: 0.8475'
ipos = str.find(':')
piece = str[ipos+2:]
value = float(piece)
print(value)
|
#! /usr/bin/env python
"""
Usage:
report_slow.py [options]
report_slow.py [options] <query_tag> ...
report_slow.py [options] --days=<D> [<query_tag> ...]
report_slow.py [options] --start-date=<start_date> [<query_tag> ...]
report_slow.py [options] --start-date=<start_date> --end-date=<end_date> [<query_tag> .... |
import numpy as np
import pickle
import keras
from keras.models import Model , Sequential
from keras.layers import Dense, Input, Reshape, Lambda, Concatenate
from keras import backend as K
import tensorflow as tf
from keras import objectives , optimizers, callbacks
import matplotlib.pyplot as plt
import h5py
... |
# [SublimeLinter @python:3]
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, division, print_function, absolute_import
import threading
import win32api
import win32con
import win32gui
class drag_accept_files(object):
def __init__(self, wnd, callback):
super(drag_accept_files, self).__in... |
import numpy as np
import cv2 as cv
img = np.zeros((300,512,3), np.uint8)
cv.namedWindow('image')
def output(x):
print(x)
# to create a switch for enabling or disablying the trackbar alternator
switch = '0:OFF\n 1:ON'
cv.createTrackbar(switch, 'image', 0, 1, output)
# to create a track bar
cv.createTrackbar('B',... |
# -*- coding: utf-8 -*-
# @TIME : 2021/3/11 10:25
# @AUTHOR : Xu Bai
# @FILE : 5-1.创建并测试一个函数,读取它的__doc__属性,再检查类型
# @DESCRIPTION :
def factorial(n):
'''
:returns n!
'''
return 1 if n < 2 else n * factorial(n - 1)
print(factorial(42))
print(factorial.__doc__)
print(type(factorial))
|
import os, cv2
import numpy as np
from .utils import normalize
from typing import Tuple, Dict
def dividir_dataset_em_treinamento_e_teste(dataset: np.ndarray, divisao=(80,20)):
"""
Divisão representa a porcentagem entre conj. de treinamento e conj. de teste.
Ex: (80,20) representa 80% para treino e 20% para... |
'''
Sanjidah Wahid
PHYS 39906: Computational Physics Summer 2020
Assignment 4 - #401
Numerical Convergence of an Integral in Our Solar System
'''
#part (a)
import numpy as np
import matplotlib.pyplot as plt
def f(s):
return ((1-s)/s)**(1/2)
N_list = [100,200,400,800,1600,3200,6400,12800]
N_arra... |
import os
import shutil
sdir = './tmp_cut/'#来源
ddir = './tmp_classed/'#目的
path = os.listdir(sdir)
for i in path:
sourceFile = sdir+i
targetDir = ddir+i[i.find('_')+1]+'/'
targetFile = targetDir+i
if not os.path.exists(targetDir):
os.makedirs(targetDir)
shutil.copyfile(sourceFile, targetFi... |
import re
import queue
from difflib import SequenceMatcher
from requester import requester
from colors import red,green,end
from log import factory_logger,time
from urllib3.exceptions import ConnectTimeoutError
def chambering(url,strike,payload = None,type = None):
if "=" in url and "?" in url:
data = ... |
import hparams
from dataprocess.cleaners import englishStopWords
class XmlModel(object):
pass
class Comment(XmlModel):
def __init__(self, attributes):
self.id = attributes.get('Id')
self.PostTypeId = attributes.get('PostId')
self.AcceptedAnswerId = attributes.get('Score')
self.... |
"""Define and implement the callback interface."""
from .base import Callback, CallbackList, CallbackListFactory
from .checkpoint import ModelCheckpoint
from .logger import TxtLogger, StdoutLogger
|
import cv2
import pandas as pd
import numpy as np
import os
#get the image path
img_path = input("Enter the image file path including extension: ")
if(img_path == ""):
img_path = os.path.join(os.getcwd(), 'bg.jpg')
#read the image
img = cv2.imread(img_path)
clicked = False
r = g = b = xpos = ypos = 0
index=["color... |
from typing import List
class Solution:
def reverseWords(self, s: str) -> str:
i = 0
n = len(s)
words = ''
while i < n:
if s[i].isspace():
words += ' '
i += 1
continue
word = []
while i < n and n... |
from __future__ import print_function, division
import numpy as np
import dqrsl
from sklearn.utils import check_array
from numpy.linalg import matrix_rank
from numpy.linalg.linalg import LinAlgError
# WARNING: there is little-to-no validation of input in these functions,
# and crashes may be caused by inappropriate us... |
from kinyu.rimport.api import RemoteImporter
from subprocess import Popen, PIPE
import pytest
import json
SRCDB = 'files://tmp/unittests/test_main'
@pytest.fixture
def remote_importer():
ri = RemoteImporter(SRCDB)
return ri
def _run_test(args):
command = ["python", "-m", "kinyu.main", "--srcdb=" + SRC... |
"""Funtions for logging.
Copyright (C) 2022-2023 C-PAC Developers
This file is part of C-PAC.
C-PAC is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation, either version 3 of the License, or (at your
option) a... |
{
'name': "incomingorder_tracking",
'summary': """
Module is for tracking incoming order to generate GRN
""",
'description': """
Module is for tracking incoming order
""",
'author': "Creator",
'website': "",
'category': 'Uncategorized',
'version': '0.1',
'depends'... |
from page.base_page import Page
from selenium.webdriver.common.by import By
class Header(Page):
home_page = (By.XPATH, "(//ul[@class='yz-navmenu'])//li[1]")
material_resource = (By.XPATH, "(//ul[@class='yz-navmenu'])//li[2]")
design_center = (By.XPATH, "(//ul[@class='yz-navmenu'])//li[3]")
clothing_co... |
lst=[1,2,3,4,5,6,7,8,9]
element=int(input("enter a number"))
for i in lst:
for j in lst:
if(i+j==element):
print(i,j) |
import math
from functools import reduce
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import AnonymousUser
from django.contrib.sites import requests
from django.core.paginator import Paginator
from django.shortcuts import render, redirect... |
#Sydney Howard, showard
#Lab partners: Kasdan Bakos (kbakos), Jack Sampiere (jsampier)
#Also got help from: siqingy; approved by Kosbie
from tkinter import *
import random
import decimal
import string
####################################
# customize these functions
####################################
### CONTROL
de... |
import tortoise
class Music(tortoise.Model):
name = tortoise.fields.CharField(max_length=63, unique=True)
duration = tortoise.fields.FloatField()
path = tortoise.fields.CharField(max_length=127, unique=True)
genre = tortoise.fields.ForeignKeyField("app.Genre", null=True,
... |
def record(result):
#test = [{'message': 'average CPU freq 1800.001MHZ!', 'type': 'CPU性能测试', 'flag': True}, {'message': 'num: 0 CPU freq: 1800.001MHZ!', 'type': 'CPU性能测试', 'flag': True}, {'message': 'num: 1 CPU freq: 1800.001MHZ!', 'type': 'CPU性能测试', 'flag': True}, {'message': 'num: 2 CPU freq: 1800.001MHZ!', 'typ... |
# A. Winner
n = int(input())
scores = dict()
chrono = list()
for _ in range(n):
inp = input().split()
name = inp[0]
score = int(inp[1])
try:
scores[name] += score
except KeyError:
scores[name] = score
chrono.append([scores[name], name])
mx = max(scores.values())
candidate_winn... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-24 12:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pages', '0013_auto_20170714_0541'),
]
operations = [
migrations.AlterField(... |
# Import system modules
import arcpy, sys, math, os
from datetime import datetime
import time
from xml.dom.minidom import parse, parseString
#########################Variables################################
# Enter the location to your feature class that contains the features
# you wish to cache by.
# cacheFeatures =... |
#Programa
valor = 0
contador = 0
while contador < 7:
valor = valor + (valor / 2) + 4
if valor % 2 == 0:
print (valor)
else:
print (valor//2)
contador = contador + 1
#Resposta
4
10
9
16
26
41
64
|
# -*- coding: utf-8 -*-
"""
Created on Sat May 25 14:51:02 2019
@author: Suraj Pawar
"""
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, UpSampling2D
from tensorflow.keras.l... |
# THREE GOLD STARS
# Sudoku [http://en.wikipedia.org/wiki/Sudoku]
# is a logic puzzle where a game
# is defined by a partially filled
# 9 x 9 square of digits where each square
# contains one of the digits 1,2,3,4,5,6,7,8,9.
# For this question we will generalize
# and simplify the game.
# Define a procedure, check_s... |
import time
from lists import command_list
from lists import math_commands
print('Hello my name is AIM. How may I help you?')
while True:
Question = input('')
if Question == 'what does aim mean':
print('Aim means: Artificial Information Machine')
elif Question == 'hi':
print('Gr... |
# File: Dice.py
# Description: A game of war simulator
# Student's Name: Trace Tschida
# Student's UT EID: TRT729
# Course Name: CS 313E
# Unique Number: 51465
#
# Date Created: 9/24/2017
# Date Last Modified: 9/26/2017
import random
class Deck():
# initialize
def __init__(self):
# hold th... |
# -*- test-case-name: vumi.transports.mtech_ussd.tests.test_mtech_ussd -*-
from xml.etree import ElementTree as ET
from twisted.internet.defer import inlineCallbacks
from vumi import log
from vumi.message import TransportUserMessage
from vumi.transports.httprpc import HttpRpcTransport
from vumi.components.session im... |
import numpy as np
import math
import matplotlib.pyplot as plt
import csv
import sys
import scipy
from pyqtgraph.Qt import QtCore, QtGui
import pyqtgraph.opengl as gl
from scipy.spatial import ConvexHull
from mpl_toolkits.mplot3d.axes3d import Axes3D
import random
from sklearn.ensemble import IsolationForest
'''
Use: ... |
import os
import pickle
import matplotlib.pyplot as plt
import numpy as np
from settings import SAVE_PATH
RESULTS_FILENAME = 'results.pkl'
STATUS_FILENAME = 'status.txt'
def save_results(out_dir, results_dict, status=None):
results_path = os.path.join(SAVE_PATH, out_dir)
ensure_dir_path_exists(results_path... |
import os
from formatConverter import *
import timeSeriesFrame
extmap = {'.csv':1, '.txt':2, '.xls':3, '.sql':4}
dir = os.curdir
"""dir refers to current directory by default
recommended to change directory to point to a folder with only files desired to be read"""
def __doConv(file, id):
"""Conversion functi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def solve(cipher, N=1000000):
idx = 0
buf = [0]*10
cipher = int(cipher)
lastnum = ""
while 10 != buf.count(1):
idx += 1
if N < idx:
return "INSOMNIA"
lastnum = str(cipher*idx)
for ch in lastnum:
... |
# -*- coding: utf-8 -*-
import serial, threading, math, time, pygame, copy, numpy, itertools, binascii, struct
from sys import exit
from pygame.locals import *
from rdp import rdp
data_list_buffer = [] # shared item between window thread and lidar thread. Lidar stores data in the list and window thread uses it as in... |
from steemit.steemit import get_last_hash_comment, send_new_hash_comment
import json
from io import BytesIO
class RootHolder(object):
def __init__(self, api):
self.api = api
def get(self):
pass
def post(self, root):
pass
def create_empty(self):
root_object = dict(
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('textureDB', '0002_auto_20150727_1136'),
]
operations = [
migrations.AlterField(
model_name='realimage',
... |
#!/usr/bin/python
import os
import subprocess
import sys # package to accept input hostname/ipaddress
command= "ssh " + sys.argv[1] + " vmstat"
vm = subprocess.check_output("%s" %command, shell = True) # getting command output from remote host
vm1 = vm.splitlines()
vm2 = vm1[2].split()
sw_in = vm... |
import itertools
import logging
from typing import List, Dict, Any
from ray.remote_function import DEFAULT_REMOTE_FUNCTION_CPUS
import ray.ray_constants as ray_constants
logger = logging.getLogger(__name__)
MIN_PYARROW_VERSION = (4, 0, 1)
_VERSION_VALIDATED = False
def _check_pyarrow_version():
global _VERSION... |
from socketserver import ThreadingMixIn
from http.server import HTTPServer
from http.server import CGIHTTPRequestHandler
if __name__ == '__main__':
class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
pass
server_address = ('', 8000)
CGIHTTPRequestHandler.cgi_directories.append('/bin')
httpd ... |
import os
import flask
from flask import Flask, request, redirect, url_for
from flask import jsonify
import threading
import requests
import json
import uuid
# very coarse grained lock for atomic operation
writeLock = threading.Lock()
cacheLock = threading.Lock()
# directory mapping
directory = {}
# local fs
UPLOA... |
# -*- coding: utf-8 -*-
import json
import os
import re
import requests
STOCK_CODE_PATH = 'symbol.json'
def round_price_by_code(price, code):
"""
根据代码类型[股票,基金] 截取制定位数的价格
:param price: 证券价格
:param code: 证券代码
:return: str 截断后的价格的字符串表示
"""
if isinstance(price, str):
return price
... |
#-*- coding:UTF-8 -*-
import urllib2
import re
import threading
class MyThread(threading.Thread):
def __init__(self):
super(MyThread, self).__init__()
def run(self):
global file_handle
global g_mutex
global count
result = []
while True:
g_mutex.acquire()
count += 1
g_mutex.rele... |
class Solution:
def threeSum(self, nums):
solution = []
length = len(nums)-1
nums.sort()
for i in range(length-1):
if i > 0 and nums[i] == nums[i-1]:
continue
j = i+1
k = length
while j < k:... |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 21 10:34:22 2020
@author: yadav
"""
# code to generate two point correlation function, Kernels K,L and sampling from DPP (see section 2.4 page number 145) in review 'random matrix theory of quantum transport' by Beenakker
# The code uses eq.(50) in review 'random matrix ... |
from django import forms
from .models import Comment
class CommentForm(forms.Form):
author = forms.CharField()
message = forms.CharField()
def save(self, commit=True):
comment = Comment(author= self.cleaned_data['author'], message= self.cleaned_data['message'])
if commit:
commen... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
orm模块
2016_9_21
"""
import db
import time
from db import next_id
class Field(object):
def __init__(self, **kw):
self.name = kw.get('name', None)
self._default = kw.get('default', None)
self.primary_key = kw.get('primary_key', False)
... |
import img_similarity_comparison
if __name__ == '__main__':
print img_similarity_comparison.compare('http://image1.mop.com/vcms/project1/2012/9/9/10/55/201209091349748014080186572403.jpg', '1.jpg') |
def onehotnames():
onehotlist = ['age', 'balance', 'month', 'duration', 'campaign', 'previous',
'day_bin_(0, 7]', 'day_bin_(7, 14]', 'day_bin_(14, 21]',
'day_bin_(21, 28]', 'day_bin_(28, 31]', 'pdays_bin_(-2, -1]',
'pdays_bin_(-1, 0]', 'pdays_bin_(0, 400]', 'pdays_bin_(400, 900]',
'jo... |
#!/usr/bin/env python3
# RyanWaltersDev Jun 15 2021 -- TIY 7-5
# Initial prompt
prompt = "\n\nThank you for choosing Runway Theaters!"
prompt += "\n(Type 'veteran' to see our discount options for service members.)"
prompt += "\n(If you are finished, please enter 'quit')"
prompt += "\n\nEnter the age of the person that... |
import datetime
import os
from datetime import timedelta
from airflow import DAG
from airflow.providers.docker.operators.docker import DockerOperator
from airflow.sensors.python import PythonSensor
from airflow.models import Variable
default_args = {
"owner": "airflow",
'email_on_failure': True,
"retries"... |
import shutil
import os
currDir = os.getcwd()
print(currDir)
shutil.unpack_archive("unzip_me_for_instructions.zip", "", "zip")
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.