text stringlengths 38 1.54M |
|---|
filename = "guest.txt"
user_name = input("Please enter your name: ")
with open(filename, "w") as fileobject:
fileobject.write(f"{user_name}")
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Support module generated by PAGE version 4.23a
# in conjunction with Tcl version 8.6
# Jul 03, 2019 01:16:17 PM -03 platform: Windows NT
import sys
import controllers.Gestos as ctrl
try:
import Tkinter as tk
except ImportError:
import tki... |
# Kimberly Vo collab with stephen chew, julie nguyen, megan Van Rafelghem
# kv3nw.... ssc6ae, jqn5xk. mtv2mn
instructor_list = []
import urllib.request
def instructors(department):
'''
returns an alphabetized list of professors that teach in the department without repeating
:param department: which depart... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 13 19:07:20 2019
@author: jorgeagr
"""
import numpy as np
def perceptron(x, w):
'''
x: Data matrix in column form. Rows are attributes, columns are instances.
w: Column vector, each row is weight of attribute.
'''
y = np.dot(w.... |
def prefSum(a):
return functools.reduce(lambda i,x : i + [i[-1] +x], a[1:], [a[0]])
#functools.reduce(function, iterable[, initializer])
|
# Generated by Django 1.11.6 on 2017-11-14 19:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("zerver", "0118_defaultstreamgroup_description"),
]
operations = [
migrations.AddField(
model_name="userprofile",
nam... |
from generateplayer import Player
from .models import Team
pointguard = Player(1)
shootingguard = Player(2)
smallforward = Player(3)
powerforward = Player(4)
center = Player(5)
newTeam = Team()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2017-04-13 10:24
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('location', '0001_initial'),
]
operations = [
... |
print ("BAJAS")
dam2 = ["Sergio", "Xabi","Xabi", "Maria", "Alexander", "Carlos" ,"Juan" ,"Imanol", "Pedro" ,"Uxue", "Javier", "Iker", "Carlos", "Xabi", "Alejandra", "Carolina","Iñaki", "Asier","Maria"]
print (dam2)
nom = input("Nombre a eliminar: ")
nom= nom.capitalize()
print ("El nombres aparece " + str(dam2.count... |
'''Exercise 16.2. Write a boolean function called is_after that takes two Time objects, t1 and t2,
and returns True if t1 follows t2 chronologically and False otherwise. Challenge: don’t use an if
statement.
'''
import time
import datetime
class Time(object):
def __init__(self, year=2000, month=1, day... |
def euler028(diagonal):
'''Number spiral diagonals
Starting with the number 1 and moving to the right in a clockwise direction a
5 by 5 spiral is formed as follows:
21 22 23 24 25
20 7 8 9 10
19 6 1 2 11
18 5 4 3 12
17 16 15 14 13
It can be verified that the sum of t... |
from keras.preprocessing import image
from keras.models import load_model
import numpy as np
import matplotlib.pyplot as plt
# test_dir = r'.\newDataSet\test\0\00000.jpg'
test_dir = r'.\pic\10.jpg'
model = load_model('newModel.h5')
img = image.load_img(test_dir, target_size=(48, 48))
x = np.expand_dims(img, axis=0)
y ... |
from django.db import models
from django.conf import settings
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
# Create your models here.
class profile(models.Model):
user = models.OneToOneField(User, on_delete= models.CASCADE)
n... |
# -----------------------------------------------------------------------------
# Copyright (c) 2012 - 2018, Anaconda, Inc. and Intake contributors
# All rights reserved.
#
# The full license is in the LICENSE file, distributed with this software.
# ----------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
"""
LSTM网络结构与LOSS函数。
@author:chenli0830(李辰)
@source:https://github.com/happynoom/DeepTrade
"""
import tensorflow as tf
from tensorflow.contrib import rnn
import os
from tensorflow.contrib.rnn import DropoutWrapper
from tensorflow.python.ops.init_ops import glorot_uniform_initializ... |
import os
import torch
from transformers import AdamW, get_linear_schedule_with_warmup
class BaseModel():
def __init__(self, opt):
self.net=None
self.opt = opt
self.gpu_ids = opt.gpu_ids
self.isTrain = opt.isTrain
self.device = torch.device('cuda:{}'.format(self.gpu_ids[0])... |
"""Represents an entire atomic snapshot (including descriptor/target data)."""
from os.path import join
import numpy as np
from mala.common.json_serializable import JSONSerializable
class Snapshot(JSONSerializable):
"""
Represents a snapshot on a hard drive.
A snapshot consists of numpy arrays for inpu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import __future__
import sys
ip = "./challenge_sample_input"
op = "./challenge_sample_output"
print("===" * 30)
print("SAMPLE INPUT:")
print("===" * 30)
print(open(ip, 'r').read())
sys.stdin = open(ip, 'r')
print("===" * 30)
print("SAMPLE OUTPUT:")
print("===" * 30)
print... |
a=int(input("digite um numero: "))
for i in range(a,0,-1):
print("*"*i)
for i in range(1,a+1,1):
print("*"*i) |
# -*- coding: UTF-8 -*-
import random
# 随机生成五位数的验证码 验证码由字母或数字组成
def auth_code():
code = ''
for i in range(5):
number = str(random.randrange(1, 10))
alphabet = chr(random.randrange(65, 91))
code += random.choice([number,alphabet])
return code
print(auth_code())
|
import wit
import json
def main(interval=2):
i=0
total_fucks=0
while i<interval:
access_token = '5OOPLQECDO32JWXIAN5TAPE7JZ7J4UHX'
wit.init()
response = wit.voice_query_auto(access_token)
parse_for_fucks = json.loads(response)
print(response)
total_fucks = total_fucks +len(parse_for_fucks["outcomes"][... |
# Generated by Django 2.1.2 on 2019-05-16 07:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('report', '0042_dailycreditcardfile_grand_total'),
]
operations = [
migrations.AddField(
model_name='dailycreditcardfile',
... |
# Author = 'Vincent FUNG'
# Create = '2017/09/26'
import datetime
import os
import sqlite3
import time
# try:
from .logger import Logger
# except ModuleNotFoundError:
# from http_websocket.logger import Logger
LOG_FILE = os.path.join(os.path.expanduser(
'~'), 'CrashParser', 'log', 'CrashParser.log')
LOG = L... |
def division(n1, n2): # try-except-else-finally
r = -1
try:
r = n1 / n2
except Exception as e:
print(e)
else:
print('No exception detected!')
finally:
print('I will be executed anyways')
return r
def main_exept():
print('Exceptions Handling M1')
print('... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def generateTrees(self, n: int) -> List[TreeNode]:
if n == 0: return []
if n == 1: return [TreeNode(1)]
def gener... |
# Generated by Django 3.2.6 on 2021-08-28 08:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('main', '0004_auto_20210826_1448'),
]
operations = [
migrations.CreateModel(
name='RequestForm',
fields=[
... |
from django.conf.urls import url
from . import views
urlpatterns = [
# ex: /ssapp/
url(r'^$', views.index, name='index'),
# ex: /ssapp/family/5/
url(r'^family/(?P<family_id>[0-9]+)/$', views.family, name='family'),
# ex: /ssapp/person/5/
url(r'^person/(?P<person_id>[0-9]+)/$', views.person, name=... |
# Django settings for satchmo project.
# This is a recommended base setting for further customization
import os
DIRNAME = os.path.dirname(__file__)
DJANGO_PROJECT = 'store'
DJANGO_SETTINGS_MODULE = 'store.settings'
ADMINS = (
('Yanchenko Igor', 'yanchenko.igor@gmail.com'), # tuple (name, email) - import... |
import graphene
from graphql import GraphQLError
from backend.likes.models import Like as LikeModel
from backend.posts.models import Post as PostModel
from backend.comments.models import Comment as CommentModel
from backend.likes.schemas.queries import LikeNode
class LikePost(graphene.Mutation):
"""
Adds a li... |
from io import BytesIO
from PIL import Image
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.core.files.base import ContentFile
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.urls import reverse
from .models import TravelRecord, TravelImage
fro... |
from keras.models import Model
from keras.regularizers import l2
from keras.optimizers import SGD, Adam
from keras.layers import *
import tensorflow as tf
import keras.backend as K
import numpy as np
def FCN(input_shape=None, weight_decay=0., batch_momentum=0.9, classes=1):
img_input = Input(shape=input_shape)
... |
import inspect
class Action_Error(RuntimeError):
def __init__(self, msg):
RuntimeError.__init__(self, msg)
class Action_Invokation_Error(Action_Error):
def __init__(self, msg):
Action_Error.__init__(self, msg)
_supported_action_additional_argument_types = []
def get_all_supported_action_... |
import sys
import csv
import utilities
import numpy
from datetime import datetime
from datetime import timedelta
date_format = "%Y-%m-%d"
start_semester = datetime.strptime('2018-09-17', date_format)
def main():
if len(sys.argv) != 3:
print("Numbers of parameter are wrong")
else:
csv_reader =... |
import math
import torch
import random
from torch import nn
from torch.autograd import Variable
import torch.nn.functional as F
from utils import lengths2mask
class Encoder(nn.Module):
RNN_TYPES = {'lstm': nn.LSTM, 'gru': nn.GRU, 'rnn': nn.RNN}
def __init__(self, args, embedding):
super(Encoder, self)... |
from django.contrib import admin
from django.urls import path, include
from Report import views
urlpatterns = [
path('report/', views.report, name='report')
] |
#import sys,os
#BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # __file__获取执行文件相对路径,整行为取上一级的上一级目录
#sys.path.append(BASE_DIR)
import numpy as np
import cv2
import time
import datetime
import tracktarget as tar
def trackmove(frame):
frame=cv2.GaussianBlur(frame,(5,5),0)
gray = cv2.cvtCol... |
import logging
from agents import dp, greedy
from decks.deck_factory import Deck
from env import SetteMezzoEnv, Player
logger = logging.getLogger('sette-mezzo')
depth = 4
limit = 4
deck = Deck()
logger.info('Deck %s', deck)
players = {Player(0): dp.DpAgent(),
Player(1, limit=limit): greedy.BookmakerAgent... |
# Generated by Django 3.0.4 on 2020-04-02 10:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('covidecapi', '0005_auto_20200402_1047'),
]
operations = [
migrations.AlterField(
model_name='casocovid',
name='activ... |
import unittest
from tasks.JsonConverter.Encoder import to_json
from json import dumps
class TestJsonEncoder(unittest.TestCase):
def test_list(self):
list_to_json = [74, True, False, None, [1, 2], {"key": 4}]
self.assertTrue(to_json(list_to_json) == dumps(list_to_json))
def test_dict(self):... |
from flask_wtf import FlaskForm
from wtforms import validators, SelectField, SubmitField, TextAreaField
from wtforms.widgets import TextArea
from wtforms.fields.html5 import DateField
from wtforms.validators import DataRequired
import datetime
class gradePerformanceform(FlaskForm):
lesson_id = SelectField(label='... |
# Example 3
class Person:
# attributes
__name = "" # use a double underscore for private attribute
__address = "" # use a double underscore for private attribute
# methods
def __init__(self, giveName, givenAddress):
self.__name = giveName
self.__address = givenAddress
... |
class job:
def __init__(self, name, value = 0):
self.name = name
self.value = value
self.categorie_list = []
class categorie:
def __init__(self, name):
self.name = name
self.amount = []
self.date = []
self.paid = []
self.paid_date = [... |
from introspective_api import generics
from introspective_api.response import ApiResponse
from dynamic_widgets.editor import models as local_models
from dynamic_widgets.editor.api.dynamic_content import serializers as model_serializers
from dynamic_widgets.settings import dynamic_widgets_settings
api_endpoint = dynam... |
# Generated by Django 3.2 on 2021-04-23 16:15
from django.db import migrations
from django.contrib.auth.hashers import make_password
import random
import decimal
def populate_db(apps, schema_editor):
User = apps.get_model('catalogue', 'User')
admin = User(username="admin", password=make_password("admin"), ema... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 2 19:37:59 2018
@author: deepak
"""
from sklearn.preprocessing import MinMaxScaler
from flask import jsonify, make_response, request, current_app
import numpy as np
from flask import Flask
import keras
from keras.models import model_from_json
app... |
import sims4.log
from contextlib import contextmanager
logger = sims4.log.Logger('Profiler')
if __profile__:
import _profiler
begin_scope = _profiler.begin_scope
end_scope = _profiler.end_scope
enable_profiler = _profiler.begin
disable_profiler = _profiler.end
flush = _profiler.flush
else... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""--- Day 1: Not Quite Lisp ---
Santa was hoping for a white Christmas, but his weather machine's "snow"
function is powered by stars, and he's fresh out! To save Christmas, he needs
you to collect fifty stars by December 25th.
Collect stars by helping Santa solve puzzle... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
url(r'^$', 'play.views.webplay', name='web_play'),
url(r'^admin/', include(admin.site.urls)),
(r'^download/pins/', 'pins.views.download_pins'),
url(r'^traffic/$', '... |
#!/usr/bin/python
"""Report authorization information."""
import datetime as dt
import argparse
import json
import wrapper
import os
_KEY = "->"
_NA = "n/a"
_DENY = "denied"
def _new_key(user, mac):
"""Create a key."""
return "{}{}{}".format(user, _KEY, mac)
def _file(day_offset, auth_info, logs):
"""R... |
from PIL import Image
from core.NST import NST
from core.preprocessor import Preprocessor
##### hyperparameters #####
no_iter = 50
alpha = 0.2
beta = 0.8
def setup_nst() -> NST:
NST.initialize('imagenet-vgg-verydeep-19.mat')
NST.set_cost_weights(alpha=alpha, beta=beta)
def nst_handler(c_image: Image, s_imag... |
import os
import sys
import glob
VALID_TAGS = tuple('natural caption blank_line attribute source_header block_header code anchor image_link'.split() +
'block_start block_end code_start code_end natural_start natural_end'.split() +
['heading{}'.format(i) for i in range(1, 7)])
INC... |
import cv2
import mediapipe as mp
import time
import math
import numpy as np
class poseDetector():
def __init__(self, mode = False, upBody =False, smooth = True, detectionCon= 0.5, trackCon = 0.5):
self.mode = mode
self.upBody = upBody
self.smooth = smooth
self.detectionCon... |
from unittest import TestCase
from task_1 import quick_sort
""" Only look at the cases with numbers. Strings, Tuples etc. can be ignored.
Cases that have to be tested are:
- Empty list - should return a empty list
- single values - should return a list with the same single value
- unsorted values - sh... |
import argparse
import re
import os
import wget
def main():
p = argparse.ArgumentParser(description="Script using to looking for extended files")
p.add_argument("--log_name", help="name files where is extended files", dest="log_name", required=True)
p.add_argument("--directory", help="name folder... |
# 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, Version 2.0 (the
# "License"); you may not u... |
#!/usr/bin/env python
"""
iTunes Graph Parser
Parses an iTunes library XML file and generates a JSON file
for use in the D3.js JavaScript library.
Example Track info:
{
'Album': 'Nirvana',
'Persistent ID': 'A50FE1436726815C',
'Track Number': 4,
'Location': 'file://localhost/Us... |
# -*- encoding: utf-8 -*-
from setuptools import setup
from setuptools import find_packages
from os.path import join, dirname
import threebot_worker as app
def long_description():
try:
return open(join(dirname(__file__), 'README.md')).read()
except IOError:
return "LONG_DESCRIPTION Error"
se... |
from flask_script import Manager
from flask import url_for
from fooApp.app import app
manager = Manager(app)
app.config['DEBUG'] = True # Ensure debugger will load.
if __name__ == '__main__':
manager.run() |
print("Enter an integer for X and Y to get the Harmonic and Arithmetic mean")
x = int(input("Enter x: "))
y = int(input("Enter y: "))
h = 2/(1/x + 1/y)
a = (x+y)/2
print(f"\nArithmetic mean: {a}")
print(f"Harmonic mean: {h}") |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat May 16 04:14:45 2020
@author: antonio
UTILS
"""
import numpy as np
from random import randrange
def dist_left(snake_head, thing, dist_wall_left, wall_right):
return (snake_head[0]-thing[0]) if (snake_head[0]-thing[0]) > 0 \
else (dist_w... |
# _*_ conding: utf8 _*_
import random
total = 1000000
doors = [1, 2, 3]
wins = 0
for x in range(total):
binggo = random.choice(doors)
hoost = random.choice(doors)
if hoost == binggo:
wins += 1
print "wins gailv for stay: %.5f%%" % (wins/float(total)*100)
wins_2 = 0
for x in range(total):
b... |
# -*- coding: utf-8 -*-
#导入包
from appium import webdriver
#前置代码
desired_caps = {}
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '5.1'
desired_caps['deviceName'] = '192.168.56.101:5555'
desired_caps['appPackage'] = 'com.android.settings'
desired_caps['appActivity'] = '.Settings'
desired_caps... |
#!/usr/bin/python
f = open('in.txt')
i = 0
for line in f:
i += 1
if i == 1:
continue
cur = int(line)
if cur == 0:
print 'Case #' + str(i-1) + ': INSOMNIA'
continue
ps = 'Case #' + str(i-1) + ': '
mul = 1
total = cur
found = ''
while 1:
s = str(total... |
from django.shortcuts import render
from django.http import Http404
from rest_framework.generics import RetrieveUpdateDestroyAPIView, ListCreateAPIView, ListAPIView, RetrieveAPIView, GenericAPIView
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
f... |
#!/usr/bin/python
#coding=utf-8
import sys, time
from sensetimebi_productstests.Sharedscript.ShareedSSH import SSH
from sensetimebi_productstests.Sharedscript.logger import Logger
if __name__ == '__main__':
host_ip = '10.9.40.150'
# print(host_ip)
ssh_name = 'root'
ssh_pwd = 'BI_SensePassXS#'
# pr... |
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
mail_content = "Hello, This is a simple mail. There is only text, no attachments are there The mail is sent using Python SMTP library. Thank You"
#The mail addresses and password
sender_address = 'dummy.upgrad@gmail.com'
... |
from sanic import Blueprint
from apis.users.UsersController import users_bp
users_group = Blueprint.group(users_bp, url_prefix='api/v1/users')
|
import os
import pygame
import GameplayConstants
class Sounds:
def __init__(self):
#explosies
soundfolder = os.path.join(os.path.dirname(__file__), 'sounds')
self.explosions = []
filenames = ["explosion_" + str(nr) + ".wav" for nr in range(10)]
for filename in filenames:
... |
import pytest
from yandex_testing_lesson import Rectangle
def test_1():
with pytest.raises(TypeError):
Rectangle('1', 12)
def test_2():
with pytest.raises(TypeError):
Rectangle([], 12)
def test_3():
with pytest.raises(TypeError):
Rectangle(12, '1')
def test_4():
with ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, os, fileinput
""" A light xml parser application which is good for transforming HunToken's xml based output into plain lines,
which is necesseraly for input data form of HunPoS (part-of-speech tagging) and HunMorph (morphological analysis).
It is embedded in ... |
# -*- coding: latin-1 -*-
import heapq as hq
from graphsearch import GraphSearch
class BestFirstSearch(GraphSearch):
def insert_border(self, node):
hq.heappush(self.border, (self.f(node), node))
def remove_border(self):
(_, node) = hq.heappop(self.border)
return node
def... |
from __future__ import division
import os, re
import string
from datetime import datetime
import logging
import logging.handlers
from collections import MutableMapping
from itertools import islice
from functools import wraps, partial
LOGDIR = os.path.join(os.path.dirname(__file__), 'logs')
def removehandlers(logger)... |
n1=eval(input())
n2=n1
for i in range(n1):
for j in range(n1-i):
print('*',end="")
print()
|
"""Ingest the files kindly sent to me by poker"""
from __future__ import print_function
import glob
import re
import datetime
import subprocess
import os
import pytz
from pyiem.util import noaaport_text, get_dbconn
from pyiem.nws.product import TextProduct
BAD_CHARS = r"[^\n\r\001\003a-zA-Z0-9:\(\)\%\.,\s\*\-\?\|/><&... |
from app import Application
from tkinter import *
#Driver
def main():
root = Tk()
root.title("Stock Tracker")
root.geometry("340x540")
app = Application(root)
root.mainloop()
main()
|
from turtle import *
from random import randint
from sys import exit
door = randint(0,1)
def getPosition():
x,y = position()
h = heading()
return (int(round(x,1)),int(round(y,1)),int(round(h/10))*10)
def isDoorOpened():
return door
def drawRoom():
forward(300)
left(90)
forward(200)
r... |
from isis.table_view import Table_View
from isis.data_model.table import Table
from isis.dialog import Dialog
from decimal import Decimal
from pymongo import MongoClient
from dict import Dict
from PySide.QtGui import QVBoxLayout, QMenu
from PySide.QtCore import Qt
d1 = MongoClient('mongodb://comercialpicazo.com', doc... |
#!/usr/bin/env python
year = int(input("Enter a year: "))
if year % 100 == 0:
if year % 4 == 0:
print 'True'
else:
print 'False'
elif year % 4 == 0:
print 'True'
else:
print 'False'
|
import turtle
t1 = turtle.Turtle()
length = float(input("Please Enter A Length for all sides: "))
for i in range(3):
t1.left(120)
t1.forward(length)
t1.forward(150)
for i in range(4):
t1.left(90)
t1.forward(length)
t1.forward(150)
for i in range(5):
t1.left(72)
t1.forward(length)
t1.forward(2... |
import datetime
def date_range(start, end, delta=None):
if delta is None:
delta = datetime.timedelta(days=1)
while True:
if start > end:
raise StopIteration
yield start
start = start + delta
def main():
start = datetime.date(1901, 1, 1)
end = datetime.da... |
__author__ = 'Zaheeb Shamsi'
import json
import requests
def load_json():
with open('ec2.json') as env:
return json.load(env)
class ScheduleEC2:
@staticmethod
def schedule_ec2(ec2json):
"""
:param ec2json: The json from the user.
:return: response from ... |
from scripts.statement import Statement
def test_generate_monthly_statement():
statementMonth0 = Statement(42, 0.04)
assert statementMonth0.getMinPmt(42, 0.04) == 1.68
def test_print_statement():
statementMonth0 = Statement(42, 0.04)
assert statementMonth0.printStatement(
42, 1.68) == "Balan... |
import socket
import datetime
def Main():
listeningPort = input("Enter listening port: ")
print("starting...")
mySocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
mySocket.bind(('0.0.0.0', int(listeningPort)))
data = ""
while data != 'q':
data = mySo... |
import re
def hash(banks):
return '-'.join(str(s) for s in banks)
def shuffle(banks):
i = banks.index(max(banks))
l = len(banks)
to_distribute = banks[i]
banks[i] = 0
for j in range(to_distribute):
banks[(1 + i + j) % l] += 1
return banks
def repeat(banks):
seen = {hash(ban... |
from game.Event import Event
from utils.beauty_print import *
from utils.common import line, prim_opt, valid_number, clear, is_integer
from game.DataStructure import DataStructure
from game.Board import Board
from game.Logger import Logger
from entity.livingbeing.person.player.Player import Player
class PlayerIM(Pl... |
from pylab import *
from core import *
import numpy
import simuPOP as sim
from simuPOP.utils import *
import sys
import time
class Model(Simulation):
""" Class that provides facilities to run simulations in simuPOP with an island model
:param Gen: number of generations over 1 simulation
:param loci: ... |
import re
phoneNumber = "415-555-1011"
phonenumberRegEx = re.compile(r"\d\d\d")
# 1st way with findAll method, this will return all matches
print(phonenumberRegEx.findall(phoneNumber))
# 2nd way with search, this returns a match object on which we call the group method. This will just return the first match.
matchObjec... |
"""
Haardt, F., & Madau, P. 2012, ApJ, 746, 125
Notes
-----
"""
import os
import numpy as np
from ares.physics.Constants import h_p, c, erg_per_ev
_input = os.getenv('ARES') + '/input/hm12'
pars_ml = \
{
'a': 6.9e-3,
'b': 0.14,
'c': 2.2,
'd': 5.29,
}
pars_err = \
{
'a': 0.001,
'b': 0.21,
'c': 0.14,
'd': 0... |
# -*- coding: utf-8 -*-
import re
import json
import scrapy
from scrapy_redis.spiders import RedisSpider
from ..items import Hospital99Item
#
class InfoSpider(RedisSpider):
name = 'hos99_slave'
redis_key = 'hos99_spider:slave8_urls'
def __init__(self, *args, **kwargs):
domain = kwargs.pop('domain'... |
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import math
# import temporal data
death_df = pd.read_csv('./time_series_2019-ncov-Deaths.csv')
confirmed_df = pd.read_csv('./time_series_2019-ncov-Confirmed.csv')
recovered_df = pd.read_csv('./time_seri... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# https://github.com/lxyu/kindle-clippings
import collections
import msgpack
import os
BOUNDARY = u"==========\r\n"
DATA_FILE = u"clips.msgpack"
OUTPUT_DIR = u"output"
if not os.path.exists(OUTPUT_DIR):
os.makedirs(OUTPUT_DIR)
def get_sections(filename):
with o... |
#!/usr/bin/env python
"""reducer.py"""
import sys,string
previous_citing_id = "-"
current_state = "-"
for line in sys.stdin:
citing,cited,state = line.split("\t")
if not previous_citing_id or previous_citing_id != citing:
previous_citing_id = citing
current_state = state
elif citing == p... |
'''NXOS Implementation for Msdp unconfigconfig triggers'''
# Genie Libs
from genie.libs.sdk.libs.utils.mapping import Mapping
from genie.libs.sdk.triggers.unconfigconfig.unconfigconfig import TriggerUnconfigConfig
# import pyats
from pyats.utils.objects import Not, NotExists
# Which key to exclude for Msdp Ops compa... |
# find the first fib number with 1000 digits
def count_digits(input):
input = int(input)
digits = 0
if input == 0:
return 1
while input:
digits+=1
input //= 10
return digits
f1 = 1
f2 = 1
digits = 0
count = 2
while digits!=1000:
term = f1 + f2
digits = count... |
#------------------------------------------------------
# import
#------------------------------------------------------
import os
import argparse
import codecs
import time
import imghdr
import numpy as np
import cv2
print("opencv : ",cv2.__version__)
from model_wrapper import *
#---------------------------------------... |
import os
import csv
import re
import datetime
# from urlparse import urlparse
from urllib.parse import urlparse
from seed.data_importer.tasks import save_raw_data, map_data, match_buildings
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.http import JsonResponse... |
import warnings
import pandas
import itertools
import bokeh.palettes
from bokeh.plotting import figure
from bokeh.io import show, curdoc
from bokeh.layouts import column, row, widgetbox
from bokeh.models.widgets import MultiSelect, TextInput, Dropdown
from bokeh.models import ColumnDataSource, CustomJS, HoverTool
from... |
# Title: Extended Euclidean Algorithm
# Creator: Austin Akerley
# Date Created: 11/26/2019
# Last Editor: Austin Akerley
# Date Last Edited: 02/02/2020
# Associated Book Page Nuber: 16
# INPUT(s) -
# x - type: int, desc: one of the inputs for the extended euclidean algorithm, example: 12345
# y - type: int, desc: one ... |
__author__ = 'Крымов Иван'
# Задание-1: Решите задачу (дублированную ниже):
# Дана ведомость расчета заработной платы (файл "data/workers").
# Рассчитайте зарплату всех работников, зная что они получат полный оклад,
# если отработают норму часов. Если же они отработали меньше нормы,
# то их ЗП уменьшается пропорцион... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.