text stringlengths 38 1.54M |
|---|
import os
import json
import re
def parse_instrument(idx):
with open(os.path.join("E:\\WSM2020_proj", 'data/hshfy_wenshu', str(idx)+".json"), 'r', encoding='utf-8') as f:
dic = json.load(f)
return dic
class Case():
def __init__(self, info):
self.max_snippet_len = 200
self.type =... |
"""Module wide settings.
"""
import logging
import yaml
import os
from ..database import get_db
log = logging.getLogger(__name__)
settings = {}
def get_settings():
"""Get the settings currently being used by QUEST.
Returns:
A dictionary of the current settings.
Example:
{'BASE_DIR': ... |
# Generated by Django 3.0.6 on 2020-06-07 19:30
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0008_auto_20200607_2126'),
]
operations = [
migrations.RemoveField(
model_name='company',
name='user',
),
... |
"""
Zhigao空调 BY 菲佣 1.0
"""
from datetime import timedelta
from base64 import b64encode, b64decode
import asyncio
import binascii
import logging
import socket
import voluptuous as vol
from homeassistant.core import callback
from homeassistant.components.climate import (
PLATFORM_SCHEMA,
ClimateDevice, ATTR_TAR... |
# Lint as: python3
# Copyright 2019, The TensorFlow Federated Authors.
#
# 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 ... |
from unittest import TestCase
import numpy as np
import matplotlib.pyplot as plt
from hyperspy.signals import Signal2D
from empyer.signals.power_signal import PowerSignal
class TestPowerSignal(TestCase):
def setUp(self):
d = np.random.rand(10, 10, 720, 180)
self.s = Signal2D(d)
self.ps = P... |
# this is first program for git testing
def printHelloWorld():
print('Hello World!')
if __name__ == '__main__':
printHelloWorld() |
import _initpath
import os
import re
import collections
import pyradox
province_map = pyradox.worldmap.ProvinceMap(game = 'EU4')
colormap = {}
for filename, data in pyradox.txt.parse_dir(os.path.join(pyradox.get_game_directory('EU4'), 'history', 'provinces'), verbose=False):
m = re.match('\d+', filenam... |
# __init__.py are used to mark directories on disk as Python package directories
# importing all modules from dir |
from flask import Flask
app = Flask(__name__)
import histogram_exercises
import dictionary_words
# import tweetGenTutorials
import creating_randomness
import ClassDictogram as d
@app.route('/')
def generate_word():
return d.Dictogram.generate_sentence_from_markov_chain(10)
if __name__ == '__main__':
# Turn ... |
from django.contrib.auth.views import LoginView
from django.shortcuts import render
# Create your views here.
from django.views import View
from accounts import handlers as accounts_handlers
class CustomerLoginView(View):
def get(self, request, *args, **kwargs):
return render(request, 'accounts/login.ht... |
# Linear Search function used to find an item in a list.
def linear_search(my_item, my_list):
found = False
position = 0
while position < len(my_list) and not found:
if my_list[position] == my_item:
found = True
position = position + 1
return found
if __name__ == "__main__"... |
# This function is not intended to be invoked directly. Instead it will be
# triggered by an orchestrator function.
# Before running this sample, please:
# - create a Durable orchestration function
# - create a Durable HTTP starter function
# - add azure-functions-durable to requirements.txt
# - run pip install -... |
from datetime import datetime
from elasticsearch import Elasticsearch
es = Elasticsearch(hosts="10.0.0.45")
doc = {
'name': 'David gidony',
'numberOfPeople': '3',
'groupName': 'Close Family',
'eMail': 'dudug@index.co.il',
'cellPhone': '0522808442',
'validated': 'yes',
'autoRemind': 'yes',
... |
import os
import csv
from pdb import set_trace
import pickle
def extract_feature(base, csvpath):
events = [event for event in os.listdir(csvpath) if event.__contains__('event')]
comments = [comment for comment in os.listdir(csvpath) if comment.__contains__('comment')]
milestones = [milestone for milestone... |
def info_filter(src_string):
start = "#INFO#"
end = "#END#\r\n"
subtract_prefix = (src_string.split(start))[1]
subtract_postfix = subtract_prefix.split(end)[0]
if ':' in subtract_postfix:
execution_result = subtract_postfix.split(':')[0]
info_string = subtract_postfix.split(':')[1]
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import argparse
from PIL import Image
import time
import io
import tflite_runtime.interpreter as tflite
import cv2
import re
CAMERA_WIDTH = 640
CAMERA_HEIGHT = 480
def load_labels(path):
... |
import pandas as pd
df = pd.read_hdf("filtered_data.hdf", "df1")
def page_entity(page):
p = False
if page == "/":
p = 'home'
if "/item/" in page:
p = 'item'
if p == False:
p = 'unknown'
df_pv['page_entity'] = df_pv['data'].apply(lambda x: page_entity(x))
df_pv = df[(df.type ... |
from django.contrib.auth.models import AbstractUser
from django.db import models
import random
import string
# Create your models here
class User(AbstractUser):
phone_number = models.CharField(max_length=100)
address = models.CharField(max_length=200)
class Friend(models.Model):
user = models.ForeignKe... |
from django.conf.urls import include, url
from django.contrib import admin
from .import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'bulding_api/$', views.BuildinListApiView.as_view(), name='buidinglist'),
url(r'bulding_api/(?P<pk>\d+)/$', views.DetailedBuildingApiView.as_view(), nam... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import Image, sys
a=1
#sys.path.insert(0,'.')
sys.path.insert(0,'..')
import CLClasses
#import repeatsAverage
class Matrix(CLClasses.Base):
fileCount = 1
def __init__(self, eitherJogosObjOrS2):
CLClasses.Base.__init__(self, eitherJogosObjOrS2)
self.folhaA4 ... |
# Import Packages
import cv2
from matplotlib import pyplot as plt
from matplotlib import gridspec as gridspec
import numpy as np
# Gridspec (Untuk mengatur letak gambar output)
gs = gridspec.GridSpec(5, 6)
# File path (sesuai directory file input)
path = r'D:\User Projects\PCD\tugasPCD\image-sample.JPG'
# import file... |
# Copyright (c) 2015 Ultimaker B.V.
# Uranium is released under the terms of the AGPLv3 or higher.
## Abstact iterator class.
class Iterator(object):
def __init__(self, scene_node):
super(Iterator, self).__init__() # Call super to make multiple inheritence work.
self._scene_node = scene_node
... |
# -*- coding: utf-8 -*-
import logging
import hashlib
from django.conf import settings
from django.dispatch import Signal, receiver
from django.utils.timezone import now as tz_now
from django.utils.crypto import get_random_string
from .models import ImpersonationLog
logger = logging.getLogger(__name__)
# signal sent ... |
import socket
import sys
import time
import os
import hashlib
FLAGS = None
class ClientSocket():
def __init__(self):
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
self.socket.bind((FLAGS.ip, FLAGS.port))
self.buf = 1024
self.timeout = 3
def socket_send(self):
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Implementation of https://arxiv.org/pdf/1512.03385.pdf.
# See section 4.2 for model architecture on CIFAR-10.
# Some part of the code was referenced below.
# https://github.com/pytorch/vision/blob/master/torchvision/models/resnet.py
import os
import torch
import torch.nn... |
import argparse
import os
from lazyme import color_print
import XmlParser
import gitAdressParser
## change these default variables as needed or use command line arguments ##############################################################################################################################
git_repo_address = ... |
from django.conf.urls import url, include
from rest_framework import routers
from cumlaudeUcla import views
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
router = routers.DefaultRouter()
router.register(r'Estudiantes', views.EstudianteViewSet)
urlpattern... |
#!/usr/bin/env python
# Copyright (c) 2018 Intel Labs.
# authors: German Ros (german.ros@intel.com)
#
# This work is licensed under the terms of the MIT license.
# For a copy, see <https://opensource.org/licenses/MIT>.
"""
Example of automatic vehicle control from client side.
"""
from __future__ import print_fu... |
from myParentclass import *
WIDTH = 900
HEIGHT = 500
class scene_block(sprite):
def __init__(self, width, height, x=0, y=0): # add frames input
sprite.__init__(self, x, y)
self.width = width
self.height = height
self.dim = (self.width, self.height)
self.typ = random.randra... |
import RPi.GPIO as GPIO
from time import sleep
from threading import Thread
m1_in1 = 24
m1_in2 = 23
m1_en = 25
temp1=1
m2_in1 = 10
m2_in2 = 9
m2_en = 11
temp2=1
GPIO.setmode(GPIO.BCM)
GPIO.setup(m1_in1,GPIO.OUT)
GPIO.setup(m1_in2,GPIO.OUT)
GPIO.setup(m1_en,GPIO.OUT)
GPIO.output(m1_in1,GPIO.LOW)
GPIO.output(... |
#!/usr/bin/env python
from Grammar import Grammar
from Grammar import Parser
import cgi
import cgitb
cgitb.enable()
form = cgi.FieldStorage()
rules = form['rules'].value.split('\r\n')
cmd = form['cmd'].value
g = Grammar()
p = Parser(g)
p.parse_rules(rules)
if cmd == 'generate':
print(g.derive('S'))
elif cmd == 'cnf... |
# noqa: D100
import re
from pathlib import Path
from setuptools import find_packages, setup
def parse_reqs(file):
"""Parse dependencies from requirements file with regex."""
egg_regex = re.compile(r"#egg=(\w+)")
reqs = list()
for req in open(file):
req = req.strip()
git_url_match = e... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-04-06 17:12
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('samples', '0003_auto_20171229_0830'),
]
operations = [
migrations.AddField(... |
import re
import csv
import string
import sys
fastq = sys.argv[1]
output = sys.argv[2]
file = open(fastq)
map = open(output,'w')
header = ['#SampleID','BarcodeSequence','LinkerPrimerSequence','Description','Length']
map.write("\t".join(header)+"\n")
line = file.readline()
while line:
if line.startswith('@'):
line =... |
#!/usr/bin/env python
# coding=UTF-8
# author: zhangjiaqi <1399622866@qq.com>
# File: 03.insert_sort
# Date: 5/12/2019
import random
def insert_sort(li):
"""
思路:从无序区第一个插入到有序区,主要是有序去的变化。
有两种判断插入区域方式:
因为循环次数固定(通过break)则需要判定跳出循环;另一种方式时:时指针方式,只要指针对应的值大
:param li:
:return:
"""
for i in ran... |
import torch
import numpy as np
import ipdb
import core.utils_data as utils_disco
st = ipdb.set_trace
import torch.nn.functional as F
XMIN = -7.5 # right (neg is left)
XMAX = 7.5 # right
YMIN = -7.5 # down (neg is up)
YMAX = 7.5 # down
ZMIN = 0.0 # forward
ZMAX = 16.0 # forward
def Ref2Mem(xyz, Z, Y, X):
# xyz... |
valorx = float(input("digite o valor para x:"))
if(valorx <= 1):
valorx = 1
elif(valorx > 1 and valorx <= 2):
valorx = 2
elif(valorx > 2 and valorx <= 3):
valorx = (valorx**2)
elif(valorx > 3):
valorx = (valorx**3)
print(round(valorx,2)) |
import os
from os.path import exists
import tqdm
import numpy as np
import torch.utils.data
from torchvision.datasets import ImageFolder
from torchvision import transforms
import functools
import PIL
import re
class VideoFolderDataset(torch.utils.data.Dataset):
def __init__(self, folder, counter = None... |
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(0, 3*np.pi, 0.1)
y = np.sin(x)
#Plot the points
plt.plot(x,y)
plt.show() #in Ubuntu Linux
|
from heapq import heappush, heappop, heapify
class Solution:
def trapRainWater(self, heightMap: List[List[int]]) -> int:
"""Priority queue.
Running time: O(mnlogmn) where m, n are the size of heightMap.
"""
if not heightMap:
return 0
m, n = len(heightMap), len(h... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from APHandler import APcreateHandler, APaskHandler, APregistHandler
from sqlalchemy.orm import scoped_session, sessionmaker
from tornado.options import define, options
#import Regis... |
from flask import Flask, redirect, request, render_template, session
import random, datetime
app = Flask(__name__)
app.secret_key = '@#$%#&%**%^%^%^#%^*(*'
@app.route('/')
def index():
if (not 'gold_count' in session) or (not 'activities' in session):
session['gold_count'] = 0
session['activities'] = []
return... |
import smtplib
mail = "youremail@gmail.com"
password = "yourpassword"
mail_server = smtplib.SMTP("smtp.gmail.com", 587) # smtp.gmail.com is server and 587 is port. You can choose 465 or 2525 too
mail_server.starttls() #starts security protocol
mail_server.login(mail, password) #login to mail
message = ... |
import cv2
import imutils
def crop_ct101_bb(image, bb, padding=10, dst_size=(32, 32)):
(y, h, x, w) = bb
(x, y) = (max(x - padding, 0), max(y - padding, 0))
roi = image[y:h+padding, x:w+padding]
roi = cv2.resize(roi, dst_size, interpolation=cv2.INTER_AREA)
return roi
def pyramid(image, scale=1.5... |
# -*- coding: utf-8 -*-
"""
Created on Fri Oct 30 00:43:54 2020
@author: 융
"""
def solution(N,road,K):
#visited = [False for _ in range(N+1)]
#pdb.set_trace()
costs = [float('inf') for _ in range(N+1)]
costs[1] = 0
parents = [1]
while(parents):
parent = parents.pop(0)
... |
# ##############################################################################
# *** SETUP ***
# ##############################################################################
# -----------------------------------
# MayAi bot Version 0.9 By Moz4r
#
# Wikidatafetcher By Beetlejuice
# --------------------------... |
# title: DataManager.py
# description:
# author: Roman Tochony
# date: 20.2.2019
# version: 1.0
# notes:
# python_version: Python 3.7.2
import json
class Container:
"""Object initiator function"""
def __init__(self, version='', date='', description='',... |
import arcade
from fishy.menu import GameOverView
class PlayerSprite:
def __init__(self):
self.sprite = None
def set_image(self, image_source, scaling):
self.sprite = arcade.Sprite(image_source, scaling)
def set_position(self, x, y):
self.sprite.center_x = x
self.sprite.ce... |
'''
Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be po... |
from modules.bomb import Bomb
bomb = Bomb()
bomb.loadSettings()
bomb.initialAnalysis()
# detectVisibleFeatures(bomb)
# rotate bomb to the other side
# detectVisibleFeatures(bomb)
# for module in bomb.modules:
# # solve the module
# # execute the solution
# pass
|
import torch
import gym
from collections import defaultdict
from tqdm import tqdm
from pprint import pprint
# If this import does not work, add an MC. to it.
from blackjack_helper import plot_blackjack_values
def run_episode(env, hold_score):
state = env.reset()
rewards, states, is_done = [], [state], False
... |
import pickle
import strategy as ai
import Strategy2 as ai2
from Othello_Core import *
import time
#############################################################
# client.py
# a simple tic-tac-toe client
# plays 2 strategies against each other and keeps score
# imports strategies from "strategies.py" as ai
# rest of fu... |
# -*- coding: utf-8 -*-
"""Family module for Speedydeletion.Wikia.com"""
__version__ = '$Id$'
from pywikibot import family
class Family(family.Family):
"""Family class for Wikia."""
def __init__(self):
"""Constructor."""
family.Family.__init__(self)
self.name = u'speedydeletion'
... |
import redis
class RedisClient:
def __init__(self, host, port):
self.host = host
self.port = port
self.client = redis.Redis(host=host, port=port)
if __name__ == '__main__':
host = "localhost"
port = 6379
r = redis.Redis(host=host, port=port)
for i in range(100):
... |
import json
import os
import pytest
import requests
import requests_mock as req_mock
from pipeline_tools.shared import http_requests
from pipeline_tools.shared.http_requests import HttpRequests
from pipeline_tools.tests.http_requests_manager import HttpRequestsManager
class TestHttpRequests(object):
def test_che... |
# Generated by Django 3.0.4 on 2020-05-18 07:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('webpage', '0004_auto_20200506_2209'),
]
operations = [
migrations.AlterField(
model_name='package',
name='descriptio... |
__author__ = 'marcus, fbahr'
import os
from ConfigParser import RawConfigParser
class Config(object): # ...RawConfigParser):
def __init__(self, path='giraffe.cfg'):
# RawConfigParser.__init__(self) # < RawConfigParser = 'old-style' class
if path == 'giraffe.cfg':
path = os.sep.joi... |
import json
from flask import Flask,render_template,request
from flaskext.mysql import MySQL
app=Flask(__name__)
mysql=MySQL()
app.config['MYSQL_DATABASE_HOST']="127.0.0.1"
app.config['MYSQL_DATABASE_USER']="root"
app.config['MYSQL_DATABASE_PASSWORD']=""
app.config['MYSQL_DATABASE_DB']="student_database... |
def get_formatted_name(first,middle,last):
"""Generates a neatly formatted full name."""
full_name = f"{first} {middle} {last}"
return full_name.title()
# This version should work for people with middle names, but when we test
# it, we see that we’ve broken the function for people with just a first and la... |
import pymysql
import timeit
import requests
import urllib
import numpy
start = timeit.default_timer()
connection = pymysql.connect(host='localhost',user='root',db='benchmark',cursorclass=pymysql.cursors.DictCursor)
c = connection.cursor()
c.execute('select id from class')
results = []
rets = c.fetchall()
for c, i in ... |
import PC
import configme
import sys
import Commander_normal
import PipCommander
import Commander
import executed_information
import register_file
from PyQt5 import QtCore, QtGui, QtWidgets
import time
import BASIC_code
#import breeze_resources
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QKeySequence, QPalett... |
tableau=[1,1,0,0,1,0,0,0,1]
grpe_nul=0
for compteur in range(len(tableau)) :
if tableau[compteur]==0 :
grpe_nul+=1
else :
grpe_nul_maxi,grpe_nul=grpe_nul,0
print("Le plus long groupe d'éléments nuls est de",grpe_nul_maxi)
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
Renames svg, jpg, and png files, removing the ID-number at the end of the filename
"""
from __future__ import print_function
import os
def new_name(name):
base_name, extension = os.path.splitext(name)
parts = base_name.split('_')
if parts[-1].isdigit():
... |
# 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... |
import numpy as np
import matplotlib.pyplot as plt
N = 6
accident_means = (520, 580, 490, 405, 550, 480)
accident_std = (2, 3, 4, 1, 2, 3)
ind = np.arange(N) # the x locations for the groups
width = 0.35 # the width of the bars
fig, ax = plt.subplots()
rects1 = ax.bar(ind, accident_means, width, color='r', ye... |
import random
def generarnumero():
return random.randint(1000,9999)
def ordenarlista(listanombres,listaintentos):
largo=len(listaintentos)
for i in range(largo-1):
for j in range (i+1,largo):
if listaintentos[i] > listaintentos[j]:
aux=listaintentos[i]
... |
import math
import sys
import os
import copy
import time
def main(argv):
#start counting time
start_time = time.time()
#time limit is current time + minutes
time_limit = time.time() + 600
# Get the file name from the command line argument
filename = os.path.splitext(sys.argv[-1])[0]
... |
from django.urls import path
from . import views
urlpatterns = [
path('session/<int:pk>/', views.AssessmentSessionDetailView.as_view(), name="assessmentsession_detail"),
path('submission/<int:pk>/', views.SubmissionUpdateView.as_view(), name="submission_edit"),
path('submit/<int:assessmentsession_id>/', v... |
class Solution(object):
def minAreaFreeRect_tle(self, points):
"""
:type points: List[List[int]]
:rtype: float
"""
def dotProduct(a, b, c):
baX, baY = b[0] - a[0], b[1] - a[1]
caX, caY = c[0] - a[0], c[1] - a[1] # bugfixed, typo
return ba... |
import torch
import numpy as np
from PIL import Image
from torchvision import transforms
import h5py
import matplotlib.pyplot as plt
import random
from torch.utils.data import Dataset, DataLoader, random_split
import torch.nn as nn
import torch.optim as optim
import os
from tqdm import tqdm
import time
import pickle
i... |
#!/bin/env python
# encoding: utf-8
__author__ = 'icejoywoo'
class Solution:
# @param {integer} x
# @return {boolean}
def isPalindrome(self, x):
if x < 0:
return False
y = x
div = 1
while y / div >= 10:
div *= 10
while y:
print ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
# import the necessary packages
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
import numpy as np
def run():
# initialize the camera and grab a reference to the raw camera capture
camera = PiCamera()
c... |
"""
This type stub file was generated by pyright.
"""
from rdkit.VLib.Supply import SupplyNode
class SmilesSupplyNode(SupplyNode):
""" Smiles supplier
Sample Usage:
>>> import os
>>> from rdkit import RDConfig
>>> fileN = os.path.join(RDConfig.RDCodeDir,'VLib','NodeLib',\
... |
#import tkinter 1
from tkinter import *
window = Tk()
window.title("Tkinter demo")
window.minsize(width=500, height=500)
window.config(padx=100, pady=200)
my_label = Label(text="I am a Label", font=("Arial", 24, "bold"))
#my_label.pack()
#my_label.place(x=0, y=0)
my_label.grid(column=0, row=0)
my_label["text"]... |
import random
def quick_sort(arr):
start, end = 0, len(arr)-1
def sort(arr, start, end):
if start - end == 1 : #Already sorted if only elem or no elem
return arr
pivot = random.randint(start, end )
arr[pivot], arr[end], pivot = arr[end], arr[pivot], end #Move pivot el... |
# Generated by Django 2.2.6 on 2020-05-23 10:59
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pictionary', '0006_cards'),
]
operations = [
migrations.DeleteModel(
name='Cards',
),
]
|
#3-4
guests = ["John Skeet", "McKeel Hagerty", "Dave Chappelle"]
baseMessage = "Dear %s,\nI would like to formally invite to my home for dinner Saturday, January 30, 2021. Please let me know if you plan to attend.\n\nThank you.\n\n"
for guest in guests:
print(baseMessage%(guest))
#3-5
print(f"Unfortun... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 13 10:35:36 2018
google colab 사용해서
@author: SDEDU
"""
import tensorflow as tf
import numpy as np
from tensorflow.keras.datasets.cifar10 import load_data
#다음 배치를 읽어오기 위한 함수
#num 개수만큼 랜덤하게 이미지와 레이블을 리턴
def next_batch(num,data,labels):
idx=np.arange(0,len(data))
n... |
#---------------------------------------------------------
#Python Layer for the cityscapes dataset
# Adapted from: Fully Convolutional Networks for Semantic Segmentation by Jonathan Long*, Evan Shelhamer*, and Trevor Darrell. CVPR 2015 and PAMI 2016. http://fcn.berkeleyvision.org
#----------------------------------... |
"""
Reads the grammar in text and returns Terminals and NonTerminal objects
"""
import re
from grammar_elements import Terminal, NonTerminal, ElementType
OR_SYMBOL = '|'
EPSILON_SYMBOL = '\L'
def from_string(string):
"""
:param string: a string that contains the syntax grammar rule definitions
:return:... |
import requests
class Repustate:
def __init__(self, api_key=None, server='api.repustate.com', cache=None):
"""
:param str api_key:
:param disk.Cache.Cache cache:
"""
self._api_key = api_key or '$APIKEY'
self._server = server
self._cache = cache
if self._cache:
self.get_entities = self._cache.make... |
import unittest
from selenium import webdriver
import time
links = ["http://suninjuly.github.io/registration1.html", "http://suninjuly.github.io/registration2.html"]
class TestForms(unittest.TestCase):
browser = webdriver.Chrome()
def test_fill_form(self):
for link in links:
self.browser... |
import qcodes.plots.pyqtgraph as qplt
import numpy as np
import datetime as t
import os
import csv
'''
Data wrapper that can create a live plot (based on qcodes.plots.pyqtgraph),
a text file and a csv file containing the data.
By: Zhang Zhongming
INSTRUCTIONS ON USE
To initialize:
data = Data(<director... |
"""
Hra o trůny
Stáhni si soubor character-deaths.csv, který obsahuje informace o smrti některých postav z prvních pěti
knih románové série Píseň ohně a ledu (A Song of Fire and Ice).
"""
#import wget
#wget.download("https://raw.githubusercontent.com/pesikj/python-012021/master/zadani/5/character-deaths.csv")
#1 Načti... |
import numpy as np
import sys
import pickle
import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
from collections import deque
import random
from simulate import PendulumDynamics
class KMostRecent:
def __init__(self, max_size):
self.max_size = max_size
self.... |
from flask_sqlalchemy import SQLAlchemy
from extensions.sql_alchemy import db
class CandleStickerModel(db.Model):
__tablename__ = 'candle_sticker'
id = db.Column(db.Integer, primary_key=True)
open_value = db.Column(db.Float(40), nullable=False)
close_value = db.Column(db.Float(40), nullable=False)
... |
import os
mappingFiles = os.listdir("./pred/prediction")
mappingFiles.sort(key=lambda x: int(x[7:-4]))
# mappingFiles = os.listdir("../mapping/")
fileNumber = 1
for file in mappingFiles:
fileIn = open("./pred/prediction/" + file, "r")
# fileIn = open("../mapping/" + file, "r")
mapping = fileIn.readlines(... |
from keras import losses
from keras import backend as K
import settings
################################################################################
# Loss functions
################################################################################
def loss_function_carl(y_true, y_pred):
return losses.binary_... |
from dcgan import DCGAN
import matplotlib.pyplot as plt
import numpy as np
def create_image(gen_imgs, name, xsize=4, ysize=4):
fig, axs = plt.subplots(xsize, ysize, figsize=(xsize*2,ysize*2))
plt.subplots_adjust(left=0.05,bottom=0.05,right=0.95,top=0.95, wspace=0.2, hspace=0.2)
cnt = 0
... |
import unittest
import collections
import dafpy as dfp
######################################
# Some definitions for the tests
######################################
class DataGenerator(object):
def __call__(self):
return {'observations': 10}
@dfp.set_call_rets_decorator('trade')
def decision(position... |
def solve_part_1(data):
answers = []
answer_data = {
"group_members": 0,
"answers": ''
}
for line in data:
if line == '':
answers.append(answer_data)
answer_data = {
"group_members": 0,
"answers": ''
}
el... |
filename = 'text_files/write2.txt'
# Make a dice class
from random import randint
class Die:
"""A Simple Dice object"""
def __init__(self,sides=6):
"""Initialize name and sides of dice"""
self.sides = sides
def roll_die(self):
return(randint(1,self.sides))
# Make new 6 sided ... |
"""
There are n cities numbered from 0 to n-1 and n-1 roads such that there is only one way to travel between two different cities (this network form a tree). Last year, The ministry of transport decided to orient the roads in one direction because they are too narrow.
Roads are represented by connections where connec... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'Department'
db.create_table(u'kb_department', (
... |
'''
Copyright (c) 2018 Tobias Sommer
Licensed under the MIT License. See LICENSE file in the project root for full license information.
'''
import os
import base64
LOG_PATH = "logfile.log"
APPLICATION_NAME = os.environ.get('APPLICATION_NAME')
SERVER_PORT = os.environ.get('SERVER_PORT')
MICROSERVICE_SUBSCRIPTION_ENABL... |
from Raton import Raton
from Teclado import Teclado
from Monitor import Monitor
class Computadora:
contadorComputadoras = 0
def __init__(self, nombre, monitor, teclado, raton):
self._idComputadora = Computadora.aumentarId()
self._nombre = nombre
self._monitor = monitor
self._te... |
import sys
import os
import time
# ---
goals = {
'Get enough sleep': 3,
'Pass exams': 5,
'Party hard': 4
}
actions = {
'Go to bed': {
'Get enough sleep': -2,
'Pass exams': 1,
'Party hard': 0
},
'Pull all-nighter at the Library': {
'Get enough sleep': 5,
'Pass exams': -4,
'Party ha... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 18 06:18:53 2019
@author: Eric Born
"""
from random import shuffle
playerNum = 3
class Card(object):
suit = [None, 'Hearts', 'Diamonds', 'Spades', 'Clubs']
rank = [None, '2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace',]
... |
from __future__ import division
def compute_extent_size(lattice):
number_of_objects = len(lattice._context._objects)
extent_size_index = {}
for c in lattice:
extent_size_index[c.concept_id] = len(c.extent) / number_of_objects
return extent_size_index |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.