text
stringlengths
38
1.54M
from itm.publishing.domain.scholarship import AcademicLevel def test_undergraduate_value(): assert AcademicLevel.UNDERGRADUATE.value == 'UNDERGRADUATE' def test_postgraduate_value(): assert AcademicLevel.POSTGRADUATE.value == 'POSTGRADUATE' def test_others_value(): assert AcademicLevel.OTHERS.value ==...
from paddle import fluid import os import multiprocessing gpu_dev_count = int(fluid.core.get_cuda_device_count()) cpu_dev_count = int(os.environ.get('CPU_NUM', multiprocessing.cpu_count())) dev_count = gpu_dev_count if gpu_dev_count > 0 else cpu_dev_count
# Word Jumble # # The computer picks a random word and then "jumbles" it # The player has to guess the original word import random WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone") word = random.choice(WORDS) correct = word print("There are", len(correct), "letters in the word.") for i in r...
#Romain Ducarrouge import sqlite3 import pandas as pd import config import numpy as np # FORMATTING LOGS FILE df = pd.read_csv("data/clean/logs_clean.csv") #Split first column into 3 columns of data (Campus, Building, Room) New1 = df['room'].str.partition('>') New1.columns = ['campus', 'building', 'room'] New2 = New...
import pyglet from pyglet.gl import * joysticks = pyglet.input.get_joysticks() assert joysticks, 'No joystick device is connected' joystick = joysticks[0] joystick.open() window = pyglet.window.Window(width=800, height=800) batch = pyglet.graphics.Batch() # Labels pyglet.text.Label("Buttons:", x=15, y=window.height ...
# coding: utf-8 # @Time: 2021/9/3 12:59 # @Author: Bing # @File: 010_string # @Project: basic s = 'chinai' print(len(s)) print(s.find('i')) print(s.startswith('c')) print(s.count('i')) print(s.replace('i', 'w')) s1 = '1@2@3@1' print(s1.split('@')) s2 = ' 1 2 2 ' print(s2.strip()) s3 = 'a' s4 = 'bbbbbbbb' print(...
class Node: def __init__(self, prevnode = None, prevmove = None): self.board = [0] * 64 self.player = 0 self.time = 0 self.pieces1 = [] #need to make func for pieces1, pieces2, pieces3, pieces4 self.pieces2 = [] self.pieces3 = [] self.pieces4 = [] sel...
from slacker import Slacker SLACK_API_TOKEN = 'your-slack-api-token-goes-here' SLACK_CHANNEL = '#general' def lambda_handler(event, context): slack = Slacker(SLACK_API_TOKEN) slack.chat.post_message(SLACK_CHANNEL, 'Hello, world!')
"""This module contains helper functions for the api blueprint.""" import os from flask import current_app from datetime import datetime def string_to_date(date_string, format): """Given a string date and format, return a corresponding date object. """ try: return datetime.strptime(date_str...
from flask.ext.wtf import Form, RecaptchaField from wtforms import TextField, PasswordField, BooleanField,validators, DateField, HiddenField, TextAreaField, SelectField from wtforms.validators import Required, EqualTo, Email, NoneOf from flask.ext.babel import gettext class UserSearchForm(Form): user_info = TextFi...
import requests import datetime import string from myDb import myDb # http://api.eventful.com/json/categories/list?app_key=BwndJZPhjvnDbKX5 categories = [ {"name":"Concerts & Tour Dates","event_count":None,"id":"music"}, {"name":"Conferences & Tradeshows","event_count":None,"id":"conference"}, {"name":"Co...
#!/usr/bin/python import urllib2 from bs4 import BeautifulSoup schedule_page = 'http://www.espn.com/college-football/team/schedule/_/id/130' page = urllib2.urlopen(schedule_page) soup = BeautifulSoup(page, 'html.parser') date = soup.find(id='showschedule').find(class_='tablehead').contents[2].contents[0].get_text()...
#!/bin/python3 """ Model for the table tb_hardware Created by Eric Gibert on 31 Aug 2016 Define the IC (probes, sensors, other...) that are present on the control board. Each hardware will have a driver to interact with defined in the 'drivers' module """ from model.model import Ponicwatch_Table from d...
import requests import json API_BASE_URL = "https://www.diabotical.com/" AVAILABLE_MODES = [ "r_macguffin", "r_wo", "r_rocket_arena_2", "r_shaft_arena_1", "r_ca_2", "r_ca_1" ] class Leaderboard: def __init__(self, mode, count, country, user_id): self.mode = mode self.count =...
from bin.start import service_start if __name__ == '__main__': '''启动程序的模块''' service_start()
from mpl_toolkits import mplot3d #%matplotlib inline import numpy as np import matplotlib.pyplot as plt # Fixing random state for reproducibility np.random.seed(19680801) circle_r = 2 circle_x = 0 circle_y = 0 circle_z = 0 N = 2500 theta = np.pi*np.random.rand(N) phi = 2 * np.pi * np.random.rand(N) r = circle_r * n...
import requests as rq import random as rn joke = input("Let me tell you a joke! Give me a topic: ") res = rq.get("http://icanhazdadjoke.com/search",headers={ 'Accept':'application/json'},params={ "term":joke}) try: if(res.json()['total_jokes']>0): print(f"I found {res...
class VaspError(): def __init__(curr_dir="./"): # determine which error the current task belongs to pass
# prompt the user for name name = input("What is your name?\n") # printing the value of name print(f"hello, {name}")
# %%writefile main.py # Source: https://www.kaggle.com/jamesmcguigan/rock-paper-scissors-random-seed-search/ # Source: https://github.com/JamesMcGuigan/ai-games/blob/master/games/rock-paper-scissors/rng/random_seed_search.py # NOTE: this is the old implementation written as a single function # see RandomSeedSearc...
class Network: def Connecting(self): raise NotImplementedError def main(): Network.Connecting()
import torch torch.manual_seed(0) class DotProjectionAttention(torch.nn.Module): def __init__(self, attn_size, enc_hidden_size, dec_hidden_size): super(DotProjectionAttention, self).__init__() self.enc_hidden_size = enc_hidden_size self.dec_hidden_size = dec_hidden_size self.attn_...
import numpy as np import pdb import matplotlib.pyplot as plt import oscillatorLib as ol import experimentLib import matplotlib import matplotlib.patches as patches from matplotlib.ticker import FormatStrFormatter ###################################### ###################################### ###### SIMULATION PARAME...
from src.utility.validate_descriptor import ValidFormula, ValidPredictors def formula(attr): def decorator(cls): setattr(cls, attr, ValidFormula()) return cls return decorator def predictors(attr): def decorator(cls): setattr(cls, attr, ValidPredictors()) return cls r...
import fpdf class PDFFlashCard(fpdf.FPDF): """docstring for PDFFlashCard""" __a4_l_w = 298 # milimet __a4_l_h = 210 def __init__(self, orient, font, size, rows, cols, spacing): super(PDFFlashCard, self).__init__(orient, "mm", "A4") self.font = font self.size = size self.orient = orient self.set_margins(...
# coding=gbk import requests import logging import time url = "http://www.jubi.com/" api = "api/v1/ticker" coin = "ans" payload = {"coin":coin} for i in range(1, 10000): res = requests.get(url + api, params = payload) ticker = res.json() msg = "%.2f" % float(ticker['last']) print time.strf...
f=open('triangle2.txt','r') triangle=[] for line in f: triangle.append([int(x) for x in line.split()]) f.close() height=len(triangle) for i in xrange(height-2,-1,-1): #row #print triangle #print i,'i' for j in xrange(i+1): triangle[i][j]=triangle[i][j]+max(triangle[i+1][j],triangle[i+1][j+1]) print trian...
""" Generated by 'django-admin startproject' using Django 2.0.7. updates: 2.2.10 (20200211); 2.2.8(20191204); 2.2.4 (20190819); 2.1.7 (?); 2.1.2 (20181013) """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #...
import os import re frameDir = "./files/frame" files = {} categories = { "start": 1, "qb": 2, "air": 3, "player": 3 } # files["test1"] = [{"a": 1, "b": 2}, {"a": 3, "b": 4}] # files["test2"] = [{"a": 5, "b": 6}, {"a": 7, "b": 8}] # for index, (file, frames) in enumerate(files.items()): # for index, frame in en...
import json import re from urllib.parse import urlparse import certifi import requests import urllib3 from bs4 import BeautifulSoup def collect_data(outfile): resource = "https://www.dailyscript.com/movie.html" movie_page = requests.get(resource) soup = BeautifulSoup(movie_page.content, features="html.pa...
""" Created on Nov 02 18:27:52 2018 Project: Plotting a best fit line through a set of points. This is a program which aims to plot a best-fit fit line through a scatter plot. The user may input the co-ordinate points either a .csv file or may enter them manually one at a time. An example result has been provided as w...
# 乱数を生成するにはrandomというライブラリをimportする必要があります import random # importしたrandomの中にある、random()という名前の関数を呼び出します r = random.random() # rには、「0以上1未満の実数」が代入されます # elif を使って記述すると次の通り if r<1/6: print('1の目が出た') elif 1/6<=r and r<2/6: # Python独自の条件の書き方に注目 print('2の目が出た') elif 2/6<=r and r<3/6: print('3の目が出た') elif 3/6<=r<4...
""" Contains all physical constants in an object called 'Constant', with some methods to change their units. Imports directly into global namespace. Constants (default units are cgs): pi exp : Euler's number c : Speed of light e : Elementary charge k_B ...
#!/usr/bin/env python """ Calculates a corrected sodium level for hyperglycemia """ def katz(serum_na, serum_glucose): """Calculates Sodium corrected for Hyperglycemia using Katz formula""" return serum_na + 0.016*(serum_glucose-100) def hillier(serum_na, serum_glucose): """Calculates Sodium corrected for...
from msvcrt import getch import serial port = 'COM6' baudrate = 115200 timeoutNum = 1 print "Settings can be configured in .py file" print 'Current settings...' print 'port:',port print 'baudrate:',baudrate # don't think this is perfect but intended to deal with situation where connection is already opon try: ser =...
''' # To clean up the terminal screen import os os.system('cls') # on windows ''' # ++++++++++++++++++++++++++++++ # Comparisons: # Equal: == # Not Equal: != # Greater Than: > # Less Than: < # Greater or Equal: >= # Less or Equal: <= # Object Identity: is # False Values: # False ...
#! /usr/bin/env python3 import http.server import os import shutil import subprocess import tempfile import threading import unittest class WrapperScriptTests(unittest.TestCase): http_port = 8080 default_download_url = "http://localhost:" + str(http_port) + "/test/testapp.jar" def setUp(self): s...
import unittest import pandas as pd import numpy as np import math from tests.common import AbstractTest from time_blender.coordination_events import Piecewise, Choice, SeasonalEvent, OnceEvent, PastEvent, \ ConcludingValueEvent from time_blender.core import Generator, ConstantEvent, LambdaEvent from time_blender....
import Assignment1SalesApp import unittest class MyTest(unittest.TestCase): """Testing loadData_Bad.txt and whether it is loading into the Model class correctly via get_data""" @mock.patch('builtins.input', side_effect=['11', '13', 'Bob']) def test1(self): #rawdata = 'a0111', should be None ~~ ...
#!/usr/bin/env python3 l=['Luke','Anakin','Palpatine'] for name in l: if name=="Luke": force="light" elif name=="Palpatine": force="dark" else: force="undetermined" print (name,force)
#-*- coding: utf-8 -*- import gensim import pickle import numpy as np import pandas as pd from datetime import datetime from scipy.stats import skew, kurtosis from scipy.spatial.distance import cosine, cityblock, jaccard, canberra, euclidean, minkowski, braycurtis def generate_w2v_distinct(infile,outfile,model): ...
import plotly.express as px import numpy as np import os if not os.path.exists("images"): os.mkdir("images") import logging import boto3 from botocore.exceptions import ClientError def upload_file(file_name, bucket,object_name): if object_name is None: object_name = file_name s3_cl...
import os import json import time import boto3 from EOSS.aws.utils import dev_client, prod_client from EOSS.aws.utils import eval_task_iam_arn, task_execution_role_arn class Task: def __init__(self, dev=False): if dev: self.client = dev_client('ecs') else: self.client = p...
#definir variables print("Ejercicio 15") #Datos de entrada costoP= 0 regaloideal=0 #Proceso dia=int(input("Ponga el dia que dese saber:")) if dia >= 1 and dia <=1: sera="Lunes" elif dia >= 2 and dia <=2: sera="Martes" elif dia >= 3 and dia <=3: sera="Miercoles" elif dia >=4 and dia <=4: sera="Jueves" elif dia ...
# -*- coding: utf-8 -*- """ Created on Fri Sep 13 14:40:44 2019 """ n = int(input("Ingrese n: ")) a = -1 b = 1 for i in range(1, n+1): c = a + b print(c, end=" ") a = b b = c
from theme_10.hospital.h import get_main from theme_10.hospital.patients.index import get_index get_main() get_index()
#!/usr/bin/env python # coding=utf-8 class NoneClass(object): def __init__(self): pass def __repr__(self): return str(None) def __getattr__(self, value): try: #return NoneClass() return NoneClass() except: return NoneClass() s = NoneC...
#!/usr/local/bin/python #-*- coding: utf-8 -* import hashlib import os import requests import click @click.group() @click.option('--debug', '-d', is_flag=True, help="Display debug logs to console") def cli(debug): pass @click.command() @click.option('--input', '-i', required=True, help="input file") @click.opti...
from asyncio.windows_events import NULL import os import string import time import csv import sys from operator import length_hint from sys import flags from os import listdir list_files = listdir(".\\data") print("VF8 LOG INTERPRETER") print("Created by TuongPV4") print("Please wait...........................") pri...
A = [64, 25, 12, 22, 11] for i in range(len(A)): min_p = i for j in range(i+1, len(A)): if A[min_p] > A[j]: min_p = j A[i], A[min_p] = A[min_p], A[i] print(A)
import datetime as dt from decimal import Decimal from unittest.mock import call, patch from typedclass import fields as f from typedclass.core import TypedClass class Entry(TypedClass): f_string = f.String() class Data(TypedClass): f_bool = f.Bool() f_datetime = f.DateTime() f_date = f.Date() ...
#! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Distributed under terms of the MIT license. """ """ import os import fire import glob import numpy as np import pandas as pd import sqlalchemy import yaml import re from sqlalchemy import create_engine from sqlalchemy import MetaData from sqlalchemy ...
import pygame import sys import random def game_over(): pygame.quit() sys.exit() def call(function): return function() def get_randomized_board(settings): """ 生成icon的排列组合 数据结构 """ icons = [] for color in settings.all_colors: for shape in settings.all_shapes: icons.appen...
"""Test if rails file.""" import os import re import platform def syntax_test(file_path): """Check file location and name to determine if a rails file.""" windows = platform.system() == "Windows" is_unc = windows and file_path.startswith("\\\\") if is_unc: unc_drive, path = os.path.splitunc...
# !/usr/bin/python # -*- coding:utf-8 -*- # ----------------------------------------------------------------------------- # Name: lhs.py # Project: Bayesian-Inference # Purpose: # # Author: Flávio Codeço Coelho<fccoelho@gmail.com> # # Created: 2008-11-26 # Copyright: (c) 2008 by the Author # Lic...
from setuptools import find_packages, setup setup( name="nginx_config_reloader", version="20230713.100241", packages=find_packages(exclude=["test*"]), url="https://github.com/ByteInternet/nginx_config_reloader", license="", author="Willem de Groot", author_email="willem@byte.nl", descri...
import uuid from django.db import models from ec.utils import get_filename_ext AD_LOCATION = ( # 注意不要有空格,否则会出现各种乱七八糟的问题 ('carousel', '动态轮播图'), ('personal_center', '个人中心'), ) def ad_image_upload(instance, filename): new_filename = uuid.uuid4() name, ext = get_filename_ext(filename) image_nam...
# COMP9021 19T3 - Rachid Hamadi # Quiz 2 Solution import sys from random import seed, randrange from pprint import pprint try: arg_for_seed, upper_bound = (abs(int(x)) + 1 for x in input('Enter two integers: ').split()) except ValueError: print('Incorrect input, giving up.') sys.exit() seed(...
#!/usr/bin/env python # -*- coding:utf-8 _*- """ @author: wangye(Wayne) @license: Apache Licence @file: Count Ways To Build Good Strings.py @time: 2022/11/12 @contact: wang121ye@hotmail.com @site: @software: PyCharm # code is far away from bugs. """ class Solution: def countGoodStrings(self, low: int, h...
import sys import copy import math """ DON'T FORGET TO ATTRIBUTE CODE """ NUM_PIECES = 4 MAX_DIST = 7 BOARDDIM = 3 NUM_PLAYERS = 3 MAX_DEPTH = 3 _FINISHING_HEXES = { 'red': {(3, -3), (3, -2), (3, -1), (3, 0)}, 'green': {(-3, 3), (-2, 3), (-1, 3), (0, 3)}, 'blue': {(-3, 0), (-2, -1), (-...
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: http://doc.scrapy.org/topics/item-pipeline.html import re import time import json import traceback from scrapy import log from scrapy.conf import settings from scrapy import signals from datetime import timedel...
"""Utils methods to convert XML data to dict from various sources""" import json import requests class JSONReadError(Exception): pass class URLReadError(Exception): pass class StringReadError(Exception): pass def readfromjson(filename: str) -> dict: """ Reads a json string and emits json st...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time :2020年04月07日 # @Author : ghost-guest # @Site : # @File : sendEmail.py # @Software: PyCharm # 说明: #! /usr/bin/python3 import smtplib import baseInfo import time from email.mime.multipart import MIMEMultipart from email.header import Header from email.mi...
#!/usr/bin/env python # encoding : utf-8 # # THIS FILE IS A PART OF SORT ALGORITHMS OF <Introduce to algorithm> # Created by Chen Yuan<cschenyuan@gmail.com> at 08/2016 # import argparse import sys import random import math parser = argparse.ArgumentParser() parser.add_argument('-o','--out-file',help='output file') pa...
import sys from collections import deque input = sys.stdin.readline N,L,R = map(int, input().split()) board = [] for _ in range(N): row = list(map(int, input().split())) board.append(row) def move_people(board): num = 1 global N united = [[0 for _ in range(N)] for _ in range(N)] is_move = ...
from geopy.geocoders import Nominatim from geopy.distance import vincenty geolocator = Nominatim() class GeoUtil: @staticmethod def geocode_location(s): loc = geolocator.geocode(s) if loc is None: return None return { 'display_name': loc.raw['display_name'], 'type': loc.r...
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def nextLargerNodes(self, head): """ :type head: ListNode :rtype: List[int] """ answer ...
''' https://programmers.co.kr/learn/courses/30/lessons/42883 문제 설명 어떤 숫자에서 k개의 수를 제거했을 때 얻을 수 있는 가장 큰 숫자를 구하려 합니다. 예를 들어, 숫자 1924에서 수 두 개를 제거하면 [19, 12, 14, 92, 94, 24] 를 만들 수 있습니다. 이 중 가장 큰 숫자는 94 입니다. 문자열 형식으로 숫자 number와 제거할 수의 개수 k가 solution 함수의 매개변수로 주어집니다. number에서 k 개의 수를 제거했을 때 만들 수 있는 수 중 가장 큰 숫자를 문자열 형태로 ret...
from sympl import ( get_constant, Stepper, initialize_numpy_arrays_with_properties ) import numpy as np class DryConvectiveAdjustment(Stepper): """ Changes the temperature profile if it is super-adiabatic """ input_properties = { 'air_temperature': { 'units': 'degK', ...
List1=[12,2,34,33,67,54] n=List1[0] for m in List1: if m>n: n=m print(m," is the largest element in the list") List1=[12,2,34,33,67,54] n=List1[0] for m in List1: if m>n: n=m print(m," is the largest element in the list") List1=[12,2,34,33,67,54] n=List1[0] for m in List1: if m>n: n=m print(m,...
#Challonge needs to be installed using, pip install, directions listed on website. import challonge def main(): #set credentials and the tournament information. challonge.set_credentials("eliasingea", "LTQX768N8omoYw2aaRYTn6EyP6yVztkaRjd7TBkQ") #show the specific tournament that we would like to get infor...
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('train/', views.train, name='train'), path('download/', views.download, name='download'), path('add/', views.add, name='add'), path('remove/', views.remove, name='remove'), path('lastupda...
import random import os BLOCK_SIZE = 128 def generate_key(): key = [] n = random.randint(0, 0xffffffffffffffffffffffffffffffff) for i in range(int(BLOCK_SIZE/8)): key.append(n&0xff) n >>= 8 id_key = len(os.listdir('../keys')) filename = f'key_{id_key}' with open(f'../keys/{fil...
import datetime class dates(): def __init__(self,protect1,protect2): self.day = "" self.protect1 = protect1 +7 self.protect2 = protect2 +1 def validate(self,date_text): try: datetime.datetime.strptime(date_text, '%Y%m%d') return True except ValueE...
import urllib.parse import re, csv from urllib.request import Request, urlopen, urlretrieve from bs4 import BeautifulSoup as bs, SoupStrainer import wget, os, sys, httplib2, requests, shutil, time # Source: https://stackoverflow.com/a/5251383 def slugify(value): filename = re.sub(r'[/\\:*?"<>|]', '', value) ...
# CCC 2020 Junior 4: Cyclic Shifts # # Author: Charles Chen # # Strings # Input text = input() shift = input() contains_shift = False # Find shifts for i in range(len(shift)): s1 = shift[:i] s2 = shift[i:] shifted_text = s2 + s1 if shifted_text in text: contains_shift = True ...
import csv import json import os import re import time from io import StringIO import psycopg2 import requests from django.http import HttpResponse import wevote_functions.admin from config.base import get_environment_variable from wevote_functions.functions import positive_value_exists logger = wevote_functions.adm...
#!/usr/bin/python # coding=utf-8 import sys import requests import json import time import matplotlib matplotlib.use('Cairo') import matplotlib.pyplot as plot import sys import os import os.path import math import argparse import sys from datetime import datetime import matplotlib.dates as mdates import commands URL ...
# coding=utf-8 import cv2 import random import os import numpy as np from tqdm import tqdm import sys from ulitities.base_functions import get_file seed = 1 np.random.seed(seed) img_w = 256 img_h = 256 image_sets = ['1.png', '2.png', '3.png', '4.png', '5.png'] FLAG_USING_UNET = True segnet_labels = [0, 1, 2] unet...
""" Copyright (C) 2021 Pablo Castells y Alejandro Bellogín Este código se ha implementado para la realización de las prácticas de la asignatura "Búsqueda y minería de información" de 4º del Grado en Ingeniería Informática, impartido en la Escuela Politécnica Superior de la Universidad Autónoma de Madrid. El...
# coding=utf-8 import socket # socket模块 import json import random import numpy as np from collections import deque from keras.models import Sequential, Model from keras.layers import Input, Dense, Conv2D, Flatten, concatenate from keras.optimizers import Adam from math import floor, sqrt import tensorflow as tf import...
# -*- coding:Latin-1 -*- from Tkinter import * # Importation d'un module de fonctions GUI def dessiner_canevas(): ca1 = Canvas(fen, width =700, height =500, background ="grey", border =3, relief ='sunken') ca1.pack(padx =10, pady =5) # mise en place # dessiner la rou...
''' Created on 19/07/2011 @author: darghex ''' from sock import Sock class Server( Sock, object): sock = None ''' Clase para el servidor de tramas ''' def __init__(self): self.getConfig() ''' Abre el socket para dar comienzo a la comunicacion ''' def open(self...
from common import * import numpy as np import concurrent.futures from threading import Lock import time THREADS = 5 # The amount of threads that will run the EA loop concurrently on the same population print_lock = Lock() # Thread lock for the print statements LOWER_BOUND = 1 UPPER_BOUND = 10 NUMBER_LIST = [] POPU...
from ...call_builder.base import BaseOffersCallBuilder from ...call_builder.call_builder_async.base_call_builder import BaseCallBuilder from ...client.base_async_client import BaseAsyncClient from ...type_checked import type_checked __all__ = ["OffersCallBuilder"] @type_checked class OffersCallBuilder(BaseCallBuilde...
from pprint import pprint import sys def bin_pattern(N): '''N is number of binary digit to display - fills with 0 ''' if int(N) < 0: print('Error:: Only positive integer allowed!') sys.exit() fmt = '{:0' + str(int(N)) + 'b}' binary_format_lst = [fmt.format(e) for e in range(2*...
#!/usr/bin/python # -*- coding: utf-8 -*- import bpy from ..rig import RigInfo class MHC_OT_ToSensorRigOperator(bpy.types.Operator): """Transform a default Rig, with or without toes, to one suited for use with the selected device.""" bl_idname = 'mh_community.to_sensor_rig' bl_label = 'Custom Rig Conversi...
class Airplane: def __init__(self, rows, columns): self.row = rows self.col = columns self.seats = [[True for _ in range(columns)] for __ in range(rows)] def seat_taken(self, seat_code): seat = [[0, self.row], [0, self.col]] for i in range(7): if s...
#!/usr/bin/python import sys def compute(prey): temp0 = -1 * prey[0] if temp0 != 0: temp1 = prey[0] % temp0 else: temp1 = temp0 temp2 = prey[0] * prey[1] temp3 = max(prey[1], prey[1]) temp1 = -1 * prey[1] temp0 = max(temp2, temp2) if temp1 > temp3: temp2 = temp0 + temp1 else: if temp1 != 0: temp2 =...
# -*- coding: utf-8 -*- """ Created on Wed May 6 15:30:46 2020 @author: Dan Wilson """ import requests from bs4 import BeautifulSoup import numpy as np import pandas as pd import os import matplotlib.pyplot as plt import time import datetime date = '08-07-2020' page = requests.get("https://raw.git...
from setuptools import setup setup( name='flexipy', version='0.4.2', description='A library for communication with accounting system Flexibee.', packages=['flexipy'], license='BSD', author='Jakub Jecminek', author_email='jecmijak@gmail.com', keywords='flexibee accounting invoices', ...
# https://leetcode.com/problems/minimum-genetic-mutation/ class Solution(object): def minMutation(self, start, end, bank): """ :type start: str :type end: str :type bank: List[str] :rtype: int """ front, back, bank_set, result = { start }, { end }, set(bank), 0 def distance(str1, str2...
class Solution(object): def getImportance(self, employees, id): emps = {employee.id: employee for employee in employees} def dfs(id): subordinates_importance = sum([dfs(sub_id) for sub_id in emps[id].subordinates]) return subordinates_importance + emps[id].subordinates_importance return dfs(id) def getIm...
#!/usr/bin/python from core_tool import * def Help(): return '''Release an object from gripper. Usage: release OBJ_ID OBJ_ID: identifier of object. e.g. 'b1' ''' def Run(t,*args): obj= args[0] if len(args)>0 else t.GetAttr(CURR,'source') if not t.HasAttr(obj,'grabbed'): print 'Error: not grabbed: ',obj...
from django.apps import AppConfig class QuotaMaangerConfig(AppConfig): name = 'quota_maanger'
from environment.battlesnake_environment import BattlesnakeEnvironment, GameMode from agents.RemoteAgent import RemoteAgent from agents.RandomAgent import RandomAgent from agents.FooooodAgent import FooooodAgent import time agents = [ RandomAgent(), RandomAgent(), RandomAgent(), FooooodAgent(), ] env =...
#!/usr/bin/python3 def max_integer(my_list=[]): if len(my_list) == 0: return None big_num = my_list[0] for x in range(len(my_list)): if my_list[x] > big_num: big_num = my_list[x] return (big_num)
# Generated by Django 3.1.2 on 2020-12-02 17:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('employee_page', '0003_delete_profile'), ('homepage', '0011_userprofile'), ] operations = [ migratio...
class Solution(object): def pivotIndex(self, nums): """ :type nums: List[int] :rtype: int """ count = len(nums) left_arr = [] left_sum = 0 for index in range(0, count): left_sum += nums[index] left_arr.append(left_sum) ...
import pytorch_pfn_extras as ppe import torch class DummySharedDataset(ppe.dataset.SharedDataset): def __init__(self): self.data = torch.arange(100).reshape(100, 1) super().__init__(self.data.shape) def __getitem__(self, idx): try: x = super().__getitem__(idx) exce...