text
stringlengths
38
1.54M
# Day 18, Part 1: Operation Order import collections def find_match(expr): stack = collections.deque() idx = expr.index("(") for i, x in enumerate(expr): if x == "(": stack.appendleft((i, x)) elif x == ")": stack.popleft() if not stack: ...
from __future__ import print_function from netmiko import ConnectHandler import sys import time import select import paramiko import re fd = open(r'C:\Users\J0000049\NewdayTest.txt','w') old_stdout = sys.stdout sys.stdout = fd platform = 'cisco_ios' username = 'admin-j0000049' password = 'xxxxx' ip_add_file = open(r...
import py_compile import sys try: print(py_compile.compile(sys.argv[1])) except IndexError as e: raise e
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import streamlit as st from smart_hr.data import load_data as load from smart_hr.data.dismissal import load as load_dismissal from smart_hr.data.activity import load as load_activities @st.cache def load_data(data_dir, models_dir): ''' ''' excel_f...
from django.db import DataError from drf_standardized_errors.formatter import ExceptionFormatter from drf_standardized_errors.handler import ExceptionHandler from drf_standardized_errors.types import ErrorResponse, ErrorType from metering_billing.exceptions.exceptions import DatabaseOperationFailed class CustomHandl...
""" ISCG5421 Practice Test - Semester 2 2020 Kris Pritchard - @krp pytest -v test_contact_tracer.py """ import pytest import contact_tracer def test_that_location_id_is_added_to_visited_set(): brown = contact_tracer.Person('brown@unitec.ac.nz') brown.visit(123) assert 123 in brown.visited def test...
from marshmallow import * from ..utils import * # ===================================================================== # Report class Report(Schema): class Meta: dateformat = ('iso') fields = ('day', 'count') class Problems(Schema): class Meta: fields = ('branch_indiference'...
import heapq class Huffman(object): def __init__(self, freq, char=None, left=None, right=None): self.char = char self.freq = freq self.left = left self.right = right def __repr__(self): return "Huffman(char=%s, freq=%s)" % (self.char, self.freq) # need...
#!/usr/bin/env python3 from abc import ABC, abstractmethod from functools import wraps from typing import Callable class Parameter(ABC): def __init__(self, i_0: int, c: float, d: float, kappa: int, omega: int, **kwargs): """ Every model involves the same mutation model (for now). This involves the paramet...
from operator import attrgetter class PostSort: def select_sort_method(self, sort_id, post_collection): if sort_id == "1": return self.sort_latestPost(post_collection) elif sort_id == "2": return self.sort_oldestPost(post_collection) elif sort_id == "3": ...
import os import re import numpy as np import swr est = re.compile('estimated',re.IGNORECASE) xsec_files = os.listdir('xsec\\') for xf in xsec_files: if est.search(xf) != None: h,xsec = swr.load_xsec('xsec\\'+xf) raw = h[0].split() npt,x,y,area = int(raw[-4]),float(raw[-3]),f...
#!/usr/bin/python def palindrome (n) : s = str(n) for i in range(len(s)/2) : if s[i] != s[-(i+1)] : return 0 return 1 # print palindrome (22) # print palindrome (23) # print palindrome (202) # print palindrome (2002) l = 0 for a in range (100,1000) : for b in range (100,1000) : prod = a*b if palindrome...
import math import os.path import random random.seed() from sklearn import tree from sklearn.ensemble import RandomForestClassifier import numpy as np import pandas as pd import plotly.plotly as py import plotly.graph_objs as go import pydotplus from IPython.display import Image import input_old import cPickle ...
# coding: utf8 from __future__ import absolute_import, unicode_literals def make_response(info='error', code=1, extra={}): res = { 'code': code, 'info': info, } res.update(extra) return res def success_response(info, extra={}): res = { 'code': 0, 'info': info, ...
# Define variables my_kitchen = 18.0 your_kitchen = 14.0 # my_kitchen bigger than 10 and smaller than 18? print(my_kitchen>10 and my_kitchen<18) # my_kitchen smaller than 14 or bigger than 17? print(my_kitchen<14 or my_kitchen>17) # Double my_kitchen smaller than triple your_kitchen? print((my_kitchen*2)< (your_kitc...
# Tony Liang and hari Shanmugaraja # Feb 9 2020 # read in text file for lidar and text file for car motor and steering and match them up # sample line # 1581083570.228828 b'8597 1407\r\n' # # # Ultra simple LIDAR data grabber for RPLIDAR. # Version: 1.10.0 # 1582122195.06 # RPLIDAR S/N: BE9B9AF2C1EA98D4BEEB9CF031483517...
import base64 import json import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from gapc_storage.storage import GoogleCloudStorage from oauth2client.client import SERVICE_ACCOUNT from oauth2client.service_account import ServiceAccountCredentials class ECGoogleCloudStora...
#!/usr/bin/env python3 import os import subprocess import urllib.request pb_files = [ 'proto/message.proto', ] for f in pb_files: subprocess.check_call([ #os.path.join(self.getdir(), 'generator-bin', 'protoc'), 'protoc', '--proto_path=proto', '--python_out='+os.path.join('src',...
import csv products = [[121, 'ABC123', 'Highlight pen', 231, 0.56], [123, 'PQR678', 'Nietmachine', 587, 9.99], [128, 'ZYX163', 'Bureaulamp', 34, 19.95], [137, 'MLK709', 'Monitorstandaard', 66, 32.50], [271, 'TRS665', 'Ipad hoes', 155, 19.01]] with open('products.csv', '...
from appliances import DishWasher, Washer, Dryer, Refrigerator, CoffeeMaker, CanOpener, Stove whirlpool_dishwasher = DishWasher("black") whirlpool_dishwasher.wash_dishes() samsung_washer = Washer("red", "electric") samsung_dryer = Dryer("red", "gas") lg_fridge = Refrigerator("stainless") lg_fridge.make_ice() mr_cof...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
from django.views.generic import ListView, DetailView, FormView, CreateView, UpdateView from webapp.models import Article, User, Comment from webapp.forms import ArticleSearchForm, ArticleForm, CommentForm, UpdateCommentForm from django.urls import reverse_lazy, reverse from django.shortcuts import get_object_or_404 ...
# -*- coding: utf-8 -*- import json from typing import Any, Dict, Mapping from mock import patch from u2flib_server.model import DeviceRegistration, RegisteredKey from eduid_common.api.testing import EduidAPITestCase from eduid_userdb.credentials import U2F from eduid_webapp.security.app import SecurityApp, securi...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Sep 7 15:58:26 2020 @author: fred """ greeting = "Guten Morgen" a = greeting[2:5:1].upper() print(a) racetrack = "RaceTrack" b = racetrack[1:4:1].capitalize() print(b) summer = "summer" c = summer.replace("umm", "inn").capitalize() print(c)
# Mariska de Vries # 223751 # Vragen om de prijs van het toegangs kaartje toegangsprijs = int(input("Wat is de prijs van het toegangskaartje: ")) # Vragen om de leeftijd leeftijd1 = int(input("Wat is uw leeftijd: ")) leeftijd2 = int(input("Wat is uw leeftijd: ")) leeftijd3 = int(input("Wat is uw leeftijd: ")) ...
# Generated by Django 2.2 on 2019-05-22 22:14 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] opera...
def age_assignment(*args, **kwargs): dic = {} for name in args: dic[name] = "" for n, age in kwargs.items(): if n == name[0]: dic[name] = age return dic print(age_assignment("Amy", "Bill", "Willy", W=36, A=22, B=61))
from mnist import * from spect import * import numpy as np # Perceptron Settings GLOBAL_EPOCH = 1 RATE = 1 # Kernel Settings DEGREE = 1 def linear(x, z): return x.dot(z) def poly_kernel(x, z, d=DEGREE): return x.dot(z)**d KERNEL = poly_kernel # Helper Functions === def sign(x): if x < 0: return -1 else: retur...
# from .off_policy_algorithm import OffPolicyAlgorithm from .softq_controller import SoftQMPC # from .sac_mpc import SACMPC __all__ = ["SoftQMPC"] #, "SACMPC"]
"""OmniSciDB test configuration module.""" import os import typing import pandas import pytest import ibis import ibis.util as util OMNISCIDB_HOST = os.environ.get('IBIS_TEST_OMNISCIDB_HOST', 'localhost') OMNISCIDB_PORT = int(os.environ.get('IBIS_TEST_OMNISCIDB_PORT', 6274)) OMNISCIDB_USER = os.environ.get('IBIS_TES...
from sys import argv, exit from PyQt5.QtWidgets import QApplication, QMainWindow from ui.hat_recognization import Ui_MainWindow if __name__ == '__main__': app = QApplication(argv) window = QMainWindow() ui = Ui_MainWindow(window) window.show() exit(app.exec_())
# region import from odo import odo from sqlalchemy.sql.expression import bindparam from base import * from celery_create import celery from enrollment import ObservationPeriod, Enrollment # endregion def init_pedsnet(connection): pedsnet_schema = connection.pedsnet_schema # override the placeholder schemas ...
import json from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ from wagtail.admin.widgets import AdminChooser from wagtail.documents.models import get_document_model class AdminDocumentChooser(AdminChooser): choose_one_text = _('Choose a document') ch...
set encoding iso_8859_1 load 'Colours.py' set autoscale unset label set linestyle 1 lt 2 lw 1 set key box linestyle 1 lc 7 set key width 0.5 height 0.75 set key top right set xtic auto set ytic auto set title "Diametrically Opposed Zn Distances at 270K" font "Times-Roman,14" set ylabel "Distances (\305)" set xlabel ...
num_of_books_in_total = int(input()) books_arr = [0]+list(map(int,input().split())) no_of_borrowed_books = int(input()) for _ in range(no_of_borrowed_books): id = int(input()) print(books_arr.pop(id))
#!/usr/bin/env python """ chtml.py: Replacing img urls for html file. __author__ = "chaung.li" """ from re import compile from shutil import copyfile from json import load def backup(filename): file_name = filename + '.bak' copyfile(filename, file_name) print(f'{file_name} Backup done!') def dic(): ...
#!python # -*- coding: utf-8 -*- """ Skyspark Client support """ import hszinc from six import string_types from .session import HaystackSession from .ops.vendor.skyspark import SkysparkAuthenticateOperation from .ops.vendor.skyspark_scram import SkysparkScramAuthenticateOperation from .mixins.vendor.skyspark import e...
#A strategy that buys stocks when market is not too bad and holds stock if its price doesn't exceed the threshold. import decision from collections import deque #Constants that determines buy decision MAX_DROP_PERCENTAGE_PER_DAY = 2 MAX_DROP_PERCENTAGE_PER_WEEK = 3 MAX_DROP_PERCENTAGE_PER_THREE_WEEK = 5 #Constants th...
import subprocess, os word = '3' while not word.isalpha(): word = input("Enter your word of choice: ") if not word.isalpha(): print("Not a valid word bud. Go ahead and try again.\n") print("\n" * 50) cls = os.system("CLS") pinataCounter = 0 won = False lettersGuessed = [] def printPinata(n): prin...
# Generated by Django 3.1.3 on 2020-11-22 10:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('library', '0015_auto_20201122_1601'), ] operations = [ migrations.AlterField( model_name='profile', name='borrow_dat...
import subprocess from evdev import InputDevice, ecodes mpc_status = "mpc status".split() mpc_random = "mpc random on".split() mpc_clear = "mpc crop".split() mpc_FUNK = "mpc add FUNK/".split() mpc_JAZZ = "mpc add JAZZ/".split() mpc_ROCK = "mpc add ROCK/".split() mpc_ROCK_NOUV = "mpc add ROCK_NOUV/".split() mpc_Play = ...
# coding: utf-8 from django.db import models from django.utils.translation import ugettext_lazy as _ class WeightedModel(models.Model): """ Objet ayant un poids, les poids les plus faibles sont en surface """ # Constantes WEIGHTS = ((x, x) for x in range(0, 100)) # Champs weight = models.SmallInte...
#!/usr/bin/python # -*- coding: utf-8 -*- from __future__ import division from __future__ import unicode_literals #from __future__ import print_function #from __future__ import absolute_import __author__ = 'Marco Antonio Pinto-Orellan' from pypro import * if __name__ == "__main__": CommonProject().main()
from collections import defaultdict import logging from matplotlib import pyplot as plt import numpy as np import time from networkx import DiGraph, Graph import networkx as nx from typing import List, Tuple, Optional import drawing from hull import quickhull from independentset import planar_independent_set from pol...
from django.shortcuts import render, get_object_or_404, get_list_or_404 from django.http import HttpResponse, Http404, HttpResponseRedirect from django.core.urlresolvers import reverse from models import MyUser, Tag, Entity, Review, Vote, Criteria_Teacher, Criteria_Uni from collections import defaultdict from django.co...
# Lists in Python # Lists are one of the most powerful tools in python. # They are just like the arrays declared in other languages. # But the most powerful thing is that list need not be always homogeneous. # A single list can contain strings, integers, as well as objects. # Lists can also be used for implementin...
#user_maker.py __author__='''Shivek Khurana''' __version__='''01.12.04.2010 | read as version.day.month.year''' __doc__='''Description : Create a dictionary named users, and add functionality to add, remove a user.''' uname={'shivek':'shivekk@gmail.com','mehak':'mehak@ls.com'} def username_input(): '''New user ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ LICENSE FOR USING PYSWIP Copyright (c) 2007-2018 Yüce Tekol 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 withou...
from setuptools import setup setup( name='security-webcam', version='0.1', author='Hsuan-Hau Liu', description='Simple security camera system right on your computer.', url='https://github.com/hsuanhauliu/security-webcam', packages=['security_webcam',], package_dir={'security_webcam': 'src/s...
# Generated by Django 2.0.5 on 2018-05-31 13:07 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0006_auto_20180531_1458'), ] operations = [ migrations.AddField( model_name='post', name='description', ...
''' import os filelist=os.listdir(r"C:\\Users\\ehuamay\\Desktop\\pm_report_tags") #print(filelist) for file in filelist: if os.path.isdir("C:\\Users\\ehuamay\\Desktop\\pm_report_tags\\"+file): print("文件夹", file) else: print("文件", file) ''' import os def getall(path): filelist=os.listdi...
import enum from botmanlib.models import Database, BaseUser, UserPermissionsMixin, BasePermission, BaseUserSession, UserSessionsMixin from sqlalchemy import Column, Float, Integer, Enum, String, ForeignKey, DateTime from sqlalchemy.orm import object_session, relationship database = Database() Base = database.Base c...
from flask.ext.wtf import Form from wtforms import StringField, PasswordField, validators from wtforms.fields.html5 import EmailField from wtforms.validators import Required class LoginForm(Form): user_name = StringField('user_name', [validators.Required()]) user_password = PasswordField('Password', [validator...
""" 首先谈到这个语言的定义和运行原理 该语言定义在这样一个环境之上: 你有一列无限长的小火车,每个车厢里装了一个数字,初始为0。 还有一个列车员,初始在最头上那节车厢上。 好了,你把你写的BrainFK程序交给列车员,列车员会做如下的事情: 从左向右、由上自下一个字符一个字符地读取你的程序 当读到`+`的时候,将所在车厢里的数字加一 当读到`-`的时候,将所在的车厢里的数字减一 当读到`>`的时候,跑到后一个车厢去 当读到`<`的时候,跑到前一个车厢去 当读到`[`的时候,如果该车厢里面的数字为0,则跳去执行下一个`]`之后的程序内容 当读到`]`的时候,如果该车想里面的数字不为0,则跳去执行上一个`[`之后的程序内容 当读到`...
from __future__ import division import warnings import sys sys.path.extend(['..', '../..']) with warnings.catch_warnings(): warnings.filterwarnings("ignore") from matplotlib import pyplot, rc, cm, font_manager from matplotlib.mpl import colorbar from matplotlib.ticker import MultipleLocator from cog...
from django.core import mail from django.test import TestCase from django.shortcuts import resolve_url as r from eventex.subscriptions.forms import SubscriptionForm from eventex.subscriptions.models import Subscription class SubscriptionsNewGet(TestCase): def setUp(self): self.resp = self.client.get(r('s...
import sys import io import os import json import time import classify_utils from subprocess import * import subprocess import re # argv[1] - filename to process # using https://pypi.org/project/LatvianStemmer/1.0.1/#files # processed file is saved in the same dir as source as filename_stemmed.tsv def main(): fi...
from typing import List import collections class RLEIterator: def __init__(self, encoding: List[int]): self.encode = collections.deque(encoding) def next(self, n: int) -> int: while self.encode: if self.encode[0] < n: n -= self.encode.popleft() ...
from tkinter import * def do_some_action(): if choosen.get() == 'czerwony': button["background"] = 'red' else: button["background"] = 'yellow' root = Tk() root.title("Radiobuttons") root.geometry("250x150") choosen = StringVar() # klasa nalezaca do tkinker, sluzy do prezchowywania...
class Feature_Coding: def __init__(self): self.featuresAll = ['TimeStamp', 'Symbol', 'Exchange', 'Type', 'PeriodCode', 'EventId', 'EventCode', 'EventDir', 'Price', 'VWAPP', 'Open', 'High', 'Low', 'Close', 'Volume', 'PIR5m', ...
import pandas as pd import numpy as np import string import random import torch def split_data(data): split_data = [] for string in data: split_space = string.split() for i, word in enumerate(split_space): split_data.append(word) return split_data def y_train_make(n): sp = ...
# -*- coding: utf-8 -*- """ Created on Tue May 14 12:23:47 2019 @author: Felix De Mûelenaere """ ############################################################################## ########################### Generating test images ########################### ##### from MSK gopro videos ...
#!/usr/bin/env python3 # pylint: disable=C0114 import os import sys try: # pylint: disable=W0632 proxy, token, roomName = sys.argv[1:] except ValueError: print('Command arguments: {} <user> <password> <proxy>'.format( os.path.basename(sys.argv[0])) ) sys.exit(1) _COMMAND_ = './ClientServe...
#!/usr/bin/python #coding=utf-8 class CookieStoreBase: def getCookie(self, url): raise NotImplementedError def setCookie(self, url, cookie): raise NotImplementedError
import requests url = 'https://mars.se-pro.site' class Blogger: url = 'https://mars.se-pro.site' def __init__(self, full_name): blogger_data = { 'full_name': full_name } response = requests.post(f'{self.url}/bloggers/', data=blogger_data) # print(response.status_co...
from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from PIL import Image from aesthetic_computation.models import Post, Category # custom error handlers def handler404(request, *args, **argv): return render(request, 'ac/404.h...
from sqlalchemy import create_engine, MetaData, Table, Integer, String, Column, DateTime, ForeignKey, \ Text, insert, select, func from sqlalchemy.exc import SQLAlchemyError from datetime import datetime from itertools import chain from multiprocessing import Pool import logging import parsers import config metada...
class Greeter: def __init__(self): pass def speak(self, name): print("Hello", name)
from Dishes import * class Plate(Dishes): def __init__(self, dishesType, material, diameter, dishName): self.dishesType = dishesType self.material = material self.diameter = diameter self.dishName = dishName
from enemyshooter import EnemyShooter from enemybullet import EnemyBullet class ShooterFleet(): def __init__(self, row_count, column_count, initial_speed, enemy_img, starting_xcor, starting_ycor): self.direction = 0.5 self.speed = initial_speed self.ships = self.get_initial_ships(row_count, ...
import sys import zmq import json import uuid class Server: def __init__(self, usr): self.usr = usr self.table = '' ### ZMQ Initialization ### ctx = zmq.Context() self.pubsrv = ctx.socket(zmq.SUB) self.pubsrv.connect('tcp://127.0.0.1:5556') self.pubsrv.set...
import pickle import tensorflow as tf from sklearn.model_selection import train_test_split # from sklearn.cross_validation import train_test_split from alexnet import AlexNet import numpy as np from sklearn.utils import shuffle import time # TODO: Load traffic signs data. with open("train.p", mode='rb') as f: trai...
def main(): import matplotlib.pyplot as plt import numpy as np with open('avg1.list') as avg1_list: avg1 = avg1_list.read() avg1 = avg1.split() avg1 = [float(item) for item in avg1] seconds = np.arange(5, avg1.__len__() * 10 + 5, 10) fig, ax = plt.subplots() plt.plot(seconds, avg...
# Copyright (c) 2018, Red Hat, Inc. # All Rights Reserved. # # 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 requir...
import socket import sys import os host = '192.168.10.1' port = 9999 ADDR = (host, port) def create(): global session session = socket.socket(socket.AF_INET, socket.SOCK_STREAM) def connect(): try: session.connect(ADDR) print("[+]Connection is build up") except: ...
#TO RUN: joey2 project_operation_tests.py import sys import os import unittest import shutil sys.path.append('../') import lib.config as config import lib.mm_util as util import test_helper as helper from lib.mm_connection import MavensMatePluginConnection from lib.mm_client import MavensMateClient class TestProject...
import numpy as np import numpy.random as npr import matplotlib.pyplot as plt plt.close('all') plt.rcParams.update({'font.size': 12}) plt.rcParams['font.family'] = 'sans-serif' # Load the training history, calulate stats, then plot hist = np.load('hist_train.npy') print('\n'+"TRAINING:_____________") print("AVERAGE S...
# -*- coding: utf-8 -*- """ Created on Sun Jul 21 17:14:23 2019 @author: smorandv """ import numpy as np import pandas as pd import matplotlib.pyplot as plt def rm_ext_and_nan(CTG_features, extra_feature): """ :param CTG_features: Pandas series of CTG features :param extra_feature: A feat...
from unittest import TestCase from p17.Solution import Solution class TestSolution(TestCase): def test_letterCombinations(self): sol = Solution() self.assertEqual([], sol.letterCombinations("")) self.assertEqual(["a", "b", "c"], sol.letterCombinations("2")) self.assertEqual(["d"...
import grpc import poetry_pb2 import poetry_pb2_grpc import poetry_gen from concurrent import futures import grpc if __name__ == '__main__': gen = poetry_gen.FullModel() print(gen.predict("poop")) class GeneratePoetryServicer(poetry_pb2_grpc.GeneratePoetryServicer): """Provides methods that implement functionalit...
class Solution: def minDistance(self, word1: str, word2: str) -> int: l1 = len(word1) l2 = len(word2) dp = [[-1 for _ in range(l2 + 1)] for _ in range(l1 + 1)] for i in range(l2 + 1): dp[0][i] = i for j in range(l1 + 1): dp[j][0] = j for i in r...
import xmlrpclib import sys import random import time def randint(): return random.randint(2**29, 2**30) proxy = xmlrpclib.ServerProxy("http://{0}:10010/".format(sys.argv[1])) starttime = time.time() ctime = time.time() c = 0 print int(ctime*1000), c while ctime - starttime < 60.0: a = randint() b = randint() r...
# -*- coding: utf-8 -*- # # Copyright 2016 Capital One Services, LLC # # 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 ...
# -*- coding: utf-8 -*- n = int(raw_input()) p = set(filter(lambda x: x, map(int, raw_input().split(' '))[1:])) q = set(filter(lambda x: x, map(int, raw_input().split(' '))[1:])) if len(p | q) >= n: print('I become the guy.') else: print('Oh, my keyboard!')
from django.apps import AppConfig class PolideportivoConfig(AppConfig): name = 'polideportivo'
import requests import base64, hashlib, hmac, time from requests.auth import AuthBase import json def products(): # sandbox api base api_base = 'https://api-public.sandbox.gdax.com' response = requests.get(api_base + '/products') if response.status_code is not 200: raise Exception('Invalid GDAX...
Testcase = eval(input()) for i in range(Testcase): enemy = [] guyeok, W = map(int,input().split()) enemy.append(list(map(int,input().split()))) enemy.append(list(map(int,input().split()))) chk = [0 for _ in range(guyeok*2)] hap = 0 orders = [] chk = [0 for _ in range(guyeok*2)] ...
from __future__ import absolute_import, unicode_literals from django.db import models from django import forms from wagtail.wagtailcore.models import Page from wagtail.wagtailcore.fields import StreamField from wagtail.wagtailadmin.edit_handlers import FieldPanel, StreamFieldPanel from wagtail.wagtailcore.blocks imp...
class Vrtx: def __init__(self, n): self.name = n self.data = {} self.data['neighbours'] = list() self.data['edges'] = list() def add_neighbours(self, v): if v not in self.data['neighbours']: self.data['neighbours'].append(v) self.data['neighbour...
n_sets = int(input()) for _ in range(n_sets): x, y = map(int, input().split()) delta = x - y if delta != 1: print("YES") else: print("NO")
import pytest from long_running.notification_mixins import ( ASGINotificationMixin, NullNotificationMixin, ) @pytest.fixture def fake_rekord(): class FakeRekord(ASGINotificationMixin): pk = 500 return FakeRekord() def test_ASGINotificationMixin_asgi_channel_name(fake_rekord): assert fa...
import datetime from project import app from project.models import db # Id Expression # 1 = netral, 2 = bahagia, 3 = sedih, 4 = terkejut class Expression(db.Model): __tablename__ = 'expression' id_expression = db.Column(db.Integer, primary_key=True) expression_name = db.Column(db.String(20), nullable=Fa...
#!/usr/bin/env python # # FFF - Flexible Force Field # Copyright (C) 2010 Jens Erik Nielsen # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your optio...
# -*- coding: utf-8 -*- from openerp import models, fields, api from openerp.exceptions import except_orm from datetime import datetime from openerp.tools.translate import _ import openerp.addons.decimal_precision as dp class panipat_crm_lead(models.Model): _name = "panipat.crm.lead" _rec_name = 'sequence' ...
from django.db import models from django.utils.safestring import mark_safe from image_cropping import ImageRatioField from easy_thumbnails.files import get_thumbnailer # Create your models here. class Page(models.Model): title = models.CharField(max_length=250) content = models.TextField() class Category(mode...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Kalman filter implementation. 1. Bicycle model 2. Unicycle model """ import numpy as np import math class Filter(object): def __init__(self, debug=False): self.debug = debug self._X = None self._P = None self._Q = None ...
import os from dispatch import * exe = read_executable('thing') exe.analyze() main = exe.function_named('_main') ins = None for i in main.instructions: if i.mnemonic == 'jne': ins = i break exe.replace_instruction(ins, '') exe.save('patched') os.system("chmod +x patched")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #TFC輸入カバーのメニュー from tfc_cover import TfcCover tc = TfcCover() menu_line =""" 1)検索コード 2)検索番地 3)ロケーション指示 (output) 4)ロケーション指示 (表示/印刷) 5)更新 6)cover_zaiko.csv 書き出し (在庫報告用) 7)修正データ読み込み(stockフォルダのrevから始まるファイル) 8)保存 9)emptyラック書き出し(data/empty_rack.csv) 10)到...
import tensorflow as tf x_data = [[10, 20, 30], [40, 50, 15], [25, 35, 45], [55, 13, 23], [33, 43, 53]] y_data = [[50], [60], [70], [80], [75]] X = tf.placeholder(tf.float32, shape=[None, 3])#None = n, 즉 원하는 만큼 쓸수있음 Y = tf.placeholder(tf.float32, shape=[None, 1]) W = tf.Variable(tf.random_normal([3,1]), name='weight...
""" 39. Combination Sum Medium 2619 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 num...