text
stringlengths
38
1.54M
from fizzbuzz import fizzbuzz def test_fizz(): assert fizzbuzz(3) == 'fizz' def test_buzz(): assert fizzbuzz(5) == 'buzz' def test_fizzbuzz(): assert fizzbuzz(15) == 'fizzbuzz'
from django.db import models # Create your models here. class About(models.Model): name= models.CharField(max_length=125, null=True) email= models.EmailField() address= models.CharField(max_length=255) zipcode = models.CharField(max_length=150) objects= models.Manager
# inferring mRNA from protein dictionary = {'F':2, 'L':6, 'I':3, 'M':1, 'V':4, 'S':4, 'P':4, 'T':4, 'A':4, 'Y':2, 'Stop':3, 'H':2,'Q':2, 'N':2, 'K':2, 'D':2, 'E':2, 'C':2, 'W':1, 'R':6, 'S':6, 'G':4} infile = open('dna.txt','r') dataset = '' for line in infile.readlines(): ...
import os import csv import glob import sys from flask import Flask import fire from dotenv import load_dotenv load_dotenv(".env", verbose=True) path = os.environ.get("PASSENGER_BASE_PATH") sys.path.append(path) from extension import db, ma # noqa: F402 from scripts.utils.import_records import ( # noqa: F402 i...
from django.shortcuts import render from datetime import datetime, timedelta def set_cookies(request): context = {} response = render(request, 'app_cookies/set_cookie.html') response.set_cookie('name', 'Onkar', expires=datetime.utcnow() + timedelta(days=3)) return response def get_cookies(request): ...
#smileyface.py from math import * from graphics import * win =GraphWin("Click&Smile" , 500, 500) win.setBackground('orange') intro = Text(Point(250,480), "Click on window, Smileys are waiting :D") intro.setFill('green') intro.draw(win) def drawCircle(x,y, r): aCircle =Circle(Point(x,y), r) aCircle.s...
import os from kbinxml import KBinXML import lxml.etree as etree from .Node import Node from .. import utils class GenericFile(Node): def from_xml(self, element): info = self._split_ints(element.text) # sometimes we don't get a timestamp if len(info) == 2: self.start, self.siz...
class student: def info(self): print('OOPs Concept') #DefaultConstructor def __init__(self): print('Default Constructer') s=student() s.info() class student: def info(self): print('OOPs Concept') # ParameterizedConstructor def __init__(self,n): print('Name ...
#encoding=utf8 # Copyright (c) 2021 PaddlePaddle Authors. 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 requi...
print("What is the name of player 1") player1 = raw_input() print("What is the name of player 2") player2 = raw_input() print("Player 1 is " + player1) print("Player 2 is " + player2) print("Player 1 please select either rock, paper, scissors") answer = raw_input() print("Player 2 please select either rock, p...
#!/usr/bin/python # -*- coding: utf-8 ############################################################################## # # Copyright (c) 2006 TINY SPRL. (http://tiny.be) All Rights Reserved. # # WARNING: This program as such is intended to be used by professional # programmers who take the whole responsability of assessi...
# -*- coding: utf-8 -*- """ Created on Tue Mar 16 12:35:15 2021 @author: swhetzel """ import espn_scraper as espn import espn_team_stats as espn_team import pygal import plotly.express as px import pandas as pd import dash import dash_core_components as dcc import dash_html_components as html game_id = "401301254" p...
class Node: def __init__(self, value, next=None, prev=None): self.value = value self.next = next self.prev = prev class Queue: size = 0 start = None end = None def __init__(self): self.start = Node(0) self.end = Node(0) self.start.next = self.end self.end.prev = self.start def inqueue (self, n): ...
# -*- coding: utf-8 -*- """ Created on Sat Mar 9 13:22:00 2019 @author: mkalo """ ''' *********************************** UMAIR CHAANDA DSC 450 ASSIGNMENT-4 PART-3 *********************************** ''' import sqlite3 import json conn = sqlite3.connect('csc455.db') c = conn.cursor(...
""" * ____ _ * | _ \ ___ __| |_ __ _ _ _ __ ___ * | |_) / _ \ / _` | '__| | | | '_ ` _ \ * | __/ (_) | (_| | | | |_| | | | | | | * |_| \___/ \__,_|_| \__,_|_| |_| |_| * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public Lice...
# users/forms.py from django import forms # form 是数据库之前的,所以可以在 forms 中检验,这样减轻数据库的负担 class LoginForm(forms.Form): username = forms.CharField(required=True) # 必须与 HTML 中的字段一样 password = forms.CharField(required=True, min_length=5) # 必须与 HTML 中的字段一样
import numpy as np from typing import Tuple from rlo.dataset import RewriteId, StateValueDataset, PolicyNetDataset from rlo import rewrites from testutils import parse_expr_typed def mock_policy_value_dataset() -> Tuple[PolicyNetDataset, rewrites.RuleSet]: rules = rewrites.get_rules("simplify_rules") value_d...
# O(n) time O(n) space def iterative_inorder(root): if root == None: return stack = [] while True: if root != None: stack.append(root) root = root.left_child else: if stack == []: break root = stack.pop() p...
# -*- coding: utf-8 -*- """ Created on Tue Oct 27 18:06:44 2020 @author: Hilbert Huang Hitomi """ import serial import time import simplejson import struct from serial.tools import list_ports from PARAMS import INPERparameters # crc def crc16(data: bytes) -> bytes: data_len = len(data) if data_len <= 0: ...
import librosa X, sample_rate, = librosa.load('mc.wav') import numpy as np win_length = 20000 #int(0.080 * sample_rate) =551 hop_length = int(win_length // 4) #ahop_length = 512 mfccs = librosa.feature.mfcc(y=X, sr=sample_rate, n_mfcc=40, n_fft=win_length, hop_length=hop_length) librosa.display.wave...
from behave import * @given("the following users exist") def step_impl(context): """ :type context: behave.runner.Context """ raise NotImplementedError(u'STEP: Given the following users exist ') @given("the admin navigated to Add customer page") def step_impl(context): """ :type ...
from django.conf import settings from adminlte2_templates.core import get_settings def template(request): """ Get all settings related to the AdminLTE 2 module and return them as context variables """ skin_style = get_settings('ADMINLTE_SKIN_STYLE') context = { 'DEBUG': getattr(setti...
# -*- coding: utf-8 -*- tests = int(input()) for i in range(0, tests): n = input() if n[0: 4] == 'Thor': print('Y') else: print('N')
import mosspy userid = 751640219 m = mosspy.Moss(userid, "c") #m.addBaseFile("ls.c") #m.addBaseFile("watch.c") # Submission Files m.addFile("test1.c") m.addFile("test2.c") # progress function optional, run on every file uploaded # result is submission URL url = m.send(lambda file_path, display_name: print('*', end...
def answer(total_lambs): """ Lovely Lucky LAMBs Args: total_lambs: the number of lambs available to distribute Returns: Int: the difference between the most `generous` and `stingiest` distributions of lambs given total_lambs """ powers = _powers_of_2(total_lambs) fib = _fibon...
# coding=utf-8 import unittest import os from time import sleep import requests as re import random import public.methods as t import public.case_xls as xl class API(unittest.TestCase,t.Methods,xl.Case_xls): u'''常见问题列表''' def setUp(self): self.headers = {self.get_row(0, 11)[0]: self.get_row(0, 11)[1]} # headers ...
from django.core.urlresolvers import reverse from django.utils.http import base36_to_int from django.http import HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.contrib.auth import login...
#https://towardsdatascience.com/sports-analytics-an-exploratory-analysis-of-international-football-matches-part-1-e133798295f7 import streamlit as st import pandas as pd import numpy as np import plotly.express as px import seaborn as sns import matplotlib.pyplot as plt import plotly.graph_objects as go from plotly.su...
import numpy as np from .. import mathematics, painters def tile_limits(zoom): l, u = 0, 2**zoom return (l,l), (u,u) def tile_range(lower=None, upper=None, zoom=0): l, u = 0, 2**zoom lower = (l,l) if lower is None else lower upper = (u,u) if upper is None else upper for y in range(max(l, lo...
#string operations greet = "deepika is a good girl:)" print(greet.title()) print(greet.upper()) print(greet.lower()) print(greet.capitalize()) print(greet.casefold()) print(greet.swapcase()) def yesorno(str1,str2): if str2 == '1': return str1.upper() if str2 == '2': return str1.lower() if s...
def leerArchivo(nombre): """Lectura de archivo: Lee un archivo y retorna su contenido separado por líneas en un arreglo y a su vez separado por palabras""" return [list(map(int, line.split())) for line in open(nombre)] def calcularCaminoAdyLargo(triangulo): """Cálculo de camino de adyacentes: ...
import sys sys.path.append('../') import unittest from lib_db import LibDb as db from lib_db import user_db class TestUserDatabase(unittest.TestCase): def setUp(self) -> None: self.lib = db.LibDb("localhost", "root", "root") self.lib.prepare_db("TestDatabase") self.lib.add_user("First", "...
# tinder.py from __future__ import print_function, division import numpy import thinkbayes2 import thinkplot def main(): maleRates = [0.52, 0.38, 0.39, 1.01, 2.63] femaleRates = [50, 20.5] pdfMale = thinkbayes2.EstimatedPdf(maleRates) pdfFemale = thinkbayes2.EstimatedPdf(femaleRates) low, high = 0, 100 n = 100...
from shapely.geometry import Point, box import psycopg2 import numpy as np import sys from configobj import ConfigObj import os from geojson2aoi import geojson2aoi import argparse parser = argparse.ArgumentParser(description='created a grid in a database based on extent of geojson file. Requires fields: srs') parser....
# encoding: utf8 from __future__ import unicode_literals, print_function from .tokenizer_exceptions import TOKEN_MATCH from .language_data import * from ..attrs import LANG from ..language import Language class Hungarian(Language): lang = 'hu' class Defaults(Language.Defaults): tokenizer_exceptions ...
# -*- coding: utf-8 -*- # UTF-8 encoding when using korean user_input = input() # print ("Hello Goorm! Your input is " + user_input) num = int(user_input) print(int(num * (num - 1) / 2))
from PyObjCTools.TestSupport import TestCase, min_os_level import Contacts class TestCNChangeHistoryFetchRequest(TestCase): @min_os_level("10.15") def testProtocols(self): self.assertProtocolExists("CNKeyDescriptor") @min_os_level("10.15") def test_methods(self): self.assertResultIsBO...
import pandas as pd import numpy as np data = pd.read_csv("../cleaned.csv", usecols=range(2, 14)) def get_keyskills(): key_skills = [] data['Key Skills'].apply(lambda x:key_skills.extend(str(x).lower().strip().split("|")) if type(x) == str else x) key_skills = pd.Series(list(map(lambda x: x.strip(), key_s...
""" This module provides compatibility for different async libs. Currently only supporting asyncio, but should not be too hard to add e.g. Trio, once Uvicorn has Trio support. """ import asyncio async def sleep(seconds): """An async sleep function. Uses asyncio. Can be extended to support Trio once we suppor...
from .Task import Task class SwipeCard(Task): def __init__(self): self.wallet_card_position = (850, 830) self.card_swipe_start_position = (666, 404) self.card_swipe_start_position = (666, 404) self.card_swipe_end_position = (1395, 404) self.y_offset = 37 super()....
#!/usr/bin/env python from __future__ import print_function import argparse import os import re import json import urllib import urllib2 from xml.dom import minidom import flickrapi import tornado.web from tornado.web import URLSpec, RequestHandler as RQ api_key = '24b43252c30181f08bd549edbb3ed394' this_dir = os.p...
from convert_to_one import convert_to_one from extract_from_pdf import extract_from_pdfs from overall_consolidator import consolidate_all from per_class_consolidator import consolidate_each_class # This is the script that run all operations to consolidate the final results results_directory = "C:\\Users\\Fabio Barros\...
import matplotlib import matplotlib.pyplot as plt #import matplotlib.pylab import matplotlib.mlab as mlab import numpy as np # USE TEX: #matplotlib.use('ps') matplotlib.rc('text', usetex=True) base = "ising_4x4_beta_1.0" fig = plt.figure(figsize=(4, 2.5)) #ax = fig.add_subplot(111) #plt.xticks(np.arange...
import pandas as pd import numpy as np from scipy import sparse from pandas.testing import assert_frame_equal from numpy.testing import assert_array_equal from encode_ffw import encode_user_ffw, get_user_counter, encode_df from sklearn.preprocessing import OneHotEncoder def test_attempts_counter(): df_exercise_t...
from src.Problem.constraint import Constraint class NotEqualConstraint(Constraint): def __init__(self, region, other_region): super().__init__([region, other_region]) self.region = region self.other_region = other_region def satisfied(self, assignment): if self.region not in a...
from django.contrib import admin from django.urls import path,include from django.views.generic import View, TemplateView , RedirectView from .views import * app_name = 'polls' urlpatterns = [ path('<int:question_id>/',DetailsView.as_view(),name='detail'), path('<int:question_id>/result',result,name='re...
class Solution: def generate(self, numRows: int) -> List[List[int]]: if numRows==0: return [] pas = [] pas.append([1]) for i in range(1,numRows): #starts at second row. first row [1] already appended. t = [1] for j in range(1,i+1): ...
from unittest import TestCase from elyra_client import ElyraClient import traceback import sys class NotebookTestCase(TestCase): def __init__(self, test_method, nb_entities_list, continue_when_error, host, username): TestCase.__init__(self, methodName=test_method) self.nb_entities_list = nb_entit...
x = int(input()) if x >= 10: print("Horse") elif 1 < x < 10: print('Duck') else: print('Baguette') print("Horse" if x >= 10 else "Duck" if 1 < x < 10 else "Baguette") # 这样写起来非常的简洁,可以将之前的代码都改正成这种格式
from SCons.Script import Builder, File, Scanner ######################################################################## # # run error detection propagation analysis on a weighted pushdown system # __edp_action = [['$__VALGRIND', '$EDP', '$EDP_FLAGS', '--error-codes=$ERROR_CODES', '--temps', '--tentative', '--quer...
from helpers import alphabet_position, rotate_character def encrypt(text, key): encrypted = "" key_loc = 0 for char in text: if char.isalpha(): rot = alphabet_position(key[key_loc]) key_loc += 1 key_loc = key_loc % len(key) encrypted += rotate_chara...
# coding: utf-8 """ Memsource REST API Welcome to Memsource's API documentation. To view our legacy APIs please [visit our documentation](https://wiki.memsource.com/wiki/Memsource_API) and for more information about our new APIs, [visit our blog](https://www.memsource.com/blog/2017/10/24/introducing-rest-apis...
from airflow.hooks.postgres_hook import PostgresHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class LoadFactOperator(BaseOperator): """ With dimension and fact operators, you can utilize the provided SQL helper class to run data transformations. Most of the logic is w...
# Generated by Django 2.0.7 on 2018-08-03 21:45 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('bases', '0003_project_subproject'), migrations.swappable_dependency(settings.AUTH_U...
#a Imports from overlap import c_overlap_2d #a Structure element class - a piece of 'background' that has an image and is slightly dynamic #c c_structure_element class c_structure_element( object ): """ An element of a structure This has a position and a list of images that can be used to represent the el...
# Generated by Django 2.1.7 on 2019-08-24 16:29 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='ImageReport', fields=[ ...
"""Models for Posts app.""" from django.contrib.contenttypes.models import ContentType from django.db import models from comments.models import Comment class Post(models.Model): """Model for Posts.""" CHOICE_PRIVATE = 'private' CHOICE_FRIENDS = 'only friends' CHOICE_PUBLIC = 'public' PRIVACY_C...
#!/usr/bin/env python3 from pysolclient import * from pysolclient import _defaultMsgCallback from pysolclient import _defaultEventCallback import sys def main_run(): context = Context() sprops = SessionProperties(HOST=sys.argv[1], VPN_NAME=sys.argv[2], USERNAME=sys.argv[3]) rxMsg = c_int(0) ...
import os import glob from datetime import datetime # Handles output from the TF model def handle_output(out): result = out.split('\n')[3] sign = result.split() score = float(sign[1][7:-1]) return sign[0], score if __name__ == '__main__': # start timer start_time = datetime.now() counter ...
import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor def exportar_csv(titulo,precio,detalle,lugar): import csv with open('vehiculo.csv','a', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter = ',') data = list(zip(titulo,precio,d...
import urllib, json class Behance(object): def __init__(self, userName, config): self.baseUrl = config.get('BEHANCE','behanceBaseUrl') self.accessKey = config.get('BEHANCE','behanceClientId') self.userName = userName def getBehanceInfoForUser(self): print("***********BEHANCE ...
from typing import Tuple from PIL import Image, ImageFont, ImageDraw import string def density_of_letter(im: Image, size: Tuple[int]) -> float: x, y = size black_pixel_count = 0 for i in range(x): for j in range(y): pixel = im.getpixel((i, j)) if pixel == 0: ...
import pages from behave import fixture from selenium.webdriver import Chrome, ChromeOptions def get_browser(context, *args, **kwargs): context.browser = Chrome(*args, **kwargs) context.main_page = pages.MainPage(driver=context.browser) yield context.browser context.browser.quit() @fixture def selen...
from data.db_session import db_auth from typing import Optional from passlib.handlers.sha2_crypt import sha512_crypt as crypto from services.classes import User, Target, Equipments, Project, Schedule from datetime import datetime, timedelta from services.accounts_service import get_equipment_project_priority, update_eq...
#!/usr/bin/python """Object used for parsing US patent xml.""" import logging import xml.etree.ElementTree as ET class USPatent(object): def __init__(self, s3_location): # figure out how to make the s3 location accessible self.data = {} self.xml = ET.parse(s3_location) self.GatherData() ...
''' Created on Apr 30, 2013 @author: ALEX This is the ID3 Decision Tree classification algorithm for CSE151 ''' import sys, math def id3(fname): total = [] f1 = [] f2 = [] f3 = [] f4 = [] label = [] allf = [] with open(fname,'r') as file: for line in file: total.ap...
import django_filters from django_filters import DateFilter from .models import * class accountFilter(django_filters.FilterSet): class Meta: model = Account fields = { 'account_balance' : {'exact'}, 'account_inital_balance' : {'exact'}, 'account_catagory' : {'ex...
#En el ejercicio anterior, creó un programa que calculaba el área de un triángulo #cuando se conocía la longitud de su base y su altura. También es posible calcular #El área de un triángulo cuando se conocen las longitudes de los tres lados. Deje s1, s2 y s3 #ser la longitud de los lados. Sea s = (s1 + s2 + s3) / 2....
import pandas as pd def biggest_variation(num_of_features=50): '''Returns array of column names with biggest variation''' train = pd.read_csv('../data/train.csv') train_features = train.drop(columns=['ID_code', 'target']) feature_names = list(train_features.columns.values) train_describe =...
""" Return string after all adjecent duplicates are removed. Example: Input: s = "abbaca" Output: "ca" For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, s...
""" :keywords: bubble sort, sorting """ import copy def bubble_sort(lst): """ :description: bubble sort - compare adjacent items n times, moving smaller to towards the front :time: O(n^2) :space: O(1) """ if len(lst) < 2: return lst for i in range(len(lst)): for j in reve...
### day1 # `ctrl` + `shift` + `p` : 사용 가능한 command palette print('Hello, world!') number = 10 string = '문자열' bools = True print (number, string, bools) ## 숫자형 (1.int 2.float 3.complex) # int a = 3 type(a) # type 확인 print(type(a)) ## bool print(type(False)) # False = 0 / 0,0 / () / [] / {} / '' / None ## 문자형 gree...
# -*- coding: utf-8 -*- # !/usr/bin/env python3 """ @Author : ziheng.ni @Time : 2021/2/19 14:21 @Contact : nzh199266@163.com @Desc : 组件模块 """ from __future__ import annotations from abc import ABC, abstractmethod from typing import List class Component(ABC): """ 组件抽象类,声明了复杂对象和简单对象的公共操作方法。 """ @...
import datetime print(datetime.MAXYEAR) print(datetime.MINYEAR) print(datetime.time) print(datetime.timezone) import datetime print(datetime.datetime.today()) now=datetime.datetime.today() other=datetime.datetime(1995,3,12,22,10) print(now-other) datetime.timedelta(18901,55547,421000) print...
from ROOT import TH1D,TCanvas,TH1 from array import array from ROOT import TH1D,TFile,TCanvas, THStack,TF1, TH1,TLegend,kRed,kBlue,TPad,gPad,TLine,kBlack,TMath ,TGraph,TMultiGraph,TLatex,kGreen from ROOT import gROOT,gStyle,gPad,gStyle,kTRUE gStyle.SetOptStat(0) path1 = '../' path2 = '/uscms_data/d3/dmendis/80x/CMSS...
import time from models import Model, SQLMixin, SQLBase from sqlalchemy import Column, String class Board(Model): def __init__(self, form): self.id = None self.title = form.get('title', '') self.ct = int(time.time()) self.ut = self.ct class BoardSQL(SQLBase, SQLMixin): __tabl...
# coding: utf-8 from enum import Enum from six import string_types, iteritems from bitmovin_api_sdk.common.poscheck import poscheck_model class ChromaLocation(Enum): UNSPECIFIED = "UNSPECIFIED" LEFT = "LEFT" CENTER = "CENTER" TOPLEFT = "TOPLEFT" TOP = "TOP" BOTTOMLEFT = "BOTTOMLEFT" BOTTO...
# coding: utf-8 from unittest import TestCase from models.models import Client, ClientAttributeError class TestClient(TestCase): def test_instance(self): client0 = Client('Pedro', 'Rua José Mendes da Silva, 326', '082.960.826-59', 20, '!Q@W#E$R%T') # must accept self.assertEqual(client0.i...
""" This script is the overall manager for all the scripts that run under this experimental framework of s-systems. It makes calls to the parsermanager : mathods : logger : author: Subhodeep Moitra (smoitra@cs.cmu.edu) BSD License """ from parsermanager import ParserManager import sys,os, copy from utility impo...
# TODO: If salt-master is not in localhost, uncomment and change API URL #API_URL = 'https://YOURSALTMASTER.net' # TODO: Generate a random key with os.urandom(24) SECRET_KEY = '' # Uncomment next line if you want to add sentry support # You'll also need to install raven[flask] # SENTRY_DSN = "https://YOUR_SENTRY_DSN" ...
import pandas as pd import numpy as np from sklearn.feature_extraction.text import TfidfVectorizer import nltk from nltk.corpus import stopwords from nltk.stem.snowball import SnowballStemmer import re import sys import warnings import matplotlib.pyplot as plt from tensorflow.keras.preprocessing.text import Tokenizer f...
import json import requests from django.http import HttpResponse from django.views import View from dynaconf import settings from rest_framework.permissions import IsAuthenticated from rest_framework.viewsets import ModelViewSet from apps.api.impl.v1.serializers import WorkSerializer from apps.education.models import...
from celery import Celery broker = 'redis://127.0.0.1:6379/1' backend = 'redis://127.0.0.1:6379/2' app = Celery(broker=broker, backend=backend, include=['order_celery.tasks'])
# Databricks notebook source #dbutils.widgets.dropdown("reset_all_data", "false", ["true", "false"]) # COMMAND ---------- # MAGIC %run ./00-setup $reset_all_data=false # COMMAND ---------- # MAGIC %python # MAGIC # MAGIC import re # MAGIC # MAGIC def display_plan(sql :str, highlightExchange :bool = False, highlig...
from flask import render_template, url_for, escape, redirect, abort, request from flask_login.utils import login_required, current_user from app import core from database import db, models @core.route('/admin/posts', methods=['GET', 'POST']) @login_required def adminPosts(): status = 0 if request.method == 'PO...
import math mod = 10**9+7 n, w, t, r = [int(_) for _ in input().split()] w, t, r = sorted([w,t,r]) ans = 1 for i in range(w+1,n+1): ans *= i ans = ans // (math.factorial(t) * math.factorial(r)) print(ans % mod)
# -*- coding: utf-8 -*- """The Android WebViewCache database event formatter.""" from __future__ import unicode_literals from plaso.formatters import interface from plaso.formatters import manager # TODO: move to android_webview.py. class AndroidWebViewCacheFormatter(interface.ConditionalEventFormatter): """Forma...
import logging class Strategy: def __init__(self, name: str, bet_strategy, put_strategy): self.name = name self.bet_strategy = bet_strategy self.put_strategy = put_strategy logging.debug( f"strategy initialized: {self.name}, put strategy: {self.put_strategy.name}, bet s...
# -*- coding: utf-8 -*- # tool for adding cards to database # probably not very useful for anyone else on the enitre world # author: bocianu@gmail.com <Wojciech Bociański> import sqlite3 import codecs import sys dbfilepath = '../assets/cardlib.db' LANG_PL = 0 LANG_EN = 1 LANG = LANG_PL resourceNames = [ 'money', ...
from openmdao.api import ExplicitComponent class WingParamComp(ExplicitComponent): def setup(self): self.add_input('taper') self.add_input('b') self.add_input('croot') self.add_output('mac') #mean aerodynamic chord of the wing self.add_output('Ybar') #spanwise location ...
import datetime from types import SimpleNamespace from django.contrib.auth.models import AnonymousUser from django.template import Context, Template from django.test import TestCase from app.models import User def render_perms_for_user(user): context = Context({'request': SimpleNamespace(user=user)}) templa...
import re inputFile = 'file.txt' outputFile = 'file.csv' # open file f = open(inputFile, 'r') newData = f.read() f.close() # clear unwanted spaces newData = re.sub(' [ ]+?([^ ])', r' \1', newData, flags=re.M) newData = re.sub('^ ', '', newData, flags=re.M) newData = re.sub(' $', '', newData, flags=re.M) # parse bo...
from time import sleep import random from typing import Any, Optional from stellar_sdk import Server import requests from django.conf import settings from django.core.management.base import BaseCommand, CommandError, CommandParser from scanner.models import Badge, StellarAccount # from pprint import pprint class Co...
# Copyright 2018 Cristian Mattarei # # Licensed under the modified BSD (3-clause BSD) License. # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the ...
#imports import pycurl import cStringIO import json import os #get_input asks user for zip code/city def get_input(): city = "" city = raw_input(["enter a zip code, or enter 'exit' to exit"]) city = city.lower() return city #make_url constructs a URL based on the user input def make_url(city): url_front = "http:...
# -*- encoding: utf-8 -*- from django.shortcuts import render from django.views.generic import TemplateView, CreateView, UpdateView, DeleteView, DetailView, ListView from django.views.generic.edit import FormView, FormMixin from django.core.urlresolvers import reverse_lazy, reverse from .forms import CampoDForm, Pers...
# https://binarysearch.com/problems/Text-Editor class Solution: def solve(self, s): stack = [] i = 0 while i < len(s): if s[i] == '<': if i < len(s) - 1 and s[i+1] == '-': if len(stack) > 0: stack.pop() ...
class Node: def __init__(self, value): self.value = value self.left = None self.right = None self.parent = None def __repr__(self): return str(self.value) def in_order_traversal(node): if node is None: return None # successor is in our right tree ...
#---------------------------------------------------# # AUTHOR: Lakshay Saini # # CODE: TitleAclaris # # WORK: We are extracting titles from GOOGLE Docs # #---------------------------------------------------# import os import sys import csv import re import...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Copyright 2010-2012 Asidev s.r.l. 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 b...