text stringlengths 38 1.54M |
|---|
# -*- coding=utf-8
'''
Created on 2016年9月23日
牌桌麻将牌的管理器
包括:
1)发牌
2)牌桌上的出牌
3)宝牌
发牌说明:
发牌涉及到好牌点
@author: zhaol
'''
from majiang2.table_tile.test.table_tile_test import MTableTileTest
from poker.entity.dao import daobase
from freetime.util import log as ftlog
import json
class MTableTileTestLongNet(MTableTileTest):
... |
import random
from p1 import (
get_number_of_repeated_columns,
get_number_of_repeated_rows,
get_trace,
)
from p5 import gen_diag_recursively
def gen_latin_matrix(n):
output_list = []
for i in range(n):
numbers = list(range(1, n + 1))
random.shuffle(numbers)
output_list.app... |
import os
import shutil
from _datetime import datetime
from PIL import Image
class ImageOrganizer:
def folder_path_from_photo_date(self, file):
date = self.photo_shooting_date(file)
return date.strftime('%Y') + '/' + date.strftime('%Y-%m-%d')
def photo_shooting_date(self, file):
... |
from api_app import Api, App
from merge_rule import *
# r_xxx_yyy_zzz
# d: default, c: common, u: unique, l: limit
r_d = MergeRule()
r_c = common_rule()
r_u = unique_rule()
r_c_u = chain_rule(r_c, r_u)
r_l_1 = limit_rule(1)
r_c_l1 = chain_rule(r_c,r_l_1)
def apps():
flowfilters = [
# app_zjxsp(),
... |
import shutil
import pdb
from operator import add
import euroki
# Example Front module
# ---------------------------------------------------------------------
er = euroki.euroKi('io-faceplate') # Give the pj a name
er.drawOutline(8) # 8 HP module
er.drawMountingHoles()
er.drawRails()
er.pot = 7.1 # Alpha 9mm pots
er.... |
from __future__ import absolute_import, division, print_function, unicode_literals
import matplotlib.pyplot as plt
import tensorflow as tf
train_dataset_fp = "hu2222.csv"
column_names = ['Hu1', 'Hu2', 'Hu3', 'Hu4', 'Hu5', 'Hu6', 'Hu7', 'Class']
feature_names = column_names[:-1]
label_name = column_names[-1]
prin... |
def frequency_count(input_string):
frequency = {}
for letter in input_string:
try:
frequency[letter] = frequency[letter] + 1
except KeyError:
frequency[letter] = 1
return frequency
print( frequency_count("CoE 161") )
|
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from torch.nn.utils import spectral_norm
from torch.nn.init import xavier_uniform_
import torch.nn.init as init
def init_weights(m):
if type(m) == nn.Linear or type(m) == nn.Conv2d:
x... |
# https://atcoder.jp/contests/abc032/tasks/abc032_b
s = input()
k = int(input())
st = set()
for i in range(len(s) - k + 1):
st.add(s[i:i+k])
ans = len(st)
print(ans)
|
""" NLPIA Chapter 2 Section 2.1 Code Listings and Snippets """
import pandas as pd
sentence = "Thomas Jefferson began building Monticello at the age of twenty-six."
sentence.split()
# ['Thomas', 'Jefferson', 'began', 'building', 'Monticello', 'at', 'the', 'age', 'of', 'twenty-six.']
# As you can see, this simple Pyt... |
## Python Script to pull turnstile data from http://web.mta.info/developers/turnstile.html
## The purpose of the this script extract the data off the web and combine in to one file
## This complete file can be cleaned and used for data exploration and forcasting
## Template for extracting data taken from:
## https://... |
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def isSymmetric(self, root: Optional[TreeNode]) -> bool:
queue = [root]
while queue:
values = ... |
from rudra.utils.validation import check_field_exists, check_url_alive
import pytest
def test_check_field_exists():
input_data = ['a', 'b', 'c']
missing = check_field_exists(input_data, ['a', 'd'])
assert 'd' in missing
missing = check_field_exists(input_data, ['a', 'c'])
assert not missing
in... |
from __future__ import division
import json
import pycountry
from django.shortcuts import render
from django.db.models import Sum
from models import *
from auth.decorators import loginRequired
from common.utils import getHttpResponse as HttpResponse
from common.utils import getUnixTimeMillisec
from common.decorators ... |
# Rohde & Schwarz instruments
# Just add each specialization as needed
from .hmc804x import *
from .ngx200 import *
# USB Vendor ID
# There may be better sources but this one was a good start on USB Vendor IDs
# https://devicehunt.com/all-usb-vendors
USB_VID = '0AAD'
# Dictionary of product/model ID (PID) and model ... |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 31 11:56:04 2020
@author: ariel
"""
from sklearn.datasets import load_iris
import pandas as pd
import seaborn as sns
iris_dataset = load_iris()
iris_dataframe = pd.DataFrame(iris_dataset['data'], columns = iris_dataset.feature_names)
iris_dataframe['target'... |
def solve(a, b):
r = int(a + b)
t = 1
while r > 0:
r -= t
t += 2
return r == 0
a, b = input().split()
if solve(a, b):
print("Yes")
else:
print("No")
|
#!/usr/bin/python3
import argparse
import rsa
from ECC import ECC
from Point import Point
import binascii
import time
def create_arguments():
"""Create command line argument for this program.
"""
parser = argparse.ArgumentParser(
description='Public Key based Cryptosystem'
)
parser.add_arg... |
#! /usr/bin/env python
import rospy
# For the state machine
from StateMachine import Smach
# To graph the state machine diagram
# import pygraphviz
# ROS messages and services
from std_msgs.msg import String, Int32
# from eagle_one_test.msg import State
# Initialize the state machine and variables
smach = Smac... |
#! /usr/bin/env python2
class Cls(object):
def __init__(self, value):
self.value = value
x = [Cls(value) for value in range(10)]
# y = x[:]
y = list(x)
y.pop()
y[0].value = 42
print [datum.value for datum in x]
print [datum.value for datum in y]
|
from __future__ import print_function, division
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_is_fitted
from sklearn.preprocessing import OneHotEncoder, LabelEncoder
from sklearn.ensemble import BaggingRegressor
from sklearn.externals import six
import numpy as np... |
import math
import sys
Obstacles = []
class Point:
def __init__(self, x_coord, y_coord, thetha_coord):
self.x_coord = x_coord
self.y_coord = y_coord
self.thetha_coord = thetha_coord
# For simplicity, the obstacle has the thetha occupied in [0,2*pi].
# Thus, i... |
import boto3
import os
import json
from botocore.exceptions import ClientError
from boto3.dynamodb.conditions import Key, Attr
from decimal import Decimal
dynamodb = boto3.resource('dynamodb', region_name='us-west-2')
lambdaClient = boto3.client('lambda')
class RentCalculator:
def __init__(self):
self.tab... |
from . import views
from django.urls import re_path
urlpatterns=[
re_path(r'^user_ask/$',views.user_ask,name='user_ask'),
#下面是用户收藏的路由
re_path(r'^user_love/$',views.user_love,name='user_love'),
#下面是用户评论的路由
re_path(r'^user_comment/$',views.user_comment,name='user_comment'),
#下面是在用户中心删除收藏... |
from flask import Flask
import tensorflow as tf
import cv2
app = Flask(__name__)
@app.route("/")
def main():
return "App is working"
if __name__ == "__main__":
app.run(host="0.0.0.0") |
rule edena_overlapping:
"""
Modified:
2020-08-17 10:05:36 Added '_se' in tool name. Should lead to deprecation in old code. TODO: Add '_se' everywhere.
Doc:
https://oit.ua.edu/wp-content/uploads/2016/10/edena_referencemanual120926.pdf
Note:
Reads provided to edena should have sa... |
"""
Desafio 074
Problema: Crie um programa que vai gerar 5 números aleatórios e colocar em uma tupla.
Depois disso, mostre a listagem de números gerados e também indique o menor e
o maior valor que estão na tupla.
Resolução do problema:
"""
from random import randint
print('-' * 30 + f'\n{"SORTEIO... |
#https://leetcode.com/problems/tree-diameter/
#Time Complexity: O(V+E)
class Solution:
def treeDiameter(self, edges: List[List[int]]) -> int:
from collections import defaultdict
self.tree = defaultdict(list)
for u,v in edges:
self.tree[u].append(v)
self.tree[v].appen... |
import numpy as np # You can set an alias for the library you imported
from sklearn.datasets import load_iris
from sklearn import tree
'''
This imports is for visualizing the
decision tree later on
https://medium.com/@rnbrown/creating-and-visualizing-decision-trees-with-python-f8e8fa394176
https://github.com/... |
import ROOT as r
from ROOT import gROOT, TCanvas, TFile, TGraphErrors, SetOwnership, TVector3
import math, sys, optparse, array, copy, os
import gc, inspect, __main__
import numpy as np
runningfile = os.path.abspath(__file__)
WORKPATH = ''
for level in runningfile.split('/')[:-1]:
WORKPATH += level
WORKPATH... |
import bs4
import webbrowser
import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from download import down... |
from BaseUserAPITest import BaseUserAPITest
from opentera.db.models.TeraParticipantGroup import TeraParticipantGroup
from opentera.db.models.TeraParticipant import TeraParticipant
from opentera.db.models.TeraSession import TeraSession
import datetime
class UserQueryParticipantGroupTest(BaseUserAPITest):
test_endp... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = '太阳黑子活动折线图'
__author__ = 'zhangjingjun'
__mtime__ = '2017/11/3'
# ----------Dragon be here!----------
┏━┓ ┏━┓
┏━┛ ┻━━━━━━┛ ┻━━┓
┃ ━ ┃
┃ ━┳━┛ ┗━┳━ ┃
┃ ┻ ┃
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-06 17:58
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('web_configurations', '0015_auto_20171006_1257'),
]
operations = [
migrations.Remove... |
# -*- coding:utf8 -*-
# 作者 yanchunhuo
# 创建时间 2018/01/19 22:36
# github https://github.com/yanchunhuo
from base.web_ui.demoProject.web_ui_demoProject_client import WEB_UI_DemoProject_Client
from page_objects.web_ui.demoProject.pages.indexPage import IndexPage
from assertpy import assert_that
class TestIndex:
def set... |
import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDHarvester import DQMEDHarvester
# Control trigger
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
SUSY_HLT_HT200_alphaT0p51 = DQMEDAnalyzer('SUSY_HLT_alphaT',
trigSummary = cms.InputTag("hltTriggerSummaryAOD",'', 'HLT'), #to use with... |
from subprocess import Popen, TimeoutExpired, PIPE
import shlex
def run_cmd(args, input=None, timeout=10):
stdin = PIPE if input else None
with Popen(shlex.split(args), stdin=stdin, stdout=PIPE, stderr=PIPE,
encoding='utf-8') as proc:
try:
# proc.wait(timeout=10)
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayOpenPublicLabelUserQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayOpenPublicLabelUserQueryResponse, self).__init__()
self._label_ids = None
... |
from FOL.Formulae import Formulae
from FOL.Alphabet import l_inference
class Sequence:
def __init__(self, antecedent, succedent):
for formula in antecedent:
assert isinstance(formula, Formulae)
for formula in succedent:
assert isinstance(formula, Formulae)
self.ante... |
import os
from dotenv import load_dotenv
import event
import asyncio
from asgiref.sync import async_to_sync
def print_camion():
print("camion")
def print_something(something: str):
print(something)
event.connect("camion_registered", print_camion)
event.connect("camion_registered", print_something)
async def tri... |
from Base.Base import Base
from Page.UIElements import UIElements
class PersonPage(Base):
def __init__(self, driver):
Base.__init__(self, driver)
def get_shop_cart(self):
"""获取优惠券文本内容"""
# timeout给10秒 在取结果元素的时候,降低失败等待时间
return self.get_element(UIElements.person_shop_cart_id, t... |
#the module NLTK (Natural Language Toolkit) is used for natural language processing
import nltk
#In many languages, words appear in several inflected forms. For example, in English, the verb 'to walk'
#may appear as 'walk', 'walked', 'walks' or 'walking'. The base form, 'walk', that one might look up in
#a dictio... |
import sys
def test():
a = [21, 2]
res = largest_number(a)
print('===== {}'.format(res))
assert int(res) == 221
def is_greater_or_equal(num1, num2):
return int(str(num1) + str(num2)) >= int(str(num2) + str(num1))
def largest_number(a):
res = ""
while a:
max_num = 0
for ... |
#The code for G(a). Author:Alapan Das
import math as m
def primality(p):
count=1
for i in range(2,p):
if p%i!=0:
count=count*1
else:
count=count*0
break
return count
def factor(n):
l=[]
a=[]
for P in range(3,int(n/2)+1):
if pri... |
import matplotlib.pyplot as plt
#绘制点模型,定义文本框和箭头格式
#分支节点,boxstyle是样式,fc是不透明度
decisionNode = dict(boxstyle = "sawtooth", fc ="0.8")
#叶节点
leafNode = dict(boxstyle="round4",fc= "0.8")
arrow_args = dict(arrowstyle="<-")
#给createPlot子节点绘图添加注释。具体解释:nodeTxt:节点显示的内容;xy:起点位置;xycoords/xytext:坐标说明?;xytext:显示字符的位置
#va/ha:显示的位置?;bbo... |
class MyQueue:
def __init__(self):
self.stack_in = []
self.stack_out = []
def push(self, x: int) -> None:
self.stack_in.append(x)
def pop(self) -> int:
if self.empty():
return None
if self.stack_out:
return self.stack_out.pop()
else:
... |
import datetime
import threading
import Queue
import json
import os
import thread
from server_config import *
import database_handler
import hashlib
import time
def read_log_file(filename):
content = "Couldn't load log file"
try:
with open(filename, 'r') as thefile:
content = thefile.read(... |
sum, tmp = 0, 1
for i in range(1, 11):
tmp *= i
sum += tmp
print("运算结果是:{}".format(sum)) |
class 부모:
def __init__(self):
print("부모생성")
class 자식(부모):
def __init__(self):
print("자식생성") #자식생성을 출력한다
super().__init__() # super()를 이용해 부모클래스에 접근해서__init__()를 실행해 부모생성을 출력한다.
# super() 부모클래스르 명시적으로 호출할수있다
나 = 자식() # 자식()으로인해 자식 생성이 출력되고 super().__init__()로인해 부모생... |
import numpy as np
import ctypes
from scipy.optimize import minimize
from scipy.sparse import coo_matrix, csr_matrix, csc_matrix
import test_math
m = int(7e0)
n = int(15e0)
k = int(4e0)
lam = 2.5
w = 3.2
nthreads = 8
np.random.seed(123)
X = np.random.gamma(1,1, size=(m,n))
W = np.random.gamma(1,1, size=(m,n))
def g... |
key = "ICE"
m_1 = """Burning 'em, if you ain't quick and nimble
I go crazy when I hear a cymbal"""
#将2个字符按值进行XOR返回一个hex
def chr_XOR(a,b):
temp = hex(ord(a) ^ ord(b)).replace('0x','')
if len(temp) == 2:
return temp
else:
temp = "0" + temp
return temp
#利用一个字符串对一个另字符串进行按块XOR
... |
import pymongo
from pymongo import MongoClient
from pymongo.errors import AutoReconnect
from xml.dom.minidom import parseString
from xml.dom.minidom import parse
from lxml import etree
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
import pandas as pd
import os... |
#! /usr/bin/env python
import re
import os
import sys
import time
import threading
import commands
import pickle
from Bio import SeqIO
from argparse import ArgumentParser
sys.path.append("/hellogene/scgene01/user/chenjiehu/bin/recovery/module/")
import pipeline
__author__ = 'Qingyuan Zhang(zhangqingyuan@scgene.com)'
... |
import os, sys
from pprint import pprint
import GaussianRunPack
usage ='Usage; %s infile' % sys.argv[0]
try:
infilename = sys.argv[1]
except:
print (usage); sys.exit()
#if len(sys.argv)==3: option = sys.argv[2]
#For reading log file ####
#option = "eae homolumo"
#test_sdf = GaussianRunP... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#!!!!!------------------------------------!!!!!
# Execute this in "su", or it won't work
#!!!!!------------------------------------!!!!!
#<<<<<startInit>>>>>
#for Displaying; show some frames
import wx
#for GPIO(requiers sudo)
import RPi.GPIO as GPIO
#for showing movi... |
#libraries
import os
import sys
import json
import spotipy
import webbrowser
import spotipy.util as util
from json.decoder import JSONDecodeError
username = sys.argv[1]
scope = 'user-read-private user-read-playback-state user-modify-playback-state'
SPOTIPY_REDIRECT_URI
try:
token=util.prompt_for... |
#!/usr/bin/env python
# coding: utf-8
# In[12]:
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
import random
# In[6]:
# Generate 9 folds with random pairs of patients for cross validation
def get_folds(data):
keynames = list(data.... |
"""
By default the read() method returns the whole text, but you can also specify how many characters you want to return.
"""
#read a 3 characters from the file.
f = open("car.txt","rt")
print(f.read(3))
f.close()
#read a line frome the file.
f = open("car.txt")
print(f.readline()) #it gives first... |
from datetime import date
class Student:
def __init__(self,id,name,dob,classification):
self.__studentid = id
self.__name = name
self.__dob = dob
self.__class = classification
self.__age = 0
self.__register = ''
def get_age(self):
return self.__age
d... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jul 19 15:13:50 2019
# repair data for KES paper
# Purpose: get data from corpus
# | pure NPs | pure NPs + pure VBs |
# | syntactic NPs | syntactic NPs + cooccurred VBs |
# output:
l2_frequency(nounlistinFile) | 309,463 extracted terms
l2_frequency(... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------
# TheGroove360 / XBMC Plugin
# Canale
# ------------------------------------------------------------
import os
import re
import time
import urllib
import urlparse
from core import httptools
from core import config
from core import... |
# %%
from recognize.source.contours import findContours
from recognize.source.points import firstPoint, secondPoint, thirdPoint
import numpy as np
from math import acos, pi, sqrt
# %%
def findPoints(image):
"""提取三个特征点
1.通过调用contour.py中的findContours()来识别轮廓特征。\n
2.通过调用point.py中的firstPoint(), secondP... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.http import Request, FormRequest
from Scrapy_WDZJ.items import *
import datetime
from Scrapy_WDZJ.tools.strtools import *
import requests
from lxml import etree
import json
import math
import re
from scrapy.loader import ItemLoader
import time
import logging
class Pl... |
from math import log
def term_frequency(term, doc):
res = doc.count(term) / len(doc)
if not res :
return 0
return 1 + log(res)
def tf_idf(term, doc, idf):
return term_frequency(term, doc) * idf
def doc_len(doc):
return len(list(filter(lambda x: x != ' ', doc)))
def BM25(term, doc, idf, params=[2, 0.75], L=0)... |
# -*- coding: utf-8 -*-
# Copyright (c) 2013 Spotify AB
import unittest
from graphwalker import tgf
class TestTGF(unittest.TestCase):
data0 = """\
n0 Start
n1 v_a
n2 v_b
n3 v_c
#
n0 n1 e_zero
n1 n2 e_one
n2 n3 e_two
"""
def test_example_abz(self):
verts, edges = tgf.deserialize(self.data0)
... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""SuperBench CLI command handler."""
from pathlib import Path
from knack.util import CLIError
from omegaconf import OmegaConf
import superbench
from superbench.runner import SuperBenchRunner
from superbench.executor import SuperBenchExecutor
... |
from django.conf.urls import url
from django.views.generic import (YearArchiveView, MonthArchiveView,
DayArchiveView)
from django.views.decorators.cache import cache_page
from news.models import Story
from news.views import StoryDetailView, StoryListView
urlpatterns = [
url(r'^(?... |
#Write a program to implement the concept of class and object creation.
class Person:
age = 10
def greet(self):
print('Hello')
print(Person.age)
print(Person.greet)
print(Person.__doc__)
class Person:
age = 10
def greet(self):
print('Hello')
harry = Person()
print(Pers... |
import os
import sys
import json
import ast
import random
import time
import uuid
from urlparse import parse_qs, urlparse
if(os.path.isfile('last_record.txt') ):
f=open('last_record.txt','r')
var=f.read().split(',')
last_record=var[0]
counter=int(var[1])
numberofRecords=int(var[2])
f.close()
else... |
#! /usr/bin/env python2
"""
Demonstrates how to hide passwords in logging messages, based on a tip in https://stackoverflow.com/questions/48380452/mask-out-sensitive-information-in-python-log
"""
import re
import sys
import logging
class SensitiveFormatter(logging.Formatter):
regexp = re.compile('PASSW(?:OR)?D[... |
import matplotlib.pyplot as plt
slice_names = ["Python", "Java", "C#", "C"]
slice_sizes = [50, 90, 20, 14]
color_swatches = plt.pie(
slice_sizes,
labels=slice_names,
autopct="%1.1f%%",
explode=[0.1, 0, 0, 0],
shadow=True,
colors=["#ff0000", "#00ff00", "#0000FF", "#FFFF00"]
)[0]
plt.legend(col... |
from django.urls import path
from .views import *
app_name = 'core'
urlpatterns = [
path('movies/', MovieList.as_view(), name='MovieList'),
path('movie/<int:pk>', MovieDetail.as_view(), name='MovieDetail'),
path('movie/<int:movie_id>/vote', CreateVote.as_view(), name='CreateVote'),
path('movie/<int:mov... |
from django.contrib import admin
from django.conf import settings
from .models import User
try:
if settings.EMAIL_MODEL_ADMIN:
admin.site.register(User)
except AttributeError:
pass
|
from django.db import models
from django.core.exceptions import ValidationError
from django.utils.translation import gettext_lazy as _
class EventMap(models.Model):
#id = models.AutoField(primary_key=True)
name = models.CharField(max_length=256)
def __str__(self):
# Subject to change
return "{}: {}".format(se... |
# coding: utf-8
# In[1]:
import numpy as np
import pickle
from numpy.linalg import norm
# In[2]:
import os
print(os.listdir("."))
train_r = pickle.load(open("train_r.pkl", "rb"))
train_b = pickle.load(open("train_b.pkl", "rb"))
valid_r = pickle.load(open("valid_r.pkl", "rb"))
valid_b = pickle.load(open("valid_b.p... |
import sqlite3
class DBHelper():
def __init__(self, name="todo.sqlite"):
self.name = name
self.conn = sqlite3.connect(name)
def create(self):
query = 'CREATE TABLE IF NOT EXISTS items (user text, description text)'
user_index = 'CREATE INDEX IF NOT EXISTS userIndex ON items (us... |
from django.urls import path
from messenger_bot.views import MessengerWebhookAPIView
urlpatterns = [
path('webhook/', MessengerWebhookAPIView.as_view(), name='messenger_bot_webhook'),
]
|
from django.db import models
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomABACUser(AbstractUser):
designation = models.CharField(blank=True, max_length=20)
age = models.CharField(blank=True, max_length=20)
role = models.CharField(blank=True, max_length=120)
... |
def solution(s):
result = s[0]
for letter in s[1:]:
if letter < result[0]:
result = result + letter
else:
result = letter + result
return result
with open('input', 'r') as infile, open('output', 'w') as out:
num_testcases = int(next(infile))
for i in range(num_tes... |
class TestData:
HOME_PAGE_URL = 'http://www.gidmenu.com'
BREAKFASTS_PAGE_URL = HOME_PAGE_URL + '/restaurants/zavtraki/'
ACCOUNT = {
'email': 'john.doe@mail.com',
'password': 'Hilton101',
'invalid_email': 'john.doe@mail.con',
'invalid_password': 'Hilton102'
}
RESTA... |
import logging
logging.basicConfig(filename='app.log', filemode='a',format='%(asctime)s - %(message)s', level=logging.INFO)
# logging.info('Admin logged in')
def print_log(*para):
para = ['%s'%e for e in para]
content = ' '.join(para)
print(content)
logging.info(content)
if __name__ =="__main__":
... |
import re
copRegex = re.compile(r'Police(wo)?man')
sentence = 'Policewoman and Policeman bad.'
found = copRegex.search(sentence)
print('The sentence is: "' + sentence +'"')
if found != None:
print(f'Found word: {found.group()}')
print(f'found.group(1) = {found.group(1)}')
else:
print('Ne e ... |
from chess.agent import BaseAgent
from chess.pieces import Empty
from chess.board import Board
class HumanAgent(BaseAgent):
"""A human agent."""
def policy(self, game):
print()
str_from = input('Move from : ')
str_to = input('Move to : ')
print()
from_ = Board.transl... |
#!/usr/bin/env python
import os
import time
# Device: Pipe/0/ppl
PRESS_DELAY = 0.025
TILT_DELAY = 0.05
HOLD_DELAY = 0.8
NAMED_PIPE = os.path.expanduser('~/Library/Application Support/Dolphin/Pipes/ppl')
PIPE = None
def initialize():
global PIPE
print '[controller.py] Initializing named pipe writer...'
if not... |
import io
import os
import numpy as np
import tensorflow as tf
from datetime import datetime
import tensorflow.keras as keras
# from PIL import Image
# from sklearn.metrics import roc_auc_score
# import PIL.Image
# import cv2
from config import config
from utils.dataset import get_dataset
from utils.custom_model import... |
from .._tier0 import execute
from .._tier0 import plugin_function
from .._tier0 import Image
@plugin_function
def copy_horizontal_slice(source : Image, destination : Image = None, slice_index : int = 0) -> Image:
"""This method has two purposes:
It copies a 2D image to a given slice y position in a 3D image s... |
import sys
import numpy as np
from atom import atom
from msa import msa
from protein import protein
import common.commp as cp
def addscore(msacol, sm):
for aa in msacol:
#if aa.upper() not in cp.abaa:
if aa.upper() in cp.aa201:
sm[aa.upper()]+=1
# check whether there is unmatched residue in t... |
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
#root.attributes('-fullscreen', True)
root.geometry('2000x2000')
root.title('AppCop 1.0')
button_frame = tk.Frame(root)
button_frame.pack(fill=tk.X, side=tk.TOP)
button_frame.columnconfigure(0, weight=1)
button_frame.columnconfigure(1, ... |
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 4 13:39:00 2018
@author: Student
STATUS : incomplete, abandoned
Assignment 5
1. Use Hunt's Algorithm to create and test a decision tree on Car Evaluation Dataset.
ref: https://archive.ics.uci.edu/ml/datasets/car+evaluation
https://www-users.cs.umn.edu/~kumar00... |
import numpy as np
import random
import sys
#import ipdb
import logging
def random_based(self):
""" Perform step 4 of Alon algorithm, performing the refinement of the pairs, processing nodes in a random way. Some heuristic is applied in order to speed up the process.
"""
pass
def partition_correct(self)... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import unittest, sys, os, datetime,socket,redis
from conf.setting import RESULT_PATH
from HTMLTestRunner import HTMLTestRunner
from test_case.utils.Tools import send_mail
from test_case.action.k_detail import test_k_deail_head_Action
BASE_PATH = os.path.dirname(os.path.di... |
# Based on common_variables in https://github.com/opensafely/post-covid-vaccinated/blob/main/analysis/common_variables.py
# Import statements
## Cohort extractor
from cohortextractor import (
patients,
codelist,
filter_codes_by_category,
combine_codelists,
codelist_from_csv,
)
#study dates
from g... |
__author__ = 'admin'
import numpy as np
import pickle
from skimage.io import imread, imsave
from ProposalSizeFilter import ProposalSizeFilter
import scipy.io as sio
proposal_path = "/Users/admin/Desktop/NewExp/proposals.mat"
mat_cont = sio.loadmat(proposal_path)
proposals = mat_cont["res"]
proposals = proposals[0, :]
... |
def fun(variable):
letters=['a','e','o','i','u']
if (variable in letters):
return True
else:
return False
sequence=['g','e','w','a','k','s','p','r']
filtered=filter(fun,variable)
print("The filtered letters are:")
for s in filtered:
print(s) |
"""
Plot illustrateive firing rate responses to step stimuli.
Created by Nirag Kadakia at 13:00 09-20-2018
This work is licensed under the
Creative Commons Attribution-NonCommercial-ShareAlike 4.0
International License.
To view a copy of this license,
visit http://creativecommons.org/licenses/by-nc-sa/4.0/.
"""
i... |
from app import application, engine
from sqlalchemy.ext.automap import automap_base
from sqlalchemy import *
from flask import request, jsonify
from werkzeug.security import check_password_hash, generate_password_hash
from sqlalchemy.orm import Session
from flask_cors import CORS, cross_origin
CORS(application, suppor... |
#1. Convert "8.8" to a float.
a = float("8.8")
print(a)
#2. Convert 8.8 to an integer (with rounding).
b = int(round(8.8))
print(b)
#3. Convert "8.8" to an integer (with rounding).
c = int(round(float('8.8')))
print(c)
#4. Convert 8.8 to a string.
d = str(8.8)
print(d)
#5. Convert 8 to a string.
e ... |
# coding=utf-8
import json
import os, sys
import hashlib
import hmac
import base64
import urllib
import time
import uuid
import requests
def get_iso8601_time():
'''返回iso8601格式的时间'''
TIME_ZONE = "GMT"
FORMAT_ISO8601 = "%Y-%m-%dT%H:%M:%SZ"
return time.strftime(FORMAT_ISO8601, time.gmtime())
def get_uu... |
# -*- coding: utf-8 -*-
import numpy as np
import argparse
import os
def maxmin(initial, final, basename, sk, res):
maxdens,mindens=0,0
for i in range(initial,final):
path=basename+'%05d'%(i,)
data=np.genfromtxt(path,skip_header=sk)
density=data[::res,-2]
mindens_temp = np.amin... |
from GestionFichiers import *
from FonctionsEssaisVitesseLineaire import *
rho_max = 250
v_max = 130 / 3.6
longueurSegment = 100000
dureeExperience = 900
facteur = 1 + 1e-2
nbPointsEspace = 25000
deltaX = longueurSegment / nbPointsEspace
deltaT = deltaX * (1 / (facteur * v_max))
nbPointsTemps = int(dureeExperience / d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.