text stringlengths 38 1.54M |
|---|
import asyncio
from server.integrations import openexchangerates
from server.models.repository import Currency
async def start_refresh_rates_routine():
asyncio.create_task(_refresh_rates_routine())
async def _refresh_rates_routine(delay=False):
if delay:
await asyncio.sleep(60 * 60 * 24)
asynci... |
#!/usr/bin/python
# _*_ coding:utf-8 _*_
__author__ = "dqz"
#引用函数getpass 实现密码输入的隐藏
import getpass
name = input("输入用户名:")
password = input("输入密码:")
no = 0
while True:
if name == 'tom' and password =='123':
print("登入成功")
break
else:
no += 1
print("登入失败%s次" %no)
n... |
class Solution:
def compressString(self, S: str) -> str:
compressed = []
n = len(S)
if n <= 1:
return S
count = 0
for i in range(n):
count += 1
if i + 1 >= n or S[i] != S[i + 1]:
compressed.append(S[i])
compr... |
__author__ = 'vikram'
import sys
import os
from os import listdir
from os.path import isfile, join
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import matplotlib.lines as mlines
import argparse
plt.close("all")
parser = argparse.ArgumentParser(description="V vs C viz script to visualize rslt c... |
from numpy import *
a = array(eval(input()))
d = ''
c = size(a)
b = 0
for j in a:
for i in a:
if j > i:
d = i
i = j
j = d
print(a) |
print(" Welcome to ABC shop ")
print("-----Please login-----")
username = input("username : ")
password = input("password : ")
u1 = "123456"
p1 = "987654"
if username == u1 and p1 == password:
print("Login complete")
print(" >>> Please select menu <<< ")
print("1.Fired rice = 35 Bth")
print("2.Fired... |
#! /usr/bin/python
# coding = utf-8
print
import urllib2
import re
page = 1
url = 'http://news.baidu.com/?qq-pf-to=pcqq.group/page/' + str(page)
user_agent = "Mozi;;a/4.0 (compatible; MSIE 5.5; Windows NT)"
headers = { 'User-Agent' : user_agent}
try:
request = urllib2.Request(url, headers = headers)
respons... |
import unittest
class tree:
def __init__(self, root):
self.root = root
class tree_node:
def __init__(self, data, left, right):
self.data = data
self.left = left
self.right = right
#preorder, postorder and inorder prints
def print_tree(tr):
if tr.root is None:
retu... |
#!/usr/bin/python env
# -*- coding: utf-8 -*-
import logging
import os
import re
import time
from Queue import Queue
import xlwt
from keystoneauth1 import loading, session
from novaclient import client
from xlrd import open_workbook
DEFAULT_TIMEOUT = 10 * 60
WAITING_QUEUE_MAX_SIZE = 10
LOGGER = None
MAX_COLUMNS = 2
... |
#/bin/python
import numpy as np
import random;
class Grid_Mdp_Id:
def __init__(self, initial_state = None):
self.states = [1,2,3,4,5,6,7,8]
self.terminal_states = dict()
self.terminal_states[6] = 1
self.terminal_states[7] = 1
self.terminal_states[8]... |
from __future__ import absolute_import
# Version 4.0
import logging as logger
import copy
import splunk.clilib.cli_common as comm
from splunk.clilib.control_exceptions import ArgError
import splunk.clilib._internal as _internal
import splunk.clilib.info_gather as info_gather
import splunk.clilib.apps as apps
impor... |
import numpy as np
import matplotlib
# matplotlib.use("TkAgg")
import matplotlib.pyplot as plt
# matplotlib.use("qt5agg")
from typing import *
import pandas as pd
import seaborn as sns
import math
sns.set()
class Accuracy(object):
def at_radii(self, radii: np.ndarray):
raise NotImplementedError()
clas... |
import math
n=int(input(int))
m=int(input(int))
o=m*n
root=math.sqrt(o)
if(int(root+0.5)**2==o):
print("yes")
else:
print("no")
|
#!/usr/bin/env python
# vim: set expandtab tabstop=4 shiftwidth=4:
# Copyright (c) 2019, CJ Kucera
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must reta... |
import torch
import torch.nn as nn
import argparse
import torchvision
import tqdm
class Logistic_regression(nn.Module):
def __init__(self):
super(Logistic_regression, self).__init__()
self.logistic = nn.Linear(784, 10)
self.sigmoid = nn.Sigmoid()
def forward(self, x):
x = se... |
#!/usr/bin/env python
import httplib
import re
class Tree(object):
def __init__(self):
self.children = []
self.found = []
self.data = None
def request(url):
conn = httplib.HTTPConnection('localhost:8080')
headers = {
'host': 'localhost:8080',
'upgrade-insecure-requ... |
#!/usr/bin/env python3
# -*-encoding: utf-8-*-
# by David Zashkol
# 2 course, comp math
# Taras Shevchenko National University of Kyiv
# email: davendiy@gmail.com
class Element:
def __init__(self, item):
self.item = item
self.next = None
self.pre = None
def __repr__(self):
r... |
import sys
class Screen:
def __init__(self, width: int, length: int):
# initialise the 2D array of cells
self._cells = []
for _ in range(length):
row = []
for _ in range(width):
row.append(".")
self._cells.append(row)
# creates an ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 29 02:07:44 2020
@author: shaol
"""
import DB.dbFetch as dbFetch
import pandas as pd
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
def gen_CA_spread(start,end):
#generate bean and meal and oil comparison
m... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'application_gui.ui'
#
# Created by: PyQt5 UI code generator 5.15.2
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 import QtCo... |
import pandas as pd
import numpy as np
from collections import defaultdict
import math
from datetime import datetime
from tqdm import tqdm
import librosa
from sklearn.preprocessing import scale
class Sun:
"""This class is made up of several functions,
the main ones take as input latitude,longitude and a date... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import unicode_literals
from django.contrib.auth.admin import User
from django.contrib.auth.decorators import login_required
from django.forms.models import inlineformset_factory
from django.shortcuts import render, HttpResponseRedirect
fro... |
# shopping_cart.py
import operator
import pandas
from datetime import datetime
import os
from dotenv import load_dotenv
import csv
load_dotenv()
def to_usd(my_price):
return f"${my_price:,.2f}" #> $12,000.71
"""
Converts a numeric value to usd-formatted string, for printing and display purposes.
Sour... |
from math import ceil
ari_scale = {
1: {'ages': '5-6', 'grade_level': 'Kindergarten'},
2: {'ages': '6-7', 'grade_level': '1st Grade'},
3: {'ages': '7-8', 'grade_level': '2nd Grade'},
4: {'ages': '8-9', 'grade_level': '3rd Grade'},
5: {'ages': '9-10', 'grade_level': '4th Gra... |
# coding: utf-8
from collections import Counter
import itertools
import os
import operator
import pickle
import sqlite3
import string
import time
import jieba
import more_itertools
import numpy as np
import zhon.hanzi as zh
CUR_DIR = os.path.dirname(__file__)
PARENT_PATH = os.path.dirname(CUR_DIR)
VOCAB2IX_PATH = os... |
# Passing a List
def greet_users(names):
"""Print a simple greeting to each user in the list."""
for name in names:
print(f"Hello, {name.title()}!")
usernames = ['vasu', 'deva', 'tiru']
greet_users(usernames) |
import os, win32api, win32con
for file in os.listdir("./"):
info = os.stat(file)
attr = win32.api.GetFileAttributes(file)
if NOT (attr & (win32con.FILE_ATTRIBUTE_SYSTEM)):
print(file)
|
# Generated by Django 3.1.3 on 2020-11-25 07:01
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('services', '0003_auto_20201124_0946'),
]
operations = [
migrations.AlterField(
model_name='service',
name='list_info... |
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from jandan_xxoo.items import JandanItem
class JandanSpider(CrawlSpider):
name = 'jandan.net'
allowed_domains = ['jandan.net']
start_urls = [
'http://jandan.net/ooxx'
]
rules = (
... |
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# 等高线画法
# https://www.pynote.info/entry/matplotlib-contour
# def f(x, y):
# return x ** 2 + y ** 2
#
# # X, Y = np.mgrid[-10:11, -10:11]
# X, Y = np.mgrid[-2:2, -2:2]
# print(X)
# # 配列転置
# # print(Y.T)
# print(Y)
#
# Z = f(X... |
"""
argparse
import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+',
help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const',
... |
soma=0
for i in range(20,31):
n1=int(input("Digite um número"))
soma = soma+n1
if(soma%2==0):
print(soma, "= ele é par")
else:
print(soma, "= ele é ímpar")
print(" A somatória é: ", soma)
Pressione Shift + Tab para acessar o histórico do bate-papo.
|
from models.House import House
class Infrastructure(House):
def __init__(self, area, price, rating, adress, number_of_rooms, city):
self.area = area
self.price = price
self.rating = rating
self.adress = adress
self.number_of_rooms = number_of_rooms
self.city = city
... |
from django.urls import path
from ex03 import views
urlpatterns = [
path('', views.table, name='table'),
] |
import json
import os
import tarfile
import time
import typing
import zipfile
from contextlib import suppress
from pathlib import Path
import requests
from openpyxl import load_workbook
from qtpy.QtCore import QByteArray, Qt
from qtpy.QtGui import QIcon
from qtpy.QtWidgets import (
QCheckBox,
QDialog,
QFor... |
# -*- coding: utf-8 -*-
from core import httptools, scrapertools
from platformcode import logger
def get_video_url(page_url, url_referer=''):
logger.info("(page_url='%s')" % page_url)
video_urls = []
vid = scrapertools.find_single_match(page_url, "(?:e|f)/([A-z0-9_-]+)")
if not vid: return ... |
import os
from hackpad_api.hackpad import Hackpad
hackpad = Hackpad(api_scheme = os.getenv('HACKPAD_API_SCHEME'),
api_domain = os.getenv('HACKPAD_API_DOMAIN'),
sub_domain = os.getenv('HACKPAD_SUB_DOMAIN'),
consumer_key = os.getenv('HACKPAD_CLIENT_ID'),
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mainUI.ui'
#
# Created by: PyQt5 UI code generator 5.13.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
... |
from injector import Module
from app.equipment_types.repositories import EquipmentTypeRepository
from tests.equipment_types.mocks import equipment_type_repository
class MockEquipmentTypeModule(Module):
def configure(self, binder):
binder.bind(EquipmentTypeRepository, to=equipment_type_repository)
|
import gym
import matplotlib.pyplot as plt
from CartPole.randomAgent.ReplayMemory import Memory
# parametres
numEpisods = 10
maxStep = 100
bufferSize = 10000
batchSize = 100
# pour calculer la récompense dans chaque épisode
sumreward = 0
# instances
env = gym.make('CartPole-v1')
memory = Memory(bufferSize)
scores= [... |
from fractions import Fraction
from helpers import memoize
class Num:
def __init__(self, const_val):
self.val = const_val
def compute_value(self):
return self.val
class Add:
def __init__(self, expr1, expr2):
self.expr1 = expr1
self.expr2 = expr2
def compute_value(self, modulus):
val1 = self.expr1.com... |
# To change this license header, choose License Headers in Project Properties.
# To change this template file, choose Tools | Templates
# and open the template in the editor.
__author__="DarkRodry"
__date__ ="$25-sep-2013 16:55:48$"
import glob
from mutagen.mp3 import MP3
from mutagen.id3 import ID3, APIC, TIT2, TPE1... |
from math import sqrt, floor
prime_limit = 2000000
prime_sum = 0
def is_prime(n):
if n == 1:
return False # 1 is not a prime Number
elif n == 2:
return True
elif n > 2 and n % 2 == 0:
return False
else:
maxdivisor = int(floor(sqrt(n)) + 1)
for divisor in range... |
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)
GPIO.setup(18, GPIO.OUT)
GPIO.output(13, False)
GPIO.output(11, False)
GPIO.output(18, False)
GPIO.cleanup()
|
from numpy import*
v1 = array(eval(input("v1: ")))
v2 = array(eval(input("v2: ")))
vet = zeros(3, dtype=int)
for i in range(size(v1)):
if v1[i]>v2[i]:
vet[0] = vet[0] + 1
elif v1[i] == v2[i]:
vet[1] = vet[1] + 1
elif v1[i] < v2[i]:
vet[2] = vet[2] + 1
print(vet) |
import pytest
from unittest.mock import patch
from rdftools.scripts import rdf
def test_rdf_script(capfd):
# We use capfd, not capsys, because the output we want to capture comes
# from the subprocess spawned by rdf, not rdf itself.
expected_out = 'usage: rdf-query [-h] [-v] [-b BASE] [-i [INPUT [INPUT .... |
def calculate_sum(val1, val2):
'''doc string
Parameters
----------
val1 : [type]
[description]
val2 : [type]
[description]
Returns
-------
[type]
[description]
'''
result = val1 + val2
return result |
some_list = list(range(5,10))
print(some_list)
for item in some_list:
print(some_list.index(item))
|
from django.db import models
class Client(models.Model):
fullName = models.CharField('Full name',max_length=50)
email = models.EmailField('Email address')
phone = models.CharField('Phone number', max_length=20)
message = models.TextField()
def __str__(self):
return self.fullName |
import random,numpy as np,cv2
from keras.callbacks import TensorBoard, ModelCheckpoint, Callback,ReduceLROnPlateau
from keras import callbacks
from perception.bases.trainer_base import TrainerBase
from configs.utils.utils import genMasks,visualize,genMasks2
from configs.utils.img_utils import img_process,img_process1
... |
import pandas as pd
import numpy as np
import requests
from bs4 import BeautifulSoup as BeSo
import lxml
import html
def lastMonthDay (year, month) :
'''La función devuelve el último día del mes del año pasado por parámetros.
El año y el mes han de tener un formato numérico.'''
import calendar
month_li... |
import os
import time
import datetime
import json
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import mixins
from rest_framework import generics
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth.... |
#!/usr/bin/python
#
# icarusay.py
#
# Written by Earl Cash <erl@codeward.org> in 2014.
import sys, os, getopt, math, time, signal
def sig_handler (signo, frame):
sys.exit (signo)
def usage ():
print "Usage:"
print " "+ os.path.basename (sys.argv[0]) +" [OPTIONS]"
print "\nOptions:"
print " -l=N\tprint N li... |
# Viraland is a batch-job control program, especially for bioinfomatics data
# file flow control and analysis. Viraland can be run directly in Python 3
# console or be run with a configuration file.
# This program also supply a good amount of API to make data processing more
# flexible.
# author: Yubing Hou
# license: ... |
import requests
from almaany.models import Hasil, Pencarian, create_tables
from almaany.parser import Parser
create_tables()
class Endpoint(object):
AL_WASEETH = "http://www.almaany.com/ar/dict/ar-ar/{q}/?c=المعجم الوسيط"
class Almaany(object):
"""class tentang almaany"""
def __init__(self, mujam, expire... |
k, m, n = map(int, input().split())
cook = n // k
if n % k != 0:
cook += 1
cook = cook * m * 2
print(cook) |
import sys
# http://www.techiedelight.com/find-duplicate-element-limited-range-array/
# Given a limited range array of size n where array contains elements in
# range 1 to n-1 with one element repeating, find duplicate number.
# using xor :: O(n) O(1) space
def find_duplicate(arr):
print(arr)
xor = 0
fo... |
from tkinter import *
import random
from tkinter import messagebox
def generate():
entry.delete(0,END)
pwd = generatepwd()
entry.insert(10,pwd)
def generatepwd():
low = "abcdefghijklmnopqrstuvwxyz"
medium = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"
strong = "ABCD... |
'''
Created on Dec 24, 2015
@author: Sameer Adhikari
'''
from collections import Counter, defaultdict
def freq_dist_imperative(data, divisor):
'''Imperative version of the frequency distribution function.'''
data_divided = [item //divisor for item in data]
counter = Counter(data_divided)
return count... |
import logging
import redis
from lib.map_traversal.map_traversal_queue import MapTraversalQueue
from lib.string_functions.string_operations import state_postal_codes, strip_state_postal_codes, remove_blacklisted_words
logger = logging.getLogger('')
class StreetNameStatistics():
def __init__(self, queue):
... |
# This file contains the fucntions to import gwas data, filter variants, make bed, and pull gNOMAD data
import sys
import subprocess
import tempfile
# Function 1: Get significant SNPS from GWAS import
# Default p-val = p<5E-8
# Make P-val adjustable
# Input: GWAS table (should define default)
# Output: array of si... |
# Generated by Django 3.0.7 on 2020-07-14 19:48
import appBookflix.models
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('appBookflix', '0001_initial'),
]
operations = [
migrations.A... |
import random
# TODO DA RIFARE LA CLASSE ACTOR. FA SCHIFO.
# ________________________________________________________________________________________
class Actor:
def __init__(self, dir, posX, posY, type):
self.posX = posX
self.posY = posY
self.type = type
self.dir = dir
def ge... |
#!/usr/bin/python3
# coding: utf-8
import time
import random
import sys
import os
tmppath = '/tmp/obd2'
if len(sys.argv) > 1:
if sys.argv[1] == 'php':
tmppath = 'tmp/obd2'
class OBDFetch:
def stop(self):
print("Stopping");
if os.path.exists(tmppath+'/stop'): os.remove(tmppath+'/stop')... |
import copy
import numpy as np
import torch
def apply_by_index(items, transform, idx=0):
"""Applies callable to certain objects in iterable using given indices.
Parameters
----------
items: tuple or list
transform: callable
idx: int or tuple or or list None
Returns
-------
result... |
import base64
import random
from coreapis import cassandra_client
from coreapis.utils import LogWrapper
from coreapis.cache import Cache
def basic_auth(trust):
username = trust['username']
password = trust['password']
base64string = base64.b64encode(
'{}:{}'.format(username, password).encode('UTF... |
#!/usr/bin/env python
# coding: utf-8
"""
gettup - A command-line file sharing utility for ge.tt
usage:
$ gett > show help
$ gett file1 file2 file3 > upload files (in same share)
$ gett *.py > linux globs (upload)
$ gett *.py -p > paralleliz... |
import numpy as np
import operator
class PokerGame:
shared_cards = np.array([])
def __init__(self, NumberOfPlayers = 2):
self.players = np.array([Player(i) for i in range(NumberOfPlayers)])
self.deck = Deck()
def play(self):
self.shared_cards = np.array([])
#... |
from bs4 import BeautifulSoup
import requests
import os
import json
import sqlite3
from datetime import date
def statFinder():
url = "http://www.espn.com/nba/hollinger/teamstats"
r = requests.get(url)
soup = BeautifulSoup(r.text, 'html.parser')
outer = soup.find('table', class_="tablehead"... |
"""do_qa.py
Purpose: wrapper script for qa module.
"""
from qa import qa_data
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
req_named = parser.add_argument_group('Required named arguments')
req_named.add_argument('-m', action='store', dest='dir_mast', ty... |
class BaseDTO:
@staticmethod
def serialize_single(obj):
if hasattr(obj, "to_dict"):
return obj.to_dict()
return obj
def serialize(self, objs):
if type(objs) is list:
return [self.serialize_single(obj) for obj in objs]
return self.serialize_single(o... |
def seq_rev(data, start, stop):
if start < stop-1:
data[start], data[stop-1] = data[stop-1], data[start]
seq_rev(data, start+1, stop-1)
return data
seq = [1, 3, 8, 9, 12, 16]
print(seq_rev(seq, 0, 6)) |
# Create a variable savings
savings = 100
# Print out savings
print(savings)
# Create a variable savings
savings = 100
# Create a variable growth_multiplier
growth_multiplier = 1.1
# Calculate result
result = savings * (growth_multiplier**7)
print(result)
# Print out result
# Create a va... |
from itertools import combinations
N = int(eval(input()))
S = input().split(' ')
K = int(eval(input()))
num = 0
den = 0
for c in combinations(S,K):
den+=1
num+='a' in c
print(float(num)/den)
|
import tensorflow as tf
from tensorflow.contrib.layers import xavier_initializer
from RNN.conv_gru import ConvGRUCell
from RNN.conv_stlstm import ConvSTLSTMCell
from RNN.PredRNN import PredRNNCell
from config import c
from config import config_gru_fms
from tf_utils import conv2d_act
class Encoder(object):
def __... |
import pytest
from wishlist.domain.customer.exceptions import CustomerAlreadyRegisteredError
from wishlist.domain.customer.ports import CreateCustomer
from wishlist.test.helpers import AsyncMock
class TestCreateCustomer:
async def test_create_customer_with_success(
self,
customer_dict,
c... |
#!/usr/bin/env python
# coding:utf-8
# Copyright (C) dirlt
class Solution(object):
def numDistinct(self, s, t):
"""
:type s: str
:type t: str
:rtype: int
"""
n = len(s) + 1
m = len(t) + 1
st = []
for i in range(n):
st.append([1] +... |
"""empty message
Revision ID: 6a1d5b118d31
Revises: 495a88477b8c
Create Date: 2018-03-07 15:19:31.806238
"""
# revision identifiers, used by Alembic.
revision = '6a1d5b118d31'
down_revision = '495a88477b8c'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic ... |
from .AssetEditor import AssetEditor, AssetEditorModule, getAssetSelectionManager
from .AssetBrowser import AssetBrowser
from .AssetPreviewer import AssetPreviewer
from . import AssetSearchEnumerator
from . import CommonAsset
from . import EngineAsset |
# Generated by Django 3.2 on 2021-06-24 14:30
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('student_profile_app', '001... |
import datetime
from Generator.ClassicMap import ClassicMap
from Generator.ExtendedMap import ExtendedMap
def dummy():
import json
return json.dumps({"tile": [
{"index": 0, "dice": 0, "resource_type": "DESE"},
{"index": 1, "dice": 5, "resource_type": "OREE"},
{"index": 2, "dice": 2, "... |
# Generated by Django 3.1.4 on 2020-12-16 03:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0022_cupon_amount'),
]
operations = [
migrations.AddField(
model_name='order',
name='received',
... |
"""Unit tests of everything related to retrieving the version
There are four tree states we want to check:
A: sitting on the 1.0 tag
B: dirtying the tree after 1.0
C: a commit after a tag, clean tree
D: a commit after a tag, dirty tree
The tests written in this file use pytest-virtualenv to achieve isolation.
Eac... |
# coding=utf-8
# Copyright 2016 Google 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 required by appl... |
stack = []
serving = {}
b = 0
n = int(raw_input())
while n:
s = raw_input().split(" ")
if s[0] == '1':
stack.append(int(s[1]))
else:
serving[stack.pop()] = b
b = b + 1
n = n - 1
for i in serving:
print serving[i], |
#Author: Aritri Paul
#To execute the code, type the following command in your terminal: python3 DOHRange.py
import sys
import pyshark
text_file=open("Commonsubsq.txt",'r')
sizeset=set()
for line in text_file:
for i in range(len(line)):
if(line[i]=='['):
array=[]
s=""
i+... |
LEGIBLE = ('legibility', 'legible')
ILLEGIBLE = ('legibility','illegible')
ENGLISH = ('language', 'english')
NOT_ENGLISH = ('language', 'not english')
NA = ('langauge', 'na')
MACHINE_PRINTED = ('class', 'machine printed')
HANDWRITTEN = ('class', 'handwritten')
OTHERS = ('class', 'others')
def inter(list1, list2):
... |
favorite = "JihongZhang"
for i in favorite:
print(i, end=' \t')
print('\n')
for num in range(2, 9):
print(num, end = '\t')
total = 0
for num2 in range(1, 10, 2):
total += num2
print(total)
|
from django.utils.text import slugify
from django.utils.crypto import get_random_string
def get_generate_slug(instance, new_slug=None):
if new_slug is not None:
slug = new_slug
else:
try:
slug = slugify(instance.title)
except AttributeError:
slug = slugify(insta... |
import torch
import numpy as np
from skfuzzy.membership import trimf
class Activations:
"""
Regular activation functions used in the module are defined here.
The activation functions used are:
* Sigmoid
* Relu
* Swish
* Leaky Relu
* tanh
"""
## Sigmoid Ac... |
import torch
x = torch.randn(4, 4)
print(x.size()) # torch.Size([4, 4])
y = x.view(16)
print(y.size()) # torch.Size([16])
|
import datetime
import random
import re
from django.conf import settings
from django.contrib.auth.models import User
from django.db import models
from django.db import transaction
from django.template.loader import render_to_string
from django.utils.hashcompat import sha_constructor
ACTIVATED = 'ALREADY_ACTIVATED'
S... |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
"""
:auteur 1: DOUCHET Benjamin
:auteur 2:
:groupe: SESI 12
:date: vendredi 27 mars 2020
:objet: Travail numéro 9 (Nombres premiers et témoins de Fermat)
"""
from matplotlib import pyplot as plt
from math import log
from random import randrange
from tp6_arithmet... |
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="plotapi",
version="1.0.0",
description="Engaging visualisations, made easy.",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://plotapi.com... |
#!/usr/bin/python
# encoding: utf-8
# -*- coding: utf8 -*-
"""
Created by PyCharm.
File: LinuxBashShellScriptForOps:download_file.py
User: Guodong
Create Date: 2016/9/13
Create Time: 15:41
"""
import hashlib
import os
import socket
import sys
import urllib
from timeout impor... |
from graph import *
import math as m
def alien(x, y, size, mirror):
body(x, y, size, mirror)
apple(x+2.5*size*mirror, y-size*3.3, size / 25, mirror)
def apple(x, y, size, mirror):
r = 25 * size
penColor(245, 84, 84)
penSize(0)
brushColor(245, 84, 84)
circle(x, y, r)
penColor("black... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
import asyncio
from typing import Any, Dict, List, Optional, Tuple
from fbpcs.entity.container_instance... |
import FWCore.ParameterSet.Config as cms
#AOD content
RecoVertexAOD = cms.PSet(
outputCommands = cms.untracked.vstring('keep *_offlinePrimaryVertices__*',
'keep *_offlinePrimaryVerticesWithBS_*_*',
'keep *_offlinePrimaryVerticesFromCosmicTracks_*_*',
'keep *_nuclearInteractionMaker_*_*',
... |
# Script i use to match with Rockyou
# Put RockYou in same folder or change path match
test_pass = input('Enter Password to test: \n')
path = 'rockyou.txt'
rslt = False
print("\nTesting.. {}".format(test_pass))
with open(path, errors="ignore") as fp:
line = fp.readline()
c = 1
while line:
line = ... |
class Parent:
def public_method(self):
return 'from Parent.public_method'
def another_public_method(self):
return 'from Parent._private_method'
class Child(Parent):
def public_method(self):
return 'from Child.public_method'
def another_public_method(self):
return 'cal... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.