text stringlengths 8 6.05M |
|---|
from __future__ import division
import sys
import subprocess
import glob, os
## Author: Spencer Caplan, University of Pennsylvania
## Contact: spcaplan@sas.upenn.edu
outputFileNamesWithWordID = False
printDebugStatements = True
testFilesRun = True
trainFilesRun = True
def accessDictEntry(dictToCheck... |
#!/usr/bin/env python
"""
Implementation of Binary Search in Python using both
iterative and recursive approach.
"""
from typing import List, Union
def binSearch(arr: List[int], elem: int) -> bool:
first = 0
last = len(arr) - 1
found = False
while first <= last and not found:
middle = (first... |
import os
import sys
import subprocess
import shutil
sys.path.insert(0, 'scripts')
sys.path.insert(0, os.path.join("tools", "families"))
import fam
import experiments as exp
import ete3
def get_tree(ale_file):
for line in open(ale_file):
if (";" in line):
return line
return None
def get_leaves(tree_file... |
from operator import add, mul, sub, truediv
def arithmetic(a, b, operator):
ops = {'add': add, 'subtract': sub, 'multiply': mul, 'divide': truediv}
return ops[operator](a, b)
|
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
#@
#@ Converts single the single solid, containting all the silicon detectors [output_file_name],
#@ into the true array of silicon detectors [output_file_name]
#@ Usage:
#@ python conver_silicon.py
#@
#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
... |
# -*- coding:utf-8 -*-
#
# Author: Muyang Chen
# Date: 2020-08-26
import os
import config
from util import PrintLog, FileController
from valid_proxy_inspector import VaildProxyInspector
from proxy_crawler import Crawler
if __name__ == '__main__':
base_path = os.path.dirname(__file__)
proxy_file = os.path.joi... |
import pytest
@pytest.fixture
def mg_tag_2():
return 2
@pytest.fixture
def tree_sentences_text_with_difficult_punctuation():
return """\nNew Toyota Corolla LE 2007, Air Toyota ^Conditioning, *Leather seaters, $.
\nAlso Available in Different Colours.
\nBeware Om Fraudsters,, Please See What You Want... |
from django.shortcuts import render, redirect, reverse
# Create your views here.
import stripe as stripes
stripes.api_key = "pk_test_tkj9QAmsgb3rQkJMZH1iommg00WAdK86DL"
def index(request):
return render(request, 'index.html')
def charge(request, *args, **kwargs):
amount = 10
if request.method == 'POST':
pri... |
import numpy as np
import winnow
import readData as rd
TEN_PERCENT=10.0/100.0
TWENTY_PERCENT=20.0/100.0
PERCENT_OF_DATA=100/100
#this function takes in filename to read data from
# splits the data to D1, D2 and D3
# return the number of mistakes made with margin and without margin
def driver(trainfileName,testFileNam... |
#IACMI_parser.py
# Version Notes #
# Version: 4.0
# Developmetn Goal: Smartly import each "chunk" of rheology
# data belonging to an individual rheology experiment into its own DF
# Libraries
import pandas as pd
import numpy as np
# Global Variables
DIRECTORY = '/Users/malcolmdavidson/Documents/Code/ODI/IACMI/Shear... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.svm import SVC
from sklearn.neural_network import MLPClassifier
from sklearn.metrics import confusion_matrix, classification_report, r2_score
from sklearn.preprocessing import StandardScaler, LabelEncoder
from sklearn.model_selec... |
import cv2
import cv2.aruco
import numpy as np
import sys
# import pygame
import time
import serial
from threading import Thread
ser1 = serial.Serial('/dev/ttyACM0', 9600)
ser2 = serial.Serial('/dev/ttyACM1', 9600)
# alpha-100 beta-150
def direction(img, top_left, top_right, centre, ids):
x1 = top_left[0]
y1... |
from core.actors.messages import GAME_TAKE_TURN
class TakeTurnMessageBuilder:
def __init__(self, available_turns, game_state):
self.available_turns = available_turns
self.game_state = game_state
def build(self):
return {
'msg': GAME_TAKE_TURN,
'payload': {
... |
"""@package docstring
Provides the web request handlers.
"""
import os, datetime, re, simplejson
import urllib, base64, uuid
import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.api import users
from google.appengine.api.urlfetch import... |
# This file is part of beets.
#
# 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,
# distribu... |
dimensions = [x for x in raw_input("Enter: ").split(',')]
dim1 = int(dimensions[0])
dim2 = int(dimensions[1])
grand_row = []
for i in range(0, dim1):
row = []
for j in range(0, dim2):
row.append(j * i)
grand_row.append(row)
for row in grand_row:
print row
|
from django.contrib.auth.models import User, Group
from rest_framework import serializers
from django.contrib.auth import authenticate
from rest_framework.authtoken.models import Token
from django.utils.translation import ugettext_lazy as _
class UserLoginSerializer(serializers.Serializer):
username = serializers.... |
import json
class Movie:
def __init__(self, title ="", genre="", running_time=0, cast = []):
self.title = title
self.genre = genre
self.running_time = running_time
self.cast = cast
def add_cast (self, cast_to_add = {}):
if "name" in cast_to_add and "age" in cast_to_ad... |
#!/usr/bin/env python
import pickle
import io
from lab_defs import teaching_length
from lab_mc import experiments, tutorials, null_experiment
experiments["LVT"] = tutorials["LVT"]
from print_student import get_styles, swansea_logo
from assign_students import get_students, match_students
from loadstore import load_pa... |
#!/usr/bin/env python3
'''
Script to download Pb-Pb train output from AliEn.
python download_data.py -p LHC18q
On hiccup:
- ssh to hiccupds
- start a screen session
- enter alidock, then `alienv enter AliRoot/latest`, then get token
- python download_data.py -c LHC18q.yaml
Note that if token expires or ot... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'Grupo37'
from flask import Flask, render_template
from flask.ext.googlemaps import GoogleMaps
from flask.ext.googlemaps import Map
import totwitter
import twitter
import io
import json
app = Flask(__name__)
GoogleMaps(app)
searchkey = '#OjalaUnDiezEnSD' #tema a... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 26 21:28:55 2018
@author: zacholivier
Association rule mining
In this notebook, you'll implement the basic pairwise association rule mining
algorithm.
To keep the implementation simple, you will apply your implementation to
a simplified dataset... |
1.登录 + 文件下载
用户必须登录才能下载
用户是否登录应该记录在服务器
并且用户可以自己选择 上传 还是 下载
2.用socket server实现上面的题 |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import os
from collections import defaultdict
from textwrap import dedent
import pytest
from pants.backend.go import target_type_rules
from pants.back... |
import os
import tempfile
import unittest
from worker.file_util import gzip_file, gzip_string, remove_path, tar_gzip_directory, un_gzip_stream, un_gzip_string, un_tar_directory
class FileUtilTest(unittest.TestCase):
def test_tar_has_files(self):
dir = os.path.join(os.path.dirname(os.path.dirname(__file__... |
def reverse(str):
res = ''
for i in str:
res = i + res
return res
s = "Jarvis"
print("The original string is : ", s)
print("The reversed string using extended slice operator is : ", reverse(s))
|
"""xxx
Revision ID: 519e5b696ae4
Revises: 628fb686363
Create Date: 2015-11-21 23:38:06.202680
"""
# revision identifiers, used by Alembic.
revision = '519e5b696ae4'
down_revision = '628fb686363'
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
def upgrade():
### commands aut... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-04-09 15:45:19
# @Author : Fallen (xdd043@qq.com)
# @Link : https://github.com/fallencrasher/python-learning
# @Version : $Id$
#文件
'''
文件操作:
1.打开文件
2.对文件句柄进行操作
3.关闭文件
报错原因:
UnicodeDecodeError: 创建文件时使用的编码方式和打开文件的解码方式对不上
SyntaxError: 一般就是windows 路径上的 '... |
"""Treadmill / Active Directory (Windows) integration."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import click
from treadmill import context
from treadmill import zknamespace as z
from treadmil... |
#! python3
# _*_ coding: utf-8 _*_
from PyQt5.QtWebEngineWidgets import QWebEngineView |
from tkinter import *
def button_clicked():
print("I got clicked")
new_text = input.get()
my_label.config(text=new_text)
window = Tk()
window.title("My First GUI Program")
window.minsize(width=500, height = 300)
window.config(padx=20, pady=20)
#Label
my_label = Label(text="I Am a Label", font=("Arial",... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/9/27 7:44
# @Author : Jason
# @Site :
# @File : python_test.py
# @Software: PyCharm
import pandas as pd
import numpy as np
data = [
{'name': 'Joe', 'state': 'NY', 'age': 18},
{'name': 'Jane', 'state': 'KY', 'age': 19, 'hobby': 'Minecr... |
# encoding: utf-8
from tastypie.utils.dict import * |
from flask import Flask, url_for, render_template, request, redirect, flash
from flask_sqlalchemy import SQLAlchemy
import pymysql
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] ='mysql+pymysql://root:@127.0.0.1:3306/test?charset=utf8'
#配置flask配置对象中键:SQLALCHEMY_COMMIT_TEARDOWN,设置为True,应用会自动在每次请求结束后提交数据库... |
import turtle
def draw_shapes():
window = turtle.Screen()
window.bgcolor("pink")
draw_square("square","purple",2)
draw_circle("circle", "blue", 2)
draw_triangle("triangle", "red", 3)
window.exitonclick()
def create_turtle(shape, color, speed):
newTurtle = turtle.Turtle()
newTur... |
from pytest import mark
import allure
data = [('hello', 'world'),
('hello', ''),
('123', 'world')]
ddt = {
'argnames':'name,description',
'argvalues':[('hello', 'world'),
('hello', ''),
('123', 'world')],
'ids': ['general test', 'no description test', 'test with digits in ... |
import functools
import pytest
def decor(func):
@functools.wraps(func)
def inner(arg, x='Farewell!'):
new_arg=x
x=arg*3
return func(new_arg, x)
return inner
def F_F(arg, x='Hello!'):
print(x)
return(arg)
print(F_F(33))
print('----------')
print(dec... |
import sys
from . import fake_pyzz as pyzz
from . import ltl_parser
from . import build_monitor
from pyaig import *
def build_base_aiger( vinst ):
aig = vinst.N.aig
for n, w in vinst.symbols.iteritems():
if aig.name_has_po(n):
continue
aig.create_po( w.get_f(), n )
is_init ... |
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda
import matplotlib.pyplot as plt
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print('Using {} device'.format(device))
training_data = datasets.CIFA... |
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the plusMinus function below.
def plusMinus(arr):
pos, neg, zero = 0, 0 , 0
for i in range(0, len(arr)):
if arr[i] > 0 :
pos +=1
elif arr[i] < 0 :
neg += 1
else :
zer... |
#!/usr/bin/env python3
import logging
from flask import Flask, render_template
from flask_ask import Ask, statement, question, session
app = Flask(__name__)
ask = Ask(app, '/')
logging.getLogger('flask_ask').setLevel(logging.DEBUG)
@ask.launch
def new_query():
welcome_msg = render_template('welcome')
retu... |
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class AnyTests(TranspileTestCase):
def test_any(self):
self.assertCodeExecution("print(any([None, True, False]))")
def test_any_true(self):
self.assertCodeExecution("print(any([1,True,3]))")
def test_any_false(self):
... |
import math
area = float(input("Informe o tamanho da área a ser pintada em m²: "))
cobertura = (area/6)
coberturaTotal = cobertura * 1.1
latasTinta = math.ceil(coberturaTotal/18)
galoesTinta = math.ceil(coberturaTotal/3.6)
print(f"Valor em latas de 18l: R${latasTinta*80:.2f}")
print(f"Valor em galões de 3,6l... |
import webapp2
from webapp2_extras import jinja2
from google.appengine.api import users
from google.appengine.ext import ndb
from model.libroLiterario import libroLiterario
class EliminarlibroLiterarioHandler(webapp2.RequestHandler):
def get(self):
user = users.get_current_user()
if user:
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Refer to https://leetcode.com/discuss/857/constant-space-solution
class Solution(object):
def singleNumber(self, nums):
once = 0
twice = 0
third = 0
for num in nums:
twice |= once & num
once ^= num
... |
"""{{ project_name }} URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
"""
from pathlib import Path
# Django imports
from django.conf.urls import include
from django.urls import path, re_path
from django.contrib... |
test_case = int(input())
for _ in range(test_case):
n = int(input())
print(2 if n == 2 else (n & 1))
|
import copy
import argparse
from multiprocessing import Pool
from functools import partial
nextCells = []
mrow = list()
mcolumn = list()
def main():
# allows me to user argparse as inputs
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', required=True)
parser.add_argument("-o",... |
from leetcode import TreeNode, test, new_tree
def min_camara_cover(root: TreeNode) -> int:
result = 0
def lrd(node: TreeNode) -> int:
nonlocal result
if not node:
return 1
left, right = lrd(node.left), lrd(node.right)
if left == 0 or right == 0:
result ... |
from kafka import KafkaConsumer
from src import string_to_list, webhook_post_request, get_kafka_data
kafka_data = get_kafka_data()
consumer = KafkaConsumer(kafka_data["kafka_topic"], bootstrap_servers=[kafka_data["kafka_port"]])
if __name__ == "__main__":
for data in consumer:
decoded_data = data.value.de... |
from django.conf.urls import url
from blog.views import index as blog_index
from blog.views import post as blog_post
from blog.views import tag as blog_tag
from blog.views import postList as blog_postList
from blog.views import emailPost as blog_emailPost
from blog.views import userReg as blog_userReg
from blog.views i... |
from dataclasses import dataclass
@dataclass
class Position:
y: int
x: int
def __add__(self, other):
return Position(y=self.y + other.y, x=self.x + other.x)
def neighbours(self):
return [self + o for o in _neighbours]
def __hash__(self):
return hash((self.y, self.x))... |
"""Here we will test assumptions about the data."""
|
"""
An interface to the NLNOG ring.
"""
# ABOUT
# =====
# ringtools - A generic module for running commands on nodes of the NLNOG
# ring. More information about the ring: U{https://ring.nlnog.net}
#
# source code: U{https://github.com/NLNOG/py-ring}
#
# AUTHOR
# ======
# Teun Vink - teun@teun.tv
__all__ = ['except... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def get_act(name):
if name == 'relu':
return nn.ReLU(inplace=True)
elif name == 'leaky_relu':
return nn.LeakyReLU(negative_slope=0.2, inplace=True)
elif name == 'silu':
return nn.SiLU(inplace=True)
elif name == ... |
from django.shortcuts import render
from django.utils import timezone
from django.views import generic
from .models import Story
class IndexView(generic.ListView):
template_name = 'iamgrey/story_list.html'
context_object_name = 'latest_story_list'
latest_story = Story.objects.latest('date_published')
... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.experimental.kotlin.register import rules as all_kotlin_rules
from pants.backend.kotlin.lint.ktlint import rules as ktlint_rules
from pants.backend.kotlin.lint.ktlint im... |
# -*- coding: utf-8 -*-
from django.conf.urls import patterns, url, include
from ceiling.views import CeilingView
urlpatterns = patterns('',
url('^$', CeilingView.as_view(), name='ceiling'),
url('^api/$', CeilingView.as_view(), name='ceiling'),
)
|
import pytest
from pcos_runrex.algo.menarche import MENARCHE_AGE, AGE_MENARCHE, MENARCHE_GRADE, GRADE_MENARCHE
@pytest.mark.parametrize(('text', 'value'), [
('menarche at age 13', 13),
('menses irregular since onset at age 13', 13),
])
def test_menarche_numeric_age(text, value):
m = MENARCHE_AGE.matchgro... |
import collections
def solution(ranks):
y = dict(collections.Counter(ranks))
counts = 0
for key in y.keys():
if(key+1 in y):
counts += y[key]
print(str(counts))
return counts
# write your code in Python 3.6
solution([3, 4, 3, 0, 2, 2, 3, 0, 0])
solution([4, 2, 0])
solution([4... |
__all__ = [
'MilestoneEditJob',
]
from async_messages import messages
from limpyd import fields
from limpyd_jobs import STATUSES
from gim.core.models import Milestone
from gim.core.ghpool import ApiError
from .base import DjangoModelJob
class MilestoneJob(DjangoModelJob):
"""
Abstract job model for jo... |
def char_in_text(char,text):
num_of_char = 0
length = len(text)
i = 0
while i < (length - 1):
if text[i] == char:
num_of_char = num_of_char + 1
i = i + 1
return num_of_char
character = input("Enter Character: ")
text = input("Enter text: ")
print("Th character %s appea... |
from django.http import HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response,render
from django.http import HttpResponseRedirect
import django.db.utils
from .forms import UploadTorrentForm
import bencode
from models import Torrent, Client
#from models import Utilities ... |
def bar_triang(*args):
return map(lambda a: round(sum(a) / 3.0, 4), zip(*args))
|
"""
公共方法类:
封装正向逆向断言方法
"""
import allure
from config import BASE_PATH
from page.page_in import PageIn
from page.page_login import PageLogin
from tools.get_driver import GetDriver
from tools.get_log import GetLog
log = GetLog.get_log()
class Until:
def __init__(self):
self.login = PageIn.get_page_login... |
from bs4 import BeautifulSoup
import requests
def decodeWebPage():
url = 'https://www.nytimes.com/'
response = requests.get(url)
html = BeautifulSoup(response.text, features="html.parser")
print("The following are a list of articles shown on 'The New York Times' website:" + '\n')
articles = ""
... |
from LeerSensores import Sensores
if __name__ == "__main__":
x=Sensores()
x.distanciaMetodo()
|
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'signup/',views.signup_view),
url(r'login/',views.LoginView.as_view()),
url(r'verifyuser',views.VerifyUser.as_view()),
url(r'verifypass',views.VerifyPass.as_view()),
url(r'ajax$',views.AjaxView.as_view()),
url(r'ajax_vi... |
#!/usr/bin/env python3
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
import sys
sys.path.append('../aardvark')
import subprocess as sp
import numpy as np
from glob import glob
import cv2
from tqdm import tqdm
import tensorflow as tf
from tensorflow.python.framework import meta_graph
from mold import Scaling as Mol... |
from django.shortcuts import render
from rest_framework.response import Response
from .gateway_caller import ctrl_device, set_group_status
from rest_framework.decorators import api_view
GW_IDS = ['HKG-01-0190838-004', 'HKG-01-0190838-003', 'hg20150601', 'HKG-01-0190838-001', 'HKG-01-0190838-005']
GWAPI_HOSTS = {
G... |
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm
from django.contrib.auth.models import User
from django import forms
class UserSignInForm(AuthenticationForm):
username = forms.CharField(widget=forms.TextInput(
attrs={
'class': 'form-control',
'placeholder'... |
from django.shortcuts import render, redirect, HttpResponse
from .models import User
from django.contrib import messages
# Create your views here.
def landing(request):
return render(request, 'loginReg/landing.html')
def index(request):
return render(request, 'loginReg/index.html')
def process(request):
... |
#coding=utf-8
from bs4 import BeautifulSoup
import bs4
import urllib2
import urllib
import re
class QSBK(object):
"""Q糗事百科的爬虫类"""
def __init__(self):
super(QSBK, self).__init__()
self.currentPage = 1
self.jokes = []
self.currentIndex = 0
def getOneJoke(self):
'''
获得一条段子
'''
if self.currentIndex <... |
import time
import requests
from datetime import datetime
import smtplib
MY_LAT = "25.211549"
MY_LONG = "85.514542"
my_email = "jalltrades12@gmail.com"
password = "@#Jack098"
response = requests.get(url="http://api.open-notify.org/iss-now.json")
response.raise_for_status()
data = response.json()
iss_latitude = flo... |
import numbers
from typing import Any, Dict, List, Literal, Optional, Sequence, Tuple, Union
import numpy as np
import torch
from PIL import Image, ImageEnhance, ImageOps
try:
import accimage
except ImportError:
accimage = None
@torch.jit.unused
def _is_pil_image(img: Any) -> bool:
if accimage is not No... |
import csv
import sys
import re
def main():
# check input lenght
if len(sys.argv) != 3:
print('Usage: python dna.py data.csv sequence.txt')
return
# reading dan and loading RAM
dna = ''
with open(sys.argv[2], "r") as file_dna:
dna = file_dna.read().strip('\n'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
print('train classyfiler stage 4')
import os
import sys
import csv
import numpy as np
import pickle
from PIL import Image
import tensorflow as tf
import tensorflow_ae_base
from tensorflow_ae_base import *
import tensorflow_util
import myutil... |
import win32con
import win32gui
from common.contants import choice_question_detail_dir, img_dir
from page.base.basepage import BasePage
class Choice_Question_Detail(BasePage):
def choice_question(self,subject_name,option_list):
'''
題目標題\選項
'''
self._params["subject_name"] = subjec... |
# Enter script code
keyboard.send_key("<backspace>")
keyboard.send_key("<home>")
keyboard.send_keys("help(")
keyboard.send_key("<end>")
keyboard.send_key(")")
keyboard.send_key("<enter>") |
import os
import pdb
def unique_output_filename(folder, format_string, maxval=100000):
"""
writes out data which we don't want to be overwritten
folder : str
The folder to write to
format_string : str
Something which can be formated using format_string.format(i)
maxval : int
... |
# Generated by Django 3.1.5 on 2021-03-06 20:13
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('hackathon', '0002_auto_20210306_1959'),
]
operations = [
migrations.CreateModel(
name='BonusIma... |
'''
Created on July 19, 2010
@author: Jason Huang
'''
#!/usr/bin/env python
import pymongo
import os
import simplejson
import MongoEncoder.MongoEncoder
from Map.ProcessTripHandler import GetTrips
from Map.ProcessTripHandler import ShowNewTrips
from Map.ProcessTripHandler import ShowHotTrips
from Map.P... |
#!/usr/bin/env python
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import A... |
from turtle import Turtle
class Scoreboard(Turtle):
def __init__(self):
super().__init__()
self.count = 0
self.hideturtle()
self.color("white")
self.up()
self.goto(-50,270)
self.down()
self.write(f"Scoreboad : {self.count}",align="left", font=("Arial"... |
#
# Dota info server in Python
# Binds REP socket to tcp://*:5555
# Expects b"get_new_msg" from client, replies with the message for the client
# to push to telegram, OR b"NONE" if there is no message.
#
# Expected implementation:
# * reads from SQS of all matches and filters them according to a static list
#... |
#!/usr/bin/env python3
import sys
from util.aoc import file_to_day
from util.input import load_data
def main(test=False):
dotdata = []
instructions = []
data = load_data(file_to_day(__file__), test)
for idx, line in enumerate(data):
if line == "":
dotdata = data[:idx]
... |
import csv
import sys
from defs import hier
def summarize(fn, nfn):
f = csv.reader(file(fn, "rb"))
fo = open(nfn, "wb")
header = f.next()
cams = Node("Root")
for l in f:
for x in zip(header, l):
if x in hier:
#print hier[x][0]
cams.inc_child(*hie... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2018-10-05 13:20
from __future__ import unicode_literals
import django.db.models.deletion
import django.db.models.manager
import django_extensions.db.fields
import elections.managers
from django.db import migrations, models
class Migration(migrations.Migration... |
# Author Yinsen Miao
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_context("poster")
dat = pd.read_pickle("../data/cleandata2.pkl")
dat_municode = dat[['PARID', 'MUNICODE']].drop_duplicates()['MUNICODE'].value_counts()
municodes = [str(code) for code in dat_munico... |
from setuptools import setup
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name="pycolate",
version="0.0.42",
author="Jack Harrington",
author_email="jackjharrington@icloud.com",
description="Generates site percolation data and illustrations.",
pa... |
""" File: cover_list_code.py
Author: Abraham Aruguete
Purpose: This is a script designed to test each of the lines in list_insert.py"""
from list_insert import *
def main():
node1 = ListNode( (-8, -7) )
node2 = ListNode ( (2, 5) )
node3 = ListNode ( (-9, -7))
sorted_list_insert(None, node2)
... |
from grid import *
from particle import Particle
from utils import *
from setting import *
from math import sin, cos, radians
import random
from scipy import stats
import numpy as np
MARKER_ANGLE_SIGMA = 10
MARKER_DIST_SIGMA = 0.5
def motion_update(particles, odom):
""" Particle filter motion update
... |
from django.db import models
# Create your models here.
class Inventory(models.Model):
"""docstring for Inventory"""
name = models.CharField(max_length=100,default='Something')
image = models.ImageField(null=True, default='No-image-available.png')
description = models.CharField(max_length=100, default='Describe S... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import argparse
import datetime
from src.analyse import Analyse
from src.data import Vir
parser = argparse.ArgumentParser()
parser.add_argument("--date",
help="date in format YYYY-MM-DD (not needed if it's today)")
parser.add_argument("--infections",
... |
import sys
import os
import fastjet as fj
import pyhepmc_ng
import tqdm
def main():
input_file="$HOME/data/jetscape/test_out.hepmc"
if len(sys.argv) > 1:
input_file = sys.argv[1]
input_file = os.path.expandvars(input_file)
print('[i] reading from:', input_file)
# input = pyhepmc_ng.ReaderAsciiHepMC2(input_... |
import pandas as pd
import numpy as np
import os
from scipy import stats
from scipy.stats import norm
from sqlalchemy import create_engine
import logging
import pickle
logger = logging.getLogger(__name__)
def prediction(model, city, bedrooms, bathrooms, floors, waterfront, condition, sqft_basement, yr_built, yr_renov... |
import logging
from microstrategy_api.task_proc.memoize_class import MemoizeClass
from microstrategy_api.task_proc.object_type import ObjectType, ObjectTypeIDDict, ObjectSubType, ObjectSubTypeIDDict
class MetadataObjectNonMemo(object):
"""
Object encapsulating a generic metadata object on MicroStrategy
... |
import glob
import pandas as pd
from models.song import Song
from models.artist import Artist
from models.songPlay import SongPlay
from models.time import Time
from models.user import User
import numpy as np
from bd import Base,session,engine
from sqlalchemy import exc
#Función que obtiene el nombre de todos los archi... |
with open("TChiWZAll.dat") as f:
content = f.readlines()
# you may also want to remove whitespace characters like `\n` at the end of each line
content = [x.strip() for x in content]
for a in content:
fileName=a.split("/")[8]
print fileName
|
from arduino_graphing import DataHandler
class Logger():
def __init__(self, beer_logs, fridge_logs, time_logs):
self.beer_logs=beer_logs
self.fridge_logs=fridge_logs
self.time_logs=time_logs
beer_logs = []
fridge_logs = []
time_logs = [0]
beer_logs.appe... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.