text
stringlengths
8
6.05M
import io import requests import zipfile import shutil import re response = requests.get(f'http://www.pythonchallenge.com/pc/def/channel.zip') zf = zipfile.ZipFile(io.BytesIO(response.content)) # print(zf.namelist()) comments = [] print(zf.open("readme.txt").readlines()) file_name = "90052.txt" while True: file...
# mocking is a very common testing practice # faking the output of a function with predefined values # allows us to write test in a consistent fashion without worrying if an underlying works correctly from unittest.mock import MagicMock from daos.book_dao_postgres import BookDaoPostgres from entities.book import Boo...
def score(palabra): totalPuntos = 0 acum = '' valores = { 'A': 1, 'E': 1, 'I': 1, 'O': 1, 'U': 1, 'L': 1, 'N': 1, 'R': 1, 'S': 1, 'T': 1, 'D': 2, 'G': 2, 'B': 3, 'C': 3, 'M': 3, 'P': 3, 'F': 4, 'H': 4, 'V': 4, 'W': 4, 'Y': 4, 'K': 5, 'J': 8, 'X': 8, 'Q': 10, 'Z': 10 ...
class Planet(): def __init__(self, name, parent): self.name = name self.parent = parent self.children = [] def totalOrbits(self): if self.parent == None: return 0 return 1 + self.parent.totalOrbits() def main(): planetList = registerPlanets() orbitCount = 0 for planet in planetList: orbitCount +...
# Generated by Django 3.2 on 2021-04-14 11:01 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('app', '0002_auto_20210414_1658'), ] operations = [ migrations.AlterModelOptions( name='role', options={'ordering': ['name']}, ...
import os.path from sqlalchemy import create_engine from sqlalchemy.orm import Session from client.clientmodels import LocalUsers, LocalContacts, MessageHistory class ClientDatabase: def __init__(self, path, name): db_path = os.path.join(path, f"client_{name}.db3") engine = create_engine(f'sqli...
def info(**nos): print str(type(nos)) print nos info(a=1, b=2, c=3)
import numpy as np def relu(X, deriv=False): if not deriv: return np.max(X, 0) else: return X > 0 def sigmoid(X, deriv=False): if not deriv: return 1/(1+np.exp(-X)) else: s = sigmoid(X) return s*(1-s) def tanh(X, deriv=False): if not deriv: exp =...
""" Time/Space complexity = O(N) """ # Top Down Approach from functools import lru_cache class Solution: def rob(self, nums: List[int]) -> int: if not nums: return 0 @lru_cache(maxsize=None) def dfs(val = 0, indx = 0): if indx >= len(num...
import MapReduce import sys """ Join input from two tables """ mr = MapReduce.MapReduce() # ============================= # Do not modify above this line def mapper(record): # 0: table name # 1: order id # 2+: data mr.emit_intermediate(record[1], record) def reducer(key, list_of_values): list_o...
# Generated by Django 2.2.5 on 2019-10-12 04:26 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('gestiondeusuarios', '0004_auto_20191010_1255'), ] operations = [ migrations.RemoveField( model_name='numid', name='Doctores'...
from selenium import webdriver import time def checkWelcome(): url = 'https://opensource-demo.orangehrmlive.com/index.php/auth/login' location = '../drivers/' driver = webdriver.Chrome(executable_path=location + 'chromedriver.exe') driver.get(url) time.sleep(2) driver.find_element_by_name('txt...
#!python def merge(list1, list2): """Merge given lists of items, each assumed to already be in sorted order, and return a new list containing all items in sorted order. TODO: Running time: ??? Why and under what conditions? TODO: Memory usage: ??? Why and under what conditions?""" # TODO: Repeat until one l...
import os import sys from functools import partial import pymel.core as pm import maya.cmds as cmds import maya.mel as mel def findAllFiles(fileDirectory, fileExtension): # Return a list of all file names, excluding the file extension allFiles = os.listdir(fileDirectory) # Refine all files, listing o...
for x in range(100, 1, -2): print(x)
''' Regular Expression Library used by Shorthand. ''' # General # Matches a valid Date Stamp DATE_STAMP_PATTERN = r'[1-2][0-9]{3}\-[0-3][0-9]\-[0-3][0-9]' # Matches a valid Date Stamp within parentheses START_STAMP_PATTERN = r'\(' + DATE_STAMP_PATTERN + r'\)' # Matches two valid Date Stamps within parentheses wi...
n=int(input('Enter the no. of lines')) for i in range(0,n): for a in range(0,i): print(' ',end=" ") for j in range(i,n): print("*",end=" ") print('')
from flask import Flask from flask import Blueprint from flask import request from flask import jsonify from flaskext.mysql import MySQL from flask_cors import CORS, cross_origin app= Flask(__name__) mysql=MySQL() app.config['MYSQL_DATABASE_USER'] ='root' app.config['MYSQL_DATABASE_PASSWORD'] ='admi' app....
# In[1]: import pandas as pd # In[3]: df_brazil = pd.read_csv("sudeste.csv", usecols=["date", "temp"]) # In[5]: df_madrid = pd.read_csv("weather_madrid_LEMD_1997_2015.csv", usecols=["CET", "Mean TemperatureC"]) # In[12]: df_brazil_no_dup_date = df_brazil.groupby("date").mean().reset_index() # In[14]: ...
""" Copyright Matt DeMartino (Stravajiaxen) Licensed under MIT License -- do whatever you want with this, just don't sue me! This code attempts to solve Project Euler (projecteuler.net) Problem #15 Lattice paths Starting in the top left corner of a 2x2 grid, and only being able to move to the right and down, there a...
#!/usr/bin/env python import subprocess import sys import os def main(): # print os.getcwd() if len(sys.argv) is 1: wd = '.' elif len(sys.argv) is 2: wd = sys.argv[1] else: raise ValueError count = 0 for root, dirs, files in os.walk(wd): for file in files: ...
from django.apps import AppConfig class HappyTeamConfig(AppConfig): name = 'happy_team'
print"Hello Github!"
import sqlite3 conn = sqlite3.connect('wordCount.db') cursor = conn.cursor() print("Connected") sql = '''select * from wordCount''' results = cursor.execute(sql) all_words = results.fetchall() for word in all_words: print(word)
from selenium import webdriver from unittest import TestCase, main from pyvirtualdisplay import Display class TestClass(TestCase): display = Display(visible=0, size=(800, 600)) display.start() browser = webdriver.Firefox() def test_0(self): self.browser.get("https://congressand.me") ...
#append list to second list l1=list() l2=list() for i in range(5): l1.append((input("enter element:"))) for i in range(5): l2.append((input("enter element:"))) print(l1) print(l2) for i in range(5): l1.append(l2[i]) print(l1)
import os import random from game import node, info from cfr import cfr_player from human import human_player C0 = 2 player = cfr_player() player.train(60 * 60 * 4 * 60) player.output("test.QAQ")
#/usr/bin/env python # Author:tjy # -*- utf-8 -*- name = "tjy" name2 = name print("my name is", name, name2) name = "paochege" print(name, name2) PI = 3.1415926 print(PI) print("您好")
#!/bin/python import math import os import random import re import sys # Complete the balancedForest function below. class Tree: def __init__(self, key, data): self.data = data self.children = {} self.parent = None self.key = key def addChild(self, key, node): self.chil...
from distutils.core import setup import py2exe setup(console=['Mainwindow.py'])​
import numpy as np import wavio rate = 22050 # samples per second T = 3 # sample duration (seconds) f = 440.0 # sound frequency (Hz) t = np.linspace(0, T, T*rate, endpoint=False) x = np.sin(2*np.pi * f * t) wavio.write("sine24.wav", x, rate, sampwidth=3) rate = 1024 T = 5 t = np.linspace(0, T, T*rate, e...
from datetime import datetime import os import time import json import vm_automation from __builtin__ import False # # GOT TIRED OF TRACKING THIS DATA IN A LIST # class portValue: """ THE BELOW portValue CLASS IS HOW I DECIDED TO TRACK THE PORT NUMBERS I WANTED A SINGLETON, BUT I FOUND NOTH...
from django.db import models class ArticleManager(models.Manager): pass
import socket, json, requests from lxml import etree # ATAK CoT proxy for CloudRF API s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) # EDIT ME: Radio templates are read from local JSON files and mapped to ATAK callsigns here radios = {"CloudRF": "radios/b...
from random import choice len_of_pass = 16 chars = "abcdefghijklmnopqrstvuwxyz1234567890!@#$%^&*()_+><>~ABCDEFGHIJKLMNOPQRSTUVWXYZ" # password = [] # for each_char in range(len_of_pass): # password.append(choice(chars)) # print("Your random password is :" ,"".join(password)) random_pass = "".join(choice(chars)...
import socket import time """ Simula la bateria fisica, mediante socket """ while True: try: cliente = socket.socket(socket.AF_INET, socket.SOCK_STREAM) direccion_servidor = ("localhost", 11000) cliente.connect(direccion_servidor) carga = input("Carga > ") cliente.send(byt...
from weibo import APIClient import urllib import webbrowser #for test import httplib import weiboconfig as config #get the pin code from the redirect_uri def get_pincode(): client = APIClient(app_key=config.APP_KEY, app_secret=config.APP_SECRET, redirect_uri=config.CALLBACK_URI) url = client.get_authorize_url(...
from machine import Pin import time D4 = Pin(2, Pin.OUT) while(True): D4.off() time.sleep(2) D4.on() time.sleep(2)
import requests, json from pprint import pprint url_netflix = "https://netflix-unofficial.p.rapidapi.com/api/search" headers_netflix = { 'x-rapidapi-host': "netflix-unofficial.p.rapidapi.com", 'x-rapidapi-key': "df04cb6865msha77f6ca500b312ep1202bcjsn9a883a67fa18" } response_netflix = requests.request("GE...
from pyicloud import PyiCloudService import os, math from datetime import datetime, timedelta ICLOUD_MAIL = os.environ['ICLOUD_MAIL'] ICLOUD_PSWD = os.environ['ICLOUD_PSWD'] class ICalendar(object): def __init__(self): self.api = PyiCloudService(ICLOUD_MAIL, ICLOUD_PSWD) self.api.calendar.refresh_client() self...
from .delboeuf_image import _delboeuf_image from .delboeuf_parameters import _delboeuf_parameters from .delboeuf_psychopy import _delboeuf_psychopy class Delboeuf: """ A class to generate the Delboeuf Illusion. The Delboeuf illusion is an optical illusion of relative size perception, where circles of...
import numpy as np import h5py import pcl dataset = np.zeros(shape=(32,2048,3)) labels = np.zeros(shape=(32,1)) '''for i in range(0,10): x = pcl.io.loadpcd("unidentified_"+str(i)+".pcd") z = x.xyz offset=2048-z.shape[0] x = np.zeros((offset,3)) dataset2 = np.append(z,x,0) dataset[i]=dataset2 labels[i]=0''' fo...
# Generated by Django 3.2.5 on 2021-08-07 13:00 import colorfield.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('works', '0005_auto_20210807_1256'), ] operations = [ migrations.CreateModel( name='ExcerptFontColor', ...
import fitsio import os import numpy as np from scipy.stats import invgamma, dirichlet, multivariate_normal, norm import urllib import random # Bayesian model selection scheme # # Let's say we have model M. Then, the model evidence is: # P(M | D) \propto P(D | M) P(M) # Typically, we will assume P(M) is uniform ac...
""" 文件缓冲区的处理 f.write() :将字符串写到缓冲区 f.close() :将缓冲区的内容写入文件,并且将缓冲区清空,同时关闭文件 f.flush() :将缓冲区的内容写入文件,但是不清空缓冲区内容 f.read() :将内容读取到缓冲区 time.sleep(10):文件对象暂停10秒再进行之后的操作 """ import time f = open("D:/test/缓冲区处理.txt","w+") f.write("python中缓冲区的处理") f.close() #调用close方法,文件缓冲区清空,...
a=int(input('digite u numero: ')) print(f'o antecessor de {a} é {a-1}') print(f'e o sucessor é {a+1}')
#!/usr/bin/python3 # Script that fetches an URL import urllib.request print("Body response:") with urllib.request.urlopen('https://intranet.hbtn.io/status') as response: body = response.read() print("\t- type: {}".format(type(response.read()))) print("\t- content: {}".format(body)) print("\t- utf8 cont...
class XcomError(Exception): def __init__(self, message = '', thrower = None): super().__init__(message) self.thrower = thrower class ParseError(XcomError): pass class ResponseError(XcomError): pass class StatusError(XcomError): pass class ClientTimeoutError(XcomError): pass clas...
col_list = [ 'symbol', 'zip', 'sector', 'fullTimeEmployees', 'longBusinessSummary', 'city', 'phone', 'state', 'country', 'companyOfficers', 'website', 'maxAge', 'address1', 'fax', 'industry', 'address2', 'ebitdaMargins', 'profitMar...
import random from random import randint from decimal import * abecedario = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] tam = 26; def exponente(y,b,mod): x = 1 while (b > 1): if( b%2 == 0): #print (str(y)+" | "+str(b)+ " | "+str(x...
lod = [{'tanah': '70', 'bangunan': '50', 'jarak_ke_pusat': '15', 'harga': '500'}, {'tanah': '70', 'bangunan': '60', 'jarak_ke_pusat': '30', 'harga': '400'}, {'tanah': '70', 'bangunan': '60', 'jarak_ke_pusat': '55', 'harga': '300'}, {'tanah': '100', 'bangunan': '50', 'jarak_ke_pusat': '30', 'harga': '700'}, {'tanah': '1...
import json import uuid import hashlib from SPARQLWrapper import SPARQLWrapper, JSON, CSV from collections import Counter def get_preferences(): db_labels = get_db_labels(reversed=True) fuseki_client = SPARQLWrapper("http://ec2-54-93-236-36.eu-central-1.compute.amazonaws.com:3030/v2/") query = """ PRE...
from selenium import webdriver import unittest import time from selenium.webdriver.common.keys import Keys class TestCaseTaoKipThi(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = webdriver.Chrome(executable_path="D:\pythonProject\driver\chromedriver.exe") cls.driver.implicit...
import requests from lxml import etree from io import StringIO import base64 import codecs from keras.models import load_model from helpers import resize_to_fit from imutils import paths import numpy as np import imutils import cv2 import pickle import os import glob import time try: import Image e...
input_str = input() i_and_moster = input_str.split(" ") i_val = int(i_and_moster[0]) moster_num = i_and_moster[-1] #print(i_val, moster_num) input_str = input() moster_list = input_str.split(" ") #print(moster_list) moster_list = [int(i) for i in moster_list] moster_list.sort() #print(moster_list) money = 0 high_money...
import sys import datetime import glob from matplotlib import pyplot as plt import matplotlib.dates as md from git import Repo def count_lines(extensions): results = [] for ext in extensions: count = 0 files = glob.glob(path_to_repo + '/**/*' + ext, recursive=True) for filename in files...
import sys import collections def all_reversals(permutation): """ Generator for all reversals of a permutation :param permutation: the input permutation string :return: each reversal of the permutation """ for i in range(len(permutation)): for j in range(i + 2, len(permutation) + 1): ...
import abc class GameEngine(object, metaclass=abc.ABCMeta): @abc.abstractmethod def create_new_game(self): """ :return: an initial GameState object, representing the initial state of a game """ raise NotImplementedError()
# -*- coding: utf-8 -*- import json class AlbBaseException(Exception): http_status_code = 200 def __init__(self, code, message=None, data=None): self.code = code self.message = message self.data = data self.tojson = self.__str__ def __str__(self): return json.dump...
import numpy as np from geoalt_geometry.vertices import Vertex, VertexCollection from geoalt_geometry.edges import Edge, EdgeCollection from timeit import default_timer as timer class FaceCollection: ''' Collection of Face objects ''' def __init__(self, stlfile): self.stlfile = stlfile ...
import requests, json from past.builtins import basestring from copy import deepcopy from datetime import date """ Edsby.py: An API wrapper/library for Python - v0.7.1 https://github.com/ctrezevant/PyEdsby/ (c) 2017 Charlton Trezevant - www.ctis.me MIT License This code is well documented. You ca...
from collections import OrderedDict from typing import Dict import numpy as np class Parameter: def __init__(self, value: np.ndarray) -> None: self.value: np.ndarray = value self.grad: np.ndarray = np.zeros_like(value) class Module: def __init__(self): self.__parameters: Dict[str, ...
''' service module ''' from .server import PrpcServer from .client import PrpcClient from .type_decorator import argument_check
from onegov.activity import ActivityCollection from onegov.feriennet.policy import ActivityQueryPolicy from sqlalchemy.orm import joinedload class VacationActivityCollection(ActivityCollection): # type is ignored, but present to keep the same signature as the superclass def __init__(self, session, type=None,...
""" Efectuar la división de dos números enteros, utilizando el método de las restas sucesivas. Observe el siguiente ejemplo: Dividir 8 entre 2 8 – 2 = 6 6 – 2 = 4 número de restas efectuadas es igual al cociente =4 4 – 2 = 2 2 – 2 = 0 %resto de la división Imprima el restante efectuado Ejemplos de prueba """ Cont...
import datetime def print_line(args): if args.verbose == 1: print( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S ") + '-' * 72 ) def print_message(msg,args): if args.verbose == 1: print( datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + ' - ' + str(msg) ) def print...
#!/usr/bin/env python3 text = input("Enter string: ") my_list = text.split("h") n_list = [] n_list.append(my_list[0]) n_list.append(my_list[-1]) text = "".join(n_list) print(text)
import matplotlib.pyplot as plt import itertools def floating_point_system(beta, t, L, U): """ Entrada: beta que corresponde a la base o raiz, t que corresponde a la presicion y L, U corresponden a rango del exponente Salida: Un sistema punto flotante normalizado correspondiente a las parametros. """ ...
########################## # R imports: Import R # objects using rpy2 ########################## from rpy2.robjects.packages import importr import rpy2.robjects as robjects R = robjects.r import rpy2.robjects.numpy2ri rpy2.robjects.numpy2ri.activate() GRF=importr('grf') ########################## # Python imports ###...
import random n1 = random.randint(1, 10) answer = input('Enter some integer: ') answer = int(answer) print(f'You choose {answer}, computer {n1}') if n1 > answer: print(f'{n1} Bigger {answer}') elif n1 < answer: print(f'{n1} Less {answer}') else: print(f'{n1} Equal {answer}') # висновок,що не дуже підходит...
from pwn import * import sys #import kmpwn sys.path.append('/home/vagrant/kmpwn') from kmpwn import * #fsb(width, offset, data, padding, roop) #config context(os='linux', arch='i386') context.log_level = 'debug' FILE_NAME = "./pwnable" HOST = "binary.utctf.live" PORT = 9003 """ HOST = "localhost" PORT = 7777 """ i...
from django.shortcuts import * from django.http import HttpResponseRedirect, HttpResponse from django.core.urlresolvers import reverse from django.views.decorators.csrf import csrf_exempt import hashlib, random, datetime from surl.models import Surl def get(request,_surl): try: s=Surl.objects.get(surl__exact=_surl)...
from django.db import models from django.utils import timezone from django.contrib.auth.models import User class Post(models.Model): author = 'test' class Test(models.Model): a = 1 # Create your models here.
import os import json import requests import logging from common_logger import init_logger init_logger("graphql-crawl.log") # Please issue your own personal access token # https://github.com/settings/tokens HEADERS = {"Authorization": "Bearer [YOUR_PERSONAL_ACCESSS_TOKEN]"} # Top 5 repos that have the largest number...
class GameSettings: screenSize = { "x": 600, "y": 600 } running = True num_asteroids = 10
import logging import os from pathlib import Path from commandbus import CommandBus from google.cloud import bigquery from pymongo import MongoClient from pepy.application.admin_password_checker import AdminPasswordChecker from pepy.application.badge_service import BadgeService, DownloadsNumberFormatter, Personalized...
""" 剑指offer第2章 面试题3 二维数组中的查找 """ def find_ele_in_array(array, ele): """数组规律是向右向下增大,所以可以找中间的数字然后就可以排除了 比如9,如果要找的数字比9小,那么就可以排除1列,因为在第一列9是最小的 如果要找的数字比9大,那么就可以排除1行,因为在第一行9是最大的 同理也可以找6,由此可见,要找到中间数字,这样容易进行排除""" # 右上角的元素坐标 if not array: return False columns = len(array[0]) rows = len(...
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: # # Copyright 2021 The NiPreps Developers <nipreps@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may...
import math from main.info import config def user_based_predict_by_knn(dao,userid,itemid): sim_list = get_user_topk_neighbor(dao,userid) other_user_rate_list = [] userbaseline = get_Baseline(dao,userid) for u,s in sim_list: r = dao.get_rate(u,itemid) #get other users rate if r: ...
__author__ = "Rinat Khaziev" __copyright__ = "Copyright 2016" import luigi import requests import pandas as pd import datetime class DownloadTaskDate(luigi.ExternalTask): ''' Download data luigi task ''' date = luigi.DateParameter(default=datetime.date.today()) def run(self): url = 'https://data.cityofchicago....
# Gil Garcia # ASTR221 - hw3 prob 2 #4/4/2019 ''' In this script, we query the Gaia DR2 catalog to find the HR diagram for M4, a globular cluster and fit it with ZAMS ''' # we import the required libraries import numpy as np import matplotlib.pyplot as plt # we use vizier to query the Hiparcos catalog from astroquer...
from django.contrib import admin from django.contrib.auth.admin import UserAdmin # Register your models here. from .models import Customer, Addresses, Management, User, Staff, UserProfile, UserDefaultAddress class AddressesInline(admin.TabularInline): model = Addresses raw_id_fields = ('user',) search_fie...
def madlib(): person = input("person: ") adjective1 = input("adjective: ") adjective2 = input("adjective: ") noun1 = input("noun: ") adjective3 = input("adjective: ") noun2 = input("noun: ") adjective4 = input("adjective: ") verb1 = input("verb: ") verb2 = input("verb: ") verb3 =...
# -*- coding: utf-8 -*- from django.conf.urls import patterns, url from django.conf import settings from django.conf.urls.static import static ''' urlpatterns = patterns('', # ... the rest of your URLconf goes here ... ) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ''' urlpatterns = patterns('myp...
from numpy import * def GN(res,x): #Residual minimization for nonlinear least squares problems eps = finfo(float).eps #machine epsilon from numpy for i in range(10): DR = cdjac(res,x) DRT = DR.T DFTDF = dot(DRT,DR) s = linalg.solve(DRTDR,-DR) x += s def cdjac(f,...
# encoding:utf-8 __author__ = 'hanzhao' import weixin import multiprocessing import logging import time import os import json # def plugin_name(): pluginname = [] for filename in os.listdir("plugins"): if not filename.endswith(".py") or filename.startswith("_"): continue ...
#!/usr/bin/env python import time as time import numpy as np import cv2 from pkg_resources import parse_version display = True width = 640 height = 480 ntries = 10 jitter = 1 OPCV3 = parse_version(cv2.__version__) >= parse_version('3') # returns OpenCV VideoCapture property id given, e.g., "FPS" def vidProperty(p...
"""Add message status and payload Revision ID: 19e4d92b2bef Revises: 4bd072d67d85 Create Date: 2020-04-16 12:34:03.014993 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '19e4d92b2bef' down_revision = '4bd072d67d85' branch_labels = None depends_on = None def ...
import streamlit as st import detection as dtc import imutils import datetime import cv2 import os import pandas as pd import torch # GUI header st.set_page_config("Social Distancing Detector", None, "wide") st.title('Automated Social Distancing Monitoring System :walking::walking:') st.subheader('COS30018...
from flask import Flask, render_template, request # importing the earth engine import ee ee.Initialize() from IPython.display import Image,display from datetime import date , timedelta from datetime import datetime import folium import pygeoj app = Flask(__name__) @app.route('/') def index(): return render_template...
from datetime import date from uuid import uuid4 from onegov.ballot import ElectionCompound, Election from onegov.core.utils import module_path from tests.onegov.election_day.common import login from webtest import TestApp as Client from webtest import Upload from unittest.mock import patch def add_data_source(clien...
from django.urls import path from . import views app_name = 'tag' urlpatterns = [ path('tag_list/', views.TagListView.as_view(), name='tag-list'), path('tag_create/', views.TagCreateView.as_view(), name='tag-create'), path('tag_delete/<tag_id>', views.TagDeleteView.as_view(), n...
"""SambaNova boilerplate main method.""" #import argparse import sys #from typing import Tuple #import torch #import torch.nn as nn #import torchvision from sambaflow import samba import sambaflow.samba.utils as utils from sambaflow.samba.utils.argparser import parse_app_args from sambaflow.samba.utils.pef_utils i...
# Strings are one f the most common data types in any programming lanugage # A string literal is just defining a string as such name = "Adam" # String interpolation putting variables into a string greeeting = "Hello " + name + " it is great to meet you!" # f is format interpolate values into your string using {} gree...
from nltk import bigrams,trigrams import string import nltk from collections import Counter mainPath = "./auto-grader/ArgumentDetection/" input = 'data/pdtb/input/' def listModals(postags, type, dict_x): counts = Counter(word if 'MD' in tag else None for word,tag in postags ) for word in counts: ...
#!/usr/bin/env python # coding: utf-8 # # វិធីសាស្រ្តបរមាកម្មតាមរយៈ SGD # ក្នុងមេរៀនមុនយើងបានសិក្សាអំពីម៉ូឌែលតម្រែតម្រង់លីនេអ៊ែរ ដែលត្រូវបានប្រើប្រាស់សម្រាប់សិក្សាពីការទំនាក់ទំនងរវាងអថេរពន្យល់និងអថេរគោលដៅ។ ក្នុងការកំណត់តម្លៃប៉ារ៉ាម៉ែត្រនៃម៉ូឌែល(មេគុណតម្រែតម្រង់) យើងបានដោះស្រាយតាមរយៈវិធីសាស្រ្តជាមូលដ្ឋាននៃគណិតវិទ្យាវិ...
def solution(n): solution =[] while (n // 1000 >= 1): solution.append("M") n = n - 1000 while (n // 500 >= 1): if (n >= 900): solution.append("CM") n = n - 900 break solution.append("D") n = n - 500 while (n // 100 >= 1): ...
from django.shortcuts import render,render_to_response from django.template import RequestContext from django.http import HttpResponseRedirect from jobs.forms import QuoteForm from jobs.models import UserProfile #import sendgrid import sys # Create your views here. def home(request): return render_to_response("jobs...
import json import os import urllib2,urllib from flask import Module from flask import redirect,request,session,url_for from flask.ext.oauth import OAuth from db import Database from util import * login = Module(__name__) oauth = OAuth() facebook = oauth.remote_app('facebook', base_url='https://graph.facebook....
from db import dataBase as database class incentive: def __init__(self): self.incentiveId = "" self.incentiveAmount = "" self.incentiveDate = "" self.employeeId = "" self.employeeSalary = 0 def selectAllIncentive(self,cursor): try: days = int(input(...