text
stringlengths
38
1.54M
#!/usr/bin/python3 """ Here, the class FileStorage that serializes instances to a JSON file and deserializes JSON file to instances """ import json import os.path class FileStorage(): """ Initialization of class attributes """ __file_path = "objects_info.json" __objects = {} def all(self): "...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-04-27 08:32 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('prodsys', '0006_auto_20170426_0456'), ] operations = [ migrations.AddField( ...
import numpy as np # Initialisation - Parameters from question k = 2 # Number of clusters to form centers = { # Initial clusters' centers 0: [-1, 3], 1: [5, 1], } x = np.array([ # Dataset [-1, 3], [1, 4], [0, 5], [4, -1], [3, 0], [5, 1] ]) try: assert(k == len(centers)) except A...
# These dictionaries are merged with the extracted function metadata at build time. # Changes to the metadata should be made here, because functions.py is generated thus any changes get overwritten. # By default all functions in functions.py are "public". # This will override that with private (prefixes name with '_')...
from pathlib import Path from time import time class struct(dict): __getattr__, __setattr__ = dict.__getitem__, dict.__setitem__ pb = {"a_example": 21, "b_read_on": 5831900, "c_incunabula": 2361663, "d_tough_choices": 5033860, "e_so_many_books": 4511113, "f_libraries_of_the_world": 4998006} def main(): fo...
#Division Function: given two numbers returns quotient of the first number divided by the second number def division(num1, num2): return num1/num2 print division(42, 7) def greeting(self): print 'Hi There','+self+','!' greeting ("Susan"); print 'Greetings', '+self+', '!' greeting("Earthling") def...
# -*- coding: utf-8 -*- """ Created on Sun Jan 10 11:07:22 2021 @author: dhruv """ import sys print("Welcome to your todo list!") tasks = [] while True: print("What would you like to do with your todo list?\n") print("1. Add a task") print("2. Remove a task") print("3. Exit a task") i =...
resp='S' soma = quantidade = media= 0 while resp in 'Ss': num = int(input('Entre com um número:')) soma+= num quantidade +=1 resp=str(input('Quer continuar?[S/N]')).upper().strip()[0] media=num//quantidade print(f'Você digitou {quantidade} números e a Média foi {media}')
from configdb.meta import app from flask import make_response class DecodeException(Exception): pass class InvalidPath(Exception): pass class NotALeaf(Exception): """trying to access a branch node in leaf context""" pass class HttpException(Exception): def __init__(self, message, code=400, *...
import os os.environ["KMP_BLOCKTIME"] = "0" os.environ["KMP_AFFINITY"] = "granularity=fine,verbose,compact,1,0" import tensorflow as tf import time from dataset import Dataset from model import FloWaveNet from hparams import hparams import argparse import numpy as np from utils import fp16_dtype_getter, average_gradie...
#SOS import RPi.GPIO as GP,time GP.setmode(GP.BOARD) GP.setup(11,GP.OUT) #Defining dot def dot(): GP.output(11, True) time.sleep(0.5) GP.output(11, False) time.sleep(0.5) dot() #Defining dash def dash(): GP.output(11, True) time.sleep(2) GP.output(11, False) time.sleep(0.5) dash() #Def...
LANGUAGE = { 'cpp' : 0, 'java' : 1, 'python' : 2 } PART = { 'backend': 0, 'frontend': 1 } CAREER = { 'junior': 0, 'senior': 1 } SOUL = { 'pizza': 0, 'chicken': 1 } db = [[[[[] for _ in range(2)] for _ in range(2)] for _ in range(2)] for _ in range(3)] def binary_search (target, l...
import requests # Globals and Constants SOLR_URL = 'https://solr-dev.monarchinitiative.org/solr/golr/select' def main(): result_docs = get_causal_disease_gene_assocs() get_disease_phenotype_list(result_docs) for key, value in result_docs.items(): print("{}\t{}\t{}\t{}\t{}".format( ...
from django.core.validators import MaxValueValidator,MinValueValidator,EmailValidator from django.db import models class User(models.Model): name=models.CharField(max_length=100) age=models.IntegerField(blank=True,null=True,validators=[MaxValueValidator(150),MinValueValidator(0)]) email=models.CharField(max_length=...
import numpy as np from sklearn.linear_model import SGDClassifier clf = SGDClassifier(loss="log", alpha=0.1, max_iter=100, shuffle=True, fit_intercept=True) classes = [] def strtonum(x): if x not in classes: classes.append(x) return classes.index(x) data = np.loadtxt("./iris.data", delimiter=',', con...
# -*- coding: utf-8 -*- """ Created on Thu Jun 11 23:41:56 2020 @author: aakan """ from keras.models import load_model #from keras.models import Sequential #import cv2 import numpy as np #import os import argparse from PIL import Image ap = argparse.ArgumentParser() ap.add_argument("-i","--image",required = True,help...
import threading from config import processing_unit import csv import pyOpenBCI class EEGStreaming(processing_unit): def __init__(self, file_queue): super().__init__() self._file_queue = file_queue self._stream_data = [] self._board = pyOpenBCI.OpenBCICyton(daisy=True) self....
import os class EnvironConfig: APP_ENVIRONMENT = os.environ.get("APP_ENVIRONMENT", "DEVELOPMENT") FLASK_APP_SECRET = os.environ.get("FLASK_APP_SECRET", "thisissecrectkey")
import sys import os import pandas as pd import csv import matplotlib.pyplot as plt plt.switch_backend('agg') import networkx as nx import spaligner_parser from gfa_parser import gfa_to_G import graphs import clustering def tsv_to_sets(tsv, min_component_size=3): clusters = set() with open(tsv, 'r') as f...
from aiohttp import web from aiohttp_example import signals from aiohttp_example.apps.say_hello.views import say_hello_handler def init_app(argv: list[str]) -> web.Application: app = web.Application() app.add_routes([ web.get('/', say_hello_handler), web.get('/{name}', say_hello_handler), ...
import sys,os def get_file(name): fn = '%s\\%s.jack' % (sys.path[0],name) if os.path.isfile(fn): return open(fn,"r") if __name__ == '__main__': #n = input('File/Folder name:') n = "Square" f = get_file(n) if not f: sys.exit() comment = False for line in f: pos,length = -1,len(line)-1 s...
# from this tutorial # https://medium.com/emergent-future/simple-reinforcement-learning-with-tensorflow-part-1-5-contextual-bandits-bff01d1aad9c import tensorflow as tf import numpy as np import tensorflow.contrib.slim as slim learn_rate = 0.001 total_episode = 10000 e = 0.1 class ContextualBandit(): def __init...
import numpy as np from PIL import Image as pil import matplotlib.pyplot as plt from scipy.optimize import curve_fit data = np.array(pil.open("original.bmp")) data = data/np.max(data) x,y=np.meshgrid(np.linspace(0,data.shape[1],data.shape[1]),np.linspace(0,data.shape[0],data.shape[0])) def twoDgaussian(X,wx,wy,x0,y0...
__author__ = 'thorwhalen' def show(d, nlines=None, cols=None): if nlines is None: nlines = len(d) if cols is None: cols = d.columns if isinstance(cols, str): cols = [cols] print(d[:nlines][cols].to_string()) def sw(df, up_rows=10, down_rows=5, left_cols=4, right_cols=3, retur...
# coding=utf-8 """ There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)). """ class Solution: # @param {integer[]} nums1 # @param {integer[]} nums2 # @return {float} @staticmethod ...
# Generated by Django 2.0.5 on 2018-10-24 05:55 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('onlineapp', '0002_studentscore'), ] operations = [ migrations.CreateModel( name='Question', fields=[ ...
import peewee from models import Supplier, Goods from data import supplier_list, goods_list def save_model(): for supplier in supplier_list: supplier_obj = Supplier() supplier_obj.name = supplier["name"] supplier_obj.address = supplier["address"] supplier_obj.phone = supplier["pho...
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pathlib import Path from pants.testutil.pants_integration_test import PantsIntegrationTest, ensure_daemon from pants.util.contextutil import temporary_dir class SchedulerIntegratio...
import os.path import pickle class Rank: def __init__(self): self.file = "rank.dat" if os.path.isfile(self.file): f = open('rank.dat', 'rb') flist = pickle.load(f) f.close() else: flist = [] self.ranklist = flist def save(self): ...
import requests from bs4 import BeautifulSoup as b_soup from random import randint txt_file = '/home/marc/git/onid/sudoku.txt' scrp_url = 'https://nine.websudoku.com/?level=' def get_diff(d): d = int(d) if d == 1: return 'easy' if d == 2: return 'medium' if d == 3: return 'ha...
from dateutil import parser as DateParser from config.database import db from utils.log import logger_set from exceptions.device import * from exceptions.account import * import random import string import jwt import hashlib import datetime import base64 from config.log import LOG_DATABASE_FILE logger = l...
from django.shortcuts import render, get_object_or_404 from django.contrib.auth.models import User from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated, IsAdminUser from rest_framework.response import Response from base.models import Brand, CarModel...
# WAP to implement bank account class which supports Deposit and Withdraw methods. # -[Hint] Auto generate account number, by taking one class attribute class BankAccount: accountNumber = 1 minAccountBalance = 1000 def __init__(self, initialBalance): self.__balance = initialBalance self._...
import pandas as pd previsores = pd.read_csv('entradas-breast.csv') classe = pd.read_csv('saidas-breast.csv') from sklearn.model_selection import train_test_split previsores_treinamento,previsores_teste,classe_treinamento,classe_teste = train_test_split(previsores,classe,test_size=0.25) import keras from ke...
# -*- coding: utf-8 -*- """ Created on Wed Apr 15 21:55:26 2020 @author : """ class State : color_dict = dict() current_level = list() #shows how the level looks currently goal_level = list() #shows how the goal level looks GoalDependency = dict() #dictionary of dependent goal locations .. {loca...
from setuptools import setup, find_packages with open('requirements.txt') as f: install_requires = f.read().strip().split('\n') # get version from __version__ variable in labour_welfare/__init__.py from labour_welfare import __version__ as version setup( name='labour_welfare', version=version, description='Labou...
def prime_factors(): prime=[] for n in range(2,21): for i in range(2,21): if(n%i==0): if(i==n): continue else: break else: if(i==20): prime.append(n) else: continue return prime if __name__=="__main__": print prime_factors()
#!/usr/bin/python import time import operator import sys, re, os from textblob import * # gensim modules from gensim import utils from gensim.models.doc2vec import LabeledSentence #from gensim.models import Doc2Vec from gensim.models import * # numpy import numpy # random from random import shuffle # classifier fr...
n, k = list(map(int, input().split())) a = list(map(int, input().split())) charged = int(input()) a.pop(k) y = sum(a) // 2 if y == charged: print('Bon Appetit') else: print(charged - y)
# -*- coding: utf-8 -*- import argparse parser = argparse.ArgumentParser() parser.add_argument("echo", help="echo the string you use here", type=str) parser.add_argument("batch", help="batchsize", type=int) parser.add_argument("input_address", help="the address of input images or videos", type=str) args = parser.pa...
import cattura_immagine import elabora_immagine import invio_web_server as invio import data_ora as d #Cattura immagine tramite scatto con la PiCamera cattura_immagine.get_img() #Elaora l'immagine con un algoritmo OpenCV elabora_immagine.trova_mosche() #Invia il risultato della foto sul server url_foto = 'Risultati...
from django.db import models class Category(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class Photos(models.Model): category = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to='images/photos'...
firstname = 'syed' lastname = 'ahemd' age = int(input("enter your age:")) fruits = ["orange", 'mango', 'banana', 'melon'] sequences = [1,2,3,4,5,6,7,8,9] print ('today is the 1st day of programming') print (firstname + " " + lastname) print(25, firstname + " " + lastname) print(fruits[0]) for value in fruits: pr...
class Dog(object): def __init__(self,name): self.name = name def game(self): print("%s 奔奔跳跳玩耍" % self.name) class XiaoTianQuan(Dog): def game(self): print("%s 飞到天上去玩耍" % self.name) class Person(object): def __init__(self,name): self.name = name def game_with_dog(se...
import torch import itertools from torch.utils.data import Dataset from conllu import parse_incr from ...utils.sequences import pad_to_max class UDRNNDataset(Dataset): I2L = [ 'ADJ', 'ADP', 'ADV', 'AUX', 'CCONJ', 'DET', 'NOUN', 'NUM', 'PART...
import socket import time import random import struct import json import base64 a = [] floatList = [random.random() for _ in range(3)] print(floatList) buf = struct.pack('%sf' % len(floatList), *floatList) print(buf) code = base64.b64encode(buf) print(code) code = code.decode() print(code) a.append(cod...
__author__ = 'Daoyuan' from BaseSolution import * class ListNode(object): def __init__(self, x): self.val = x self.next = None def toString(self): tmp = self ret = "" while tmp is not None: ret = ret + ' ' + str(tmp.val) tmp = tmp.next r...
#!/usr/bin/env python3 import os import json from threads.thread import Thread __author__ = "Dibyo Majumdar" __email__ = "dibyo.majumdar@gmail.com" __all__ = [ 'TimeManager', 'TaskManager' ] # ROOT_DIRECTORY ROOT_DIRECTORY = os.path.normpath(os.path.join(__file__, '../data')) class TimeManager(): "...
import os import discord import motor.motor_asyncio import nest_asyncio from discord.ext import commands nest_asyncio.apply() mongo_url = os.environ.get("mongo") cluster = motor.motor_asyncio.AsyncIOMotorClient(mongo_url) levelling = cluster["discord"]["levelling"] bot_channel = 813687679014797332 talk_channels = ...
from collections import deque c_current = "red" c_child = "green" c_visited = "black" visited = [] adj_list = [] result = deque() def dfs(node): try: visited[node] = 1 except IndexError: return global result, c_current, c_child, c_visited result.append([node + 1, c_current]) for neighbor in adj_list[node]: ...
import threading VALUE=0 gLock=threading.Lock() def add_value(): global VALUE #锁只用在修改全局变量的地方,访问不需要加锁 gLock.acquire() for x in range(10): VALUE +=1 print("="*10) print(VALUE) gLock.release() print('value:%d' %VALUE) def main(): for x in range(2): t=threading.T...
import numpy as np def rmse(true,pred): if len(true) != len(pred): print("true and pred do not have same length") exit sum = 0 for i in range(len(true)): sum = np.sum((true[i]-pred[i])*(true[i]-pred[i])) return np.sqrt(sum/len(true)) def average(pred): sum = np.zeros(pred[0]...
# Generated by Django 3.2.4 on 2021-06-17 12:16 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('adminapp', '0011_auto_20210617_1500'), ] operations = [ migrations.RemoveField( model_name='chats', name='is_pub_black', ...
# coding:utf-8 ''' 添加新徽章: 1、加名字 2、加简介 3、加等级 4、加条件 如果徽章和成就无关: 5、加条件对应的成就等级 6、加赋值0 7、加跳过语句 搜索以上步骤,然后改,就可以了。 ''' import time import datetime import random from base.models import User, Idea, Achievement, Gooded, Collected, Looked, Badge from django.core.cache import cache achievementindex = {} achievementindex['1'] = "连...
# -*- coding: utf-8 -*- # @Time: 11/9/18 10:21 AM # @Author: Weiling # @File: split_frames.py # @Software: PyCharm import cv2 i = '01' vidcap = cv2.VideoCapture('videos/ISLab/ISLab-' + str(i) + '.mp4') success, image = vidcap.read() count = 0 while success: if count % 100 == 0: img_path = 'videos/ISLab_c...
import unittest import unittest.mock as mock import splendor_sim.interfaces.card.i_card as i_card import splendor_sim.interfaces.card.i_card_reserve as i_card_reserve import splendor_sim.interfaces.coin.i_coin_reserve as i_coin_reserve import splendor_sim.interfaces.coin.i_coin_type as i_coin_type import splendor_sim....
import os import json import argparse import logging import logging.config import numpy as np import torch import torch.nn as nn import torch.nn.parallel import torch.optim as optim from torch.utils.data import DataLoader import torchvision.datasets as dset import torchvision.transforms as transforms import torchvision...
from pandas.plotting._matplotlib.boxplot import boxplot as boxplot, boxplot_frame as boxplot_frame, boxplot_frame_groupby as boxplot_frame_groupby from pandas.plotting._matplotlib.converter import deregister as deregister, register as register from pandas.plotting._matplotlib.hist import hist_frame as hist_frame, hist_...
import BaseHTTPServer class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): usage = """<html> <body> <h1>TaskMuxer v0.1</h1> <table border="1"> <tr><th>Command</th><th>Description</th></tr> <tr><td><a href="/task">task</a></td><td>Get current task</td></tr> <tr><td><a href="/time">time</a></td><td>Get time re...
a, b, c, d = map(int, input().split()) #คือการให้ค่าตัวแปรหลายตัวในทีเดียว map(func,*iterible(เช่น list)) ตรงส่วนของfunctionบอกแค่ชื่อพอ one, two, three, four = 0, 0, 0, 0 if a < b: if c > b: one, two, three = a, b, c else: if a < c: one, two, three = a, c, b else: ...
# Copyright 2021 Google 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 applicable law or agreed to in writing, ...
import os import config import config.hrnet import config.pretrain USE_GPU = config.USE_GPU NUM_JOINTS = config.NUM_JOINTS # (True, False) for (END_TO_END, SOFTARGMAX) is not possible END_TO_END, SOFTARGMAX = (True, True) # Term-wise loss coefficients LOSS_COEFF = { 'hrnet_maps': 10, 'cycl_martinez': { ...
""" Make some synthetic FTG data """ import logging logging.basicConfig() import numpy import pylab from fatiando.data.gravity import TensorComponent from fatiando.utils.geometry import Prism # Create a synthetic body prisms = [] prism = Prism(dens=1000, x1=-100, x2=100, y1=-100, y2=100, z1=500, z2=700) prisms.app...
import argparse import logging import os import config import constants import engine import packet_common def log_level(string): string = string.lower() if string == 'critical': return logging.CRITICAL elif string == 'error': return logging.ERROR elif string == 'warning': retu...
import os import manifest import unittest from manifest.tasks import convert_bash_colors from manifest.tasks import sanitize_keys from manifest.tasks import populate_playbooks from manifest.tasks import run_ansible_jeneric from manifest.tasks import run_ansible_playbook from manifest.tasks import run_ansible_playbook_m...
import argparse parser = argparse.ArgumentParser() parser.add_argument('--head', dest='head') parser.add_argument('--tail', dest='tail') parser.set_defaults(head=None, tail=None) args = parser.parse_args() print args.head, args.tail
# -*- coding: utf-8 -*- """ Created on Sun Aug 22 12:32:36 2021 @author: rahul """ car = { "brand": "Ford", "model": "Mustang", "year": 1964 } car.pop("brand") print(car)
import sys def sprint(x): sys.stdout.write(str(x)) sys.stdout.flush() def sortReverse(lst): srt = sorted(lst) rlst = srt[: :-1] return rlst #This function is copied from: #http://code.activestate.com/recipes/252143-invert-a-dictionary-one-liner/ def dictinvert(d): inv = {} for k, v in d.i...
from socket import * import os serverSocket = socket(AF_INET, SOCK_STREAM) serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1) serverSocket.bind(('127.0.0.1', 9100)) serverSocket.listen(1); def parse_headers (data): headers = {} lines = data.splitlines() for l in lines: parts = l.split(": ", 1)...
# -*- coding: utf-8 -*- from __future__ import absolute_import #django.contrib from django.contrib import admin #scipycon from .models import Talk class TalkAdmin(admin.ModelAdmin): list_display = ('title', 'speaker', 'topic', 'duration', 'audience', 'approved', 'submitted') list_filter = ('approved', 'submi...
from rest_framework import viewsets from rest_framework.response import Response from rest_framework import permissions, status from django.contrib.auth import get_user_model from .serializers import ProfileSerializer, SellerSerializer from .models import SellerProfile, Profile User = get_user_model() class ProfileV...
import os # Function For Read File def searchNFG(filename): with open (filename , "r") as f: filecontent = f.read() if val in filecontent.lower(): return True else: return False if __name__ == "__main__": # List All Files and Direcatory dir_content = os....
def plotSmooth(deliveries,k,Daily_Total,FactOpen,FactClose,nOptimal,plotType): import matplotlib.pyplot as plt import numpy import pylab from descartes import PolygonPatch import itertools pylab.figure(figsize=(12, 9)) ax1 = pylab.subplot(111) ax1.spines["top"].set_visible(False...
from models.discriminator import Discriminator from torchaudio.transforms import Spectrogram from models.autoencoder import AutoEncoder from trainers.base_trainer import Trainer from models.generator import Generator from torch.optim import lr_scheduler from utils.metrics import snr, lsd from torch import nn import num...
# Savitzky-Golay: show convolution coeffs on plot import numpy as np import matplotlib.pyplot as plt M = 3 # window width is 2M+1 N = 2 # fitting polynomial degree n = 10 # d is impulse sequence d = np.concatenate([np.zeros(M), [1], np.zeros(M)]) impulse_domain = np.arange(-M,M+1) print('d =', d) a = np.polyfit(impul...
dic = {'애플': 'www.apple.com', '파이썬': 'www.python.org', '마이크로소프트': 'www.microsoft.com'} for k, v in dic.items(): print("{0}: {1}".format(k, v))
import time import hashlib import hmac import base64 import json import urllib.request as urllib2 import ssl class KrakenFuturesAPIClient: def __init__(self, api_keys, timeout=10, checkCertificate=True): self.api_keys = api_keys self.apiPath = "https://futures.kraken.com/derivatives" self....
from bmtk.simulator.filternet.pyfunction_cache import py_modules class Cell(object): def __init__(self, node): self._node = node self._gid = node.gid self._node_id = node.node_id self._lgn_cell_obj = None @property def gid(self): return self._gid @property ...
import cv2 as cv import numpy as np # Original image = cv.imread("./Resources/Photos/cats.jpg") cv.imshow("Original", image) # blank blank_img = np.zeros(image.shape, dtype="uint8") blank_img2 = np.zeros(image.shape, dtype="uint8") # Gray gray_img = cv.cvtColor(image, cv.COLOR_BGR2GRAY) cv.imshow("Gray", gray_img) ...
#!/usr/bin/python3 import argparse import csv import sys import os.path # ./merge.py -a file1 -b file2 -1 name1 -2 name2 -c name_after def parse_arguments(): parser = argparse.ArgumentParser() parser.add_argument( "-a", "--file1", required=True, help="provide filename for f...
from django.urls import path from .views import TicketListView, TicketCreateView, TicketDetailView, TicketUpdateView, TicketDeleteView app_name = 'tickets' urlpatterns = [ path('', TicketListView.as_view(), name='ticket-list'), path('<int:pk>/', TicketDetailView.as_view(), name='ticket-detail'), path('<...
import RPi.GPIO as GPIO import time import sys brakePin = 10 GPIO.setmode(GPIO.BOARD) GPIO.setup(brakePin, GPIO.OUT) p = GPIO.PWM(brakePin, 50) p.start(8) print("Wind Turbine Brake Calibration Program") print("This program will help you understand the range of brake pressure values and their effect on the turbine.")...
#!/usr/bin/python import json import socket import sys import time import xml.etree.ElementTree as ET import homefarm as hf ############################################################################### # # these functions handle reporting for the report generator def format_eta(eta): eta = float(eta) if et...
# -*- coding: utf-8 -*- # # @Version: python 3.7 # @File: process_all_seed_to_db.py # @Author: ty # @E-mail: nwu_ty@163.com # @Time: 2020/12/30 # @Description: # @Input: # @Output: # from tqdm import tqdm from Fuzzer.utils import get_file_abspath_list_from_dir, read_file, write_file, get_id, round_up from Fuzzer.fuzz...
class Solution: def expand(self, S: str) -> List[str]: """Backtracking. Running time: O(k) where k is the length of result. """ def backtracking(res, word, l): if not l: res.append(word) else: for c in l[0]: ...
""" Project Initialization package. Copyright (c) 2018 Qualcomm Technologies, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met: * Redistribution...
#!/usr/bin/python from selenium import webdriver from selenium.webdriver.chrome.options import Options import sys from colorama import Fore, Style try: user_county = sys.argv[1] except: print(Fore.RED+"I need the county name"+ Style.RESET_ALL) CHROME_PATH = '/usr/bin/google-chrome' CHROMEDRIVER_PATH = '/usr/...
""" This is a module to quickly call SQL databases into the rd_SQL function writen by mike by kwargs Author: matth Date Created: 28/02/2017 1:12 PM """ from __future__ import division from core.ecan_io.SQL_databases.Wells_database import wells_db from core.ecan_io.SQL_databases.sql_arg_class import sql_arg
from django.contrib import admin from django_summernote.admin import SummernoteModelAdmin # Register your models here. from campaigns.models import ( Category, Campaign, Organization, ) class CampaignAdmin(SummernoteModelAdmin): summernote_fields=('description',) admin.site.register(Campaign) admin.site.register...
# -*- coding=utf-8 -*- from __future__ import absolute_import, division, unicode_literals import functools import logging from lxml import etree from smarthome.config.parser.common.logic_expression import parse_logic_expression from smarthome.config.parser.common.procedure import eval_procedure logger = logging.getL...
#!/usr/bin/python print "hello world!" print; from Genesis2.XMLCrawler import XMLCrawler c = XMLCrawler() print c; c.read_xml('FPGen.xml') #c.goto_subinst('top_FPGen'); c = c.get_top() print c; print "iname=",c.iname() print "mname=",c.mname(); print "bname=",c.bname(); print "sname=",c.sname(); print "checkpoi...
import pandas as pd import numpy as np from sklearn.manifold import TSNE from sklearn.preprocessing import LabelEncoder from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler import matplotlib.pyplot as plt # https://github.com/llSourcell/visualize_dataset_demo/blob/mast...
from django.urls import path from api.views import PostApiview, PostDetailview, PostDeleteApiview, PostUpdateApiview urlpatterns = [ path('posts/', PostApiview.as_view(), name='blog-api'), path('posts/<int:pk>', PostDetailview.as_view(), name='blog-detail'), path('posts/delete/<int:pk>', PostDeleteApiview...
import sys def minDist(arr, x, y): arrLen = len(arr); minimunDistance = arrLen + 1; firstPositionIndex = sys.maxsize; firstValueFound = sys.maxsize; for i in range(arrLen): if (arr[i]==x) or (arr[i]==y): if (firstPositionIndex == sys.maxsize) or (arr[i] == firstValueFound): ...
# from poker.card import Card #CREATING DEPENDENSE...!!! import random class Deck(): def __init__(self): # (self, shuffle_func) this is how to decouple and give it independancy self.cards = [] #self._cards def __len__(self): return len(self.cards) def add_cards(self, ...
from django.contrib import admin # Register your models here. from django.contrib import admin from .models import Personal_detail # Register your models here. class Personal_detail_Admin(admin.ModelAdmin): list_display = ['owner','Fullname', 'Aadhar_number', 'Date_of_birth', 'Father_name', 'District', 'roll_num...
# Reference : Setup script documentation # https://setuptools.readthedocs.io/en/latest/setuptools.html from setuptools import setup, find_packages def get_requirements(filename): with open(filename) as f: requirements = f.read().splitlines() return requirements setup(name='codeTime', version...
from model import Base, Users from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///person.db?check_same_thread=False') Base.metadata.create_all(engine) DBSession = sessionmaker(bind=engine) session = DBSession() def add_user(full_name, password, email, nicknam...
import simpy import numpy as np import pandas as pd import matplotlib.pyplot as plt import random class Part: def __init__(self, id): self.id = id self.step = 0 self.process_list = ['process1', 'process2', 'process3', 'sink'] class Source: def __init__(self, env, monitor, ...
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-09-28 15:42 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app', '0006_remove_category_choises'), ] operation...