text stringlengths 8 6.05M |
|---|
import argparse
import os
import re
from modules.fitsfile import writefits
from modules.metafile import writemeta
from modules.textfile import writetext
def _outputpathlist(outputdir, gal):
file_endings = ['-folded-moments.txt',
'-folded-spectra.fits',
'-folded-misc.txt']
... |
# as in tambura
from pippi import dsp
from pippi import tune
midi = {'lpd': 7}
def play(ctl):
param = ctl.get('param')
lpd = ctl.get('midi').get('lpd')
scale = [ dsp.randchoose([1, 5, 8]) for s in range(dsp.randint(2, 4)) ]
freqs = tune.fromdegrees(scale, root='eb', octave=dsp.randint(0, 2))
fre... |
__all__ = ["PAGE_TITLE"]
PAGE_TITLE = "Google" |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-11-09 10:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nova', '0030_sql'),
]
operations = [
migrations.CreateModel(
na... |
from string import ascii_lowercase, ascii_uppercase
from random import choice, randint, shuffle
from Dictionaries import uppercasedict as updict
from Dictionaries import lowercasedict as lowdict
from os import system
import sys
sys.path.insert (0, '~/Desktop/Matteo/Informatica/Python/Password/Dictionaries')
pool = []... |
from rv.modules import Behavior as B
from rv.modules import Module
from rv.modules.base.dcblocker import BaseDcBlocker
class DcBlocker(BaseDcBlocker, Module):
behaviors = {B.receives_audio, B.sends_audio}
|
from select import select
from tkinter import *
import tkinter.scrolledtext as scrolledtext
Keyboard_App = Tk()
Keyboard_App.title("Master keyboard")
Keyboard_App.resizable(0, 0)
def select(value):
if value == "<-":
txt = text.get(1.0, END)
val = len(txt)
text.delete(1.0, END)
tex... |
date = (3,30,2019,9,25)
print(f"{date[3]:0>2}/{date[4]:0>2}/{date[2]} {date[0]:0>2}:{date[1]:0>2}") |
# encoding: utf-8
# A flag to differentiate between client and worker code
IS_CLIENT = False
|
# -*- coding: utf-8 -*-
"""
Created on Sun May 31 21:42:17 2020
@author: maurop
"""
# =============================================================================
# Imports
# =============================================================================
import time
#=================================================... |
from gensim.models.phrases import Phraser
from gensim.models import Word2Vec
from scipy.spatial.distance import cosine
from nltk import pos_tag
from collections import defaultdict
from ..nlp_utils.common import *
from ..nlp_utils.pos_tag import *
from ..nlp_utils.time import *
import numpy as np
init_tagger = Tagger(lo... |
from django import forms
from django.core import validators
from myapp.models import User
from .models import *
class Authentic(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User
fields =("username","password","first_name","last_name", 'email')
... |
def merge_the_tools(string, k):
# your code goes here
t = []
for i in range(len(string)//k):
start = i * k
t.append(string[start: start + k])
#print(t)
for s in t:
u = ""
for c in s:
if c not in u:
u += c
print(u)
if __name__ ==... |
# From http://astroweb.case.edu/jakub/TA/aitoff.py
#USED to project Aitoff data points and grid lines (assumes input in degrees)
import numpy as np
import matplotlib.pyplot as plt
degrad = np.pi/180.
def project(li,bi,lz):
sa = li-lz
if len(sa) == 1:
sa = np.zeros(1)+sa
x180 = np.where(sa >= 180... |
# -*- coding: utf-8 -*-
from irc3.utils import wraps_with_context
from irc3.compat import asyncio
import venusian
import re
def plugin(wrapped):
"""register a class as plugin"""
setattr(wrapped, '__irc3_plugin__', True)
setattr(wrapped, '__irc3d_plugin__', False)
return wrapped
class event:
r"""... |
import configparser
import networkx as nx
import itertools
import math
import random
import json
from tqdm import tqdm
import sys
import time
import timeit
import pickle
import sys
from pathlib import Path
class GenGraph(object):
def __init__(self, config_path):
self.config = configparser.ConfigParser()
... |
# -*- coding: utf-8 -*-
#!/usr/bin/env python
import time
import homie
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
from modules.homiedevice import HomieDevice
from modules.mysql import db
class Schedule(HomieDevice):
_states = {}
def loopHandler(self):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
# Funktioner
def find_prot(ecoli_dict, protein_name):
u""" Finder et protein i ecoli_dict med nøglen protein_name
args:
ecoli_dict: dict(String, String)
protein_name: String
returnerer:
protein_sequence: String
fejl:
Hvis ikke der findes et ... |
from django.shortcuts import render
from django.views.generic import View
# Create your views here.
class Taxation_ListView(View):
def get(self, *args, **kwargs):
return render(self.request, "taxation/taxation_list.html")
class November_2019View(View):
def get(self, *args, **kwargs):
return re... |
def detect_anagrams(the_word, word_list):
return [word for word in word_list
if sorted(the_word.lower()) ==
sorted(word.lower()) and
the_word.lower() != word.lower()]
|
#by 李星星
import poplib
import html
import time
import DBaction
from email.parser import Parser
from email.header import decode_header
from email.utils import parseaddr
email='1678120695@qq.com'
password='veztvpjocggzjbdb2'
password1='veztvpjocggzjbdb'
server='pop.qq.com'
def judgePass(E,P):
try:
server = p... |
from django import forms
CATEGORIES = [
("Home", "Home"),
("Technology", "Technology"),
("Sport", "Sport"),
("Fashion", "Fashion")
]
"""
Source: https://docs.djangoproject.com/en/3.0/topics/forms/#rendering-fields-manually
https://docs.djangoproject.com/en/3.0/ref/forms/widgets/
"""
class Lis... |
from django.contrib import admin
from doctors.models import Specialization, Domain, Doctor, Appointment, Review, LocationDoctor, BusinessWork
admin.site.register(Specialization)
admin.site.register(Domain)
admin.site.register(Doctor)
admin.site.register(Appointment)
admin.site.register(Review)
admin.site.register(Loc... |
import numpy as np
from math import sqrt
import pandas as pd
from sklearn.datasets import load_iris
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
# sklearn
X = [[2, 3], [5, 4], [8, 1], [4, 7], [7, 2], [9, 6]]
y = [1, 0, 0, 0, 0, 0]
from sklearn.neighbors import KNeighborsClassi... |
import torch
import torch.nn as nn
from models import model_utils
from utils import eval_utils
from collections import OrderedDict
import numpy as np
def fuse_features(feats, opt):
if opt['fuse_type'] == 'mean':
feat_fused = torch.stack(feats, 1).mean(1)
elif opt['fuse_type'] == 'max':
feat_fus... |
from flask import Flask,render_template,request,jsonify,redirect,send_file
from flask import request
import requests
import json
from flask_restful import Resource, Api, reqparse
import string
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.errorhandler(405)
def page_not_found(e):
# note that we... |
from keras.engine import Model
from keras.layers import Flatten, Dense, Input
from keras_vggface.vggface import VGGFace
from keras import optimizers
from keras.preprocessing.image import ImageDataGenerator
from keras.models import load_model
import numpy as np
import cv2
import os
from flask import Flask, request, re... |
from app import db
from flask_login import UserMixin
from werkzeug.security import generate_password_hash, check_password_hash
""" many-to-many = User to Group table """
User_Group = db.Table("User_Group",
db.Column('id', db.Integer, primary_key=True),
db.Column('user_id', ... |
class ItemPage():
# here are elements' ids or x_paths in item page
itemPageTitle_id = "sg.com"
topItem_xp = "TextView[3]"
topItemText_xp = "TextView[3]"
filterBtn_id = "sg.com"
resolutionSwitch_id = "sg.com"
scheduleSwitch_id = "sg.com"
meetingSwitch_id = "sg.com"
showResu... |
import unittest
from six import string_types
from pandas.core.frame import DataFrame
from opengrid.library.kmi import *
class KMITest(unittest.TestCase):
"""
Class for testing the kmi web scraper
"""
def test_fetch_website(self):
"""
Check if the URL works
"""
self.as... |
#
# gdb helper commands and functions for Linux kernel debugging
#
# module tools
#
# Copyright (c) Siemens AG, 2013
#
# Authors:
# Jan Kiszka <jan.kiszka@siemens.com>
#
# This work is licensed under the terms of the GNU GPL version 2.
#
import gdb
from linux import cpus, utils, lists
module_type = utils.CachedTy... |
from distutils.core import setup
from Cython.Build import cythonize
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy as np
ext_modules = [
Extension(
"asfamcparser",
["AMCFileReader.pyx"],
libraries=["m"],
extra_compile_args = ["-ffast-ma... |
#oef5
n = input("Give a number: ")
result = int(n)+int(n+n)+int(n+n+n)
print("The result is : {}".format(result)) |
import pickle
from flask import Flask, request, render_template
app = Flask(__name__)
@app.route("/", methods= ["GET","POST"])
@app.route("/login", methods=['POST','GET'])
def login():
return render_template("login.html")
@app.route("/about", methods=['POST','GET'])
def about():
return render_tem... |
from suds.transport import Reply
from http.client import HTTPMessage
import unittest.mock as mock
import soap
import re
from .http import HttpTransport
try:
from lxml import etree
except ImportError:
try:
# Python 2.5
import xml.etree.cElementTree as etree
except ImportError:
try... |
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 20 20:39:13 2021
@author: Gustavo
@mail: gustavogodoy85@gmail.com
"""
def tabla_mult(number):
number = number
header = ('0','1','2','3','4','5','6','7','8','9')
print(f'{"":>4s} {"%4s %4s %4s %4s %4s %4s %4s %4s %4s %4s" % header}')
print(f'{"":->55}')
... |
#!/usr/bin/python
# coding=utf-8
"""
Author: moshed
Created on 21/12/2020
"""
from pysat.solvers import Solver
from pysat.solvers import Glucose3
ids = ["311395834", "314981259"]
F, T = False, True
status_map = {'U': 0, 'H': 1, 'S': 2, 'I': 3, 'Q': 4, '?': 5, 'SN': 6, 'R': 7, 'LQ': 8, 'EQ': 9, 'VAC': 10}
# transla... |
import os
# Cache Dosyasını bulmak için yapmanız gerekenler:
# Windows arama yerine %appdata% yazın.
# Discord dosyasını açın.
# İçinde bulunan cache dosyasının konumunu kopyalayın
print("\u001b[35;1mDiscord Cache Decrypter")
print("\u001b[37;1mMert Kemal Atılgan tarafından kodlanmıştır.")
print("https://git... |
TOKEN = '1505312478:AAHf1SaNEL4TntYbOrjS6NkSmjIHxqhhYok' |
# -*- coding:utf-8 -*-
import numpy as np
import pandas as pd
import matplotlib as mpl
from scipy.stats import multivariate_normal
from sklearn.mixture import GaussianMixture
from sklearn.metrics.pairwise import pairwise_distances_argmin
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
# enab... |
class Solution(object):
def isPalindrome(self, head):
"""
:type head: ListNode
:rtype: bool
"""
if not head or not head.next: return True
fast, slow = head.next, head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
... |
'''
Created on Oct 18, 2011
@author: Rob
'''
import morpher.pydbg.pydbg as pydbg
import morpher.pydbg.defines as defines
import struct
def sprintf_handler(dbg):
addr = dbg.context.Esp + 0xC
count = dbg.read_process_memory(addr, 4)
count = int(struct.unpack("L",count)[0])
print "Caught... |
from protorpc import messages
class IngredientMessage(messages.Message):
ingredient = messages.StringField(1, required=True)
quantity = messages.FloatField(2, required=True)
unit = messages.StringField(3, required=True)
class RecipeMessage(messages.Message):
title = messages.StringField(1, required=Tr... |
import numpy as np
def xavier_initializer(shape):
coeff = np.sqrt(2/(shape[0]+shape[1]))
return normal_initializer(shape)*coeff
def normal_initializer(shape):
return np.random.randn(shape[0], shape[1])
def get_initializer(name):
return {'xavier': xavier_initializer,
'normal': normal_in... |
__author__ = 'Dell'
import csv
from datetime import datetime
# import matplotlib
# matplotlib.use('ps')
import matplotlib.pyplot as plt
import numpy as np
startreader = csv.reader(open("start-fav-indegree.csv", "r"), delimiter='\t')
endreader = csv.reader(open("end-fav-indegree.csv", "r"), delimiter='\t')
base = da... |
#!/usr/bin/env python
import argparse
from datetime import datetime
from neomodel import config
from runner import HdfsToNeo4j
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Import HDFS Directory to Neo4j.')
parser.add_argument('--neo4j-url', type=str,
dest='neo4j_url', de... |
#!/usr/bin/env python3
import argparse
import os
import sys
from mpi4py import MPI
import numpy as np
import adios2
import plxr
from PIL import Image
## viewer.py
usage_msg = """Usage: plxr <operation> <op_args>
Where <operation> is one of the following:
extract
insert
list
"""
def commandline (argv)... |
#!/usr/bin/python
#\file concat_imgs.py
#\brief certain python script
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Aug.26, 2021
import cv2
import numpy as np
if __name__=='__main__':
img1= cv2.imread('../cpp/sample/rtrace1.png')
img2= cv2.flip(img1, 0)
cat_v= np.concatenate((img1,... |
from sklearn.datasets import load_iris
iris = load_iris()
# print(iris.data)
# print(iris.target)
from sklearn.preprocessing import StandardScaler
print("standard scaler:")
print(StandardScaler().fit_transform(iris.data))
from sklearn.preprocessing import MinMaxScaler
print("min max scaler")
print(MinMaxScaler().fit... |
#!/usr/local/bin/python3
# Decided to try mkaing my own interpretation of a deck just to see how it would compare to the books.
import collections
class MyDeck:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'J', 'Q', 'K', 'A']
suits = ['Spades', 'Diamonds', 'Hearts', 'Clubs']
Card = collections.namedtuple('Card'... |
'''
Given an int n, return True if it is within 10 of 100 or 200.
Note: abs(num) computes the absolute value of a number.
near_hundred(93) → True
near_hundred(90) → True
near_hundred(89) → False
'''
def near_hundred(n):
return (-10 <= n - 100 <= 10) | (-10 <= n - 200 <= 10) |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import cv2
from sklearn.model_selection import train_test_split, StratifiedKFold
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Conv2D,... |
from back_machine.config.parser import get_config_from_json
import argparse
import time
from math import ceil
import zmq
def collector(addressReceive, addressSend, numTerminate, is_test=False):
"""
takes binary image and pushes it to the contours_node.
Args:
addressReceive: string of the ip addres... |
from django.contrib import admin
# Register your models here.
from .models import ZooSpamForm
admin.site.register(ZooSpamForm) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_m3u_dump
----------------------------------
Tests for `m3u_dump` module.
"""
import os
import pytest
from click.testing import CliRunner
from m3u_dump import cli
from m3u_dump.m3u_dump import M3uDump
@pytest.fixture(scope='session')
def music_dir(tmpdir_fact... |
import os
from utils import load_as_dictionary
config = load_as_dictionary(os.environ.get("CONFIG_PATH", "config/config.yaml"))
|
from flask import Flask, render_template, request, jsonify
from evaluate import tweetscore
import evaluate
import emoticonTranslator
from text2speech import synthesize_text_file
app = Flask(__name__)
@app.route('/', methods=['POST', 'GET'])
def result():
if request.method == 'POST':
phrase = request.form[... |
def matrix_multiple(first, second):
ret = [[0 for i in range(8)] for j in range(8)]
for i in range(8):
for j in range(8):
for k in range(8):
ret[i][j] += first[i][k] * second[k][j]
ret[i][j] = ret[i][j] % 1000000007
return ret
matrix = [0 for i in range(3... |
# coding: utf-8
# In[13]:
import psycopg2 as pg
import csv
import os
import sys
def csv2db(dbname,schema,host,user,password,csvfile):
connect_cmd='dbname="'+dbname+'" user="'+user+'" host="'+host+'" password="'+password+'"'
try:
conn = pg.connect(connect_cmd)
except:
print("Unable to ... |
import csv
import glob
import logging
import os
import re
from datetime import datetime
from random import Random
import global_constants
import function_library as func_lib
import consecutive_words_format
import word_list_format
from tqdm import tqdm
# Logging
logs_folder = 'logs'
os.makedirs(logs_folder, exist_ok... |
# 访问已有的数据综合
# 数据集可视化
# 加载本地数据集
# 输出显示测试集数据数和训练集数据数
import tensorflow as tf
boston_housing = tf.keras.datasets.boston_housing
(train_x,train_y),(test_x,test_y) = boston_housing.load_data()
# print("Training set:",len(train_x))
# print("Testing set:",len(test_x))
# 改变数据集划分比例
(train_x,train_y),(test_x,test_y... |
import math
def iszhishu(num):
"""
最优解法
"""
if num <= 3:
return num > 1
sqrt_num = math.sqrt(num)
for i in (2, sqrt_num + 1):
if num % i == 0:
return False
return True
def iszhishu_best(num):
"""
最优解法
我们继续分析,其实质数还有一个特点,就是它总是等于 6x-1 或者 6x+1,其中 x 是大于... |
from challenges.hashtable.hashtable import HashTable
def test_create():
hashtable = HashTable()
assert hashtable
def test_predictable_hash():
hashtable = HashTable()
initial = hashtable._hash('spam')
secondary = hashtable._hash('spam')
assert initial == secondary
def test_in_range_hash():
... |
import torch
class Polynom(torch.nn.Module):
def __init__(self):
super().__init__()
self.w = torch.nn.Parameter(torch.zeros(10, dtype=torch.float64))
self.b = torch.nn.Parameter(torch.zeros(1, dtype=torch.float64))
self.power = torch.concat([torch.ones(5, dtype=torch.float64),
... |
#!/bin/python
import sys
import re
def valid_byr(value):
year = re.search(r"\d{4}", value)
if year is None:
return False
return (int(year.group()) >= 1920 and int(year.group()) <= 2002)
def valid_iyr(value):
year = re.search(r"\d{4}", value)
if year is None:
return False
retur... |
from nltk.tokenize.stanford_segmenter import StanfordSegmenter
import re
import os
stanford_corenlp_path = r'/media/mcislab3d/Seagate Backup Plus Drive/zwt/stanford corenlp'
def segment_sentences_char(sentence_list):
return [' '.join(i) for i in sentence_list]
def segment_sentences(sentence_list):
... |
def function(*args):
print(type(args))
function(1,2,3,5,6,7,7)
"""sum =0
def function1(*args): #variable length argument
for each in args:
sum += each
"""
#function1(1,2,3,5,6,7,7)
def function3(**kwargs):
print(type(kwargs))
function3(a=1,b=2,c=4)
def function4(**kwargs):
sum=0
f... |
# You can use this file to execute any code to be run when importing a module
# in the package for the first time
print("Hello from the init.py") |
#!/usr/bin/env python
"""
Delete CouchDB requests.
Delete requests in CouchDB specified by names (CouchDB IDs) in the input
file. Needs to have credentials for accessing CMS web ready in
$X509_USER_CERT $X509_USER_KEY, or proxy stored in /tmp/x509up_u<ID>
CMSCouch.Database only sets _deleted=True flag (all fields r... |
#!/usr/bin/env python
from dsx import *
# Declaration of all MWMR fifos
tg_demux = Mwmr('tg_demux' , 32, 2)
demux_vld = Mwmr('demux_vld' , 32, 2)
vld_iqzz = Mwmr('vld_iqzz' , 128, 2)
iqzz_idct = Mwmr('iqzz_idct' , 256, 2)
idct_libu = Mwmr('idct_libu' , 64, 2)
libu_ramdac = Mwmr('libu_ramdac', 8*... |
#The Game of choosing a number between 0 and 100
import random
Q = (random.randint(0, 100))
print Q
UP = int(100)
Down = int(0)
I = int(0)
while (I==0):
print "your guss should be between" , (Down,UP)
guss=raw_input ("Enter your guss:\n")
guss=int(guss)
if guss==Q:
I=int(1)
if guss<Q:
Down=guss
if guss>... |
#!/usr/bin/python
#\file slider4.py
#\brief New QWidget slider class
#\author Akihiko Yamaguchi, info@akihikoy.net
#\version 0.1
#\date Apr.15, 2021
import sys
from PyQt4 import QtCore,QtGui
class TSlider(QtGui.QWidget):
def __init__(self, *args, **kwargs):
super(TSlider, self).__init__(*args, **kwargs... |
from solvent import config
from solvent import run
from solvent import label
from upseto import gitwrapper
import logging
import os
class Submit:
def __init__(self, product, directory):
self._product = product
self._directory = directory
git = gitwrapper.GitWrapper(os.getcwd())
sel... |
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# make the figure 3 from Hajo and Marks paper.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
if __name__ == '__main__':
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot as plt
import xarray as xr
import pandas as ... |
from flask import Blueprint, request, jsonify
from regression_model.predict import make_prediction
from flask_cors import CORS
from api.config import get_logger
#from api.validation import validate_inputs
_logger = get_logger(logger_name=__name__)
prediction_app = Blueprint('prediction_app',__name__)
CORS(predict... |
from doisouum import DoisOuUm
x = DoisOuUm(6000)
x.salvar_log(False)
x.executar()
|
#!/usr/bin/python3
""" 101-main """
from models.base import Base
from models.rectangle import Rectangle
from models.square import Square
if __name__ == "__main__":
list_rectangles = [
Rectangle(2**i, 2**i) for i in range(1, 5)
]
list_squares = [
Square(2**i) for i in range(5, 9)
]
... |
channels = ['3mu', '2mu1e', '2e1mu', '3e']
allChannels = ['all'] + channels
# This adds more versatile channels. Avoid long lists of different flavor channels like Humuhumunukunukuapua
class channel:
def __init__(self, nElectrons=-1, nMuons=-1):
self.nE = nElectrons
self.nM = nMuons... |
import sys
import glob
from multiprocessing import Process,Manager
from threading import Thread
import serial
import time
import os
import json
import hashlib
class bm:
msg=""
rec_arr=Manager().list()
send_arr=Manager().list()
serial_enable=Manager().dict()
ser=None
def __init__(self,serial_port... |
class Gato:
'''Classe para trabalhar com gatos'''
#Construtor
def __init__(self, nome):
self.nome = nome;
print('Seu gato se chama', self.nome)
#Metodos diversos
def peso_gato(self, peso):
self.peso = peso
if (self.peso > 5.0):
print('Seu gato está ... |
a = 1
b = 2
c =2
a = 2
class info():
def __init__(self):
self.color="red"
|
import speech_recognition as sr
from textblob import TextBlob
from playsound import playsound
from gtts import gTTS
import argparse
from google.cloud import language
from google.cloud.language import enums
from google.cloud.language import types
GOOGLE_CLOUD_SPEECH_CREDENTIALS =
counter = 0
def speaker(toTalk):
... |
#!/usr/bin/env python
import os
import jinja2
import webapp2
template_dir = os.path.join(os.path.dirname(__file__), "templates")
jinja_env = jinja2.Environment(loader=jinja2.FileSystemLoader(template_dir), autoescape=False)
class BaseHandler(webapp2.RequestHandler):
def write(self, *a, **kw):
return se... |
from typing import Iterable, Any
def ilen(coll: Iterable) -> int:
"""
Функция получения размера генератора
>>> foo = (x for x in range(10))
>>> ilen(foo)
10
"""
counter = 0
for i in coll:
counter++
return counter
def flatten(mas: Iterable[Any]) -> Iterable[Any]:
"""
... |
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from modeltranslation.admin import TranslationAdmin
from snippets.admin import BaseModelAdmin
from snippets.modeltranslation import get_model_translation_fields
from snippets.seo import models
class SEOAd... |
import http.server
import socketserver
# Обробка запитів клієнта до сервера
handler = http.server.SimpleHTTPRequestHandler
# Сервер буде запущений на порту 1234
with socketserver.TCPServer(("", 1234), handler) as httpd:
# Сервер буди виконуватись постійно
httpd.serve_forever() |
"""
LeetCode - Hard
"""
import ast
import json
"""
Serialization is the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be reconstructed later in the same or another computer environment.
D... |
from fioo.fioo import * |
from shutil import copy
from os.path import join as path, dirname, abspath, expanduser
from os import remove
tin = path('src', 'bakedbeans', 'tin.template')
# Grab modules from the tin and run them, using the local setup_config.
# We don't attempt to fill in the setup_config template from the tin, because
# there's t... |
class GraphTraverser(object):
def __init__(self, graph, eventSet, eventMapping, networkNodes):
self.graph = graph
self.eventSet = eventSet
self.eventMapping = eventMapping
self.networkNodes = networkNodes
def dfs(self, v, reverseList, timestamp, dst, port, src=None):
... |
import glob, random, os, json
files = glob.glob(
"assets/images/thumbs/*.jpg")
captions = {}
for file in files:
filename = file.split("/")[-1].split(".")[0]
captions[filename] = filename
fw = open("data/full-captions.json", 'w')
json.dump(captions, fw, ensure_ascii=False, indent=4,
sort_keys=True,... |
import time
from openerp.osv import fields, osv
from report import report_sxw
from openerp.tools.translate import _
import logging
_logger = logging.getLogger('reportes')
class reportes_reportc(report_sxw.rml_parse):
total_exento = 0.0
total_cf = 0.0
total_per = 0.0
total_pro = 0.0
rectificador = 0.0
rectifi... |
file_name = 'learning_python.txt'
with open(file_name) as file_object:
content_0 = file_object.read()
print(content_0)
print("-----")
with open(file_name) as file_object:
line = file_object.readline()
print(line)
print("-----")
with open(file_name) as file_object:
lines = file_object.readlines()
... |
"""
Queries of label queries
"""
def gql_labels(fragment):
"""
Return the GraphQL labels query
"""
return f'''
query ($where: LabelWhere!, $first: PageSize!, $skip: Int!) {{
data: labels(where: $where, first: $first, skip: $skip) {{
{fragment}
}}
}}
'''
GQL_LABELS_COUNT = '''
query($where: L... |
import random
import itertools
word = "SOS"
rows = None
cols = None
def searchWord(grid,i,j,word,direction):
flag=True
if direction == "orizontia":
j=j+1
for k in range(1,len(word)):
if j<cols and word[k]==grid[i][j]:
j=j+1
else:
flag=Fal... |
"""
Quick Sort:
Time Complexity :
1) Average case : O(n log n)
2) Worst Case : O(n^2)
"""
def quicksort(arr):
size_arr = len(arr)
if size_arr < 2:
return arr
if size_arr == 2:
if arr[0] > arr[1]:
arr[0], arr[1] = arr[1], arr[0]
... |
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/ptok")
def ptok():
return render_template("ptok.html")
@app.route("/goodbye")
def goodbye():
return render_template("goodbye.html")
@app.route("/listdic")
def listdic():
page="<h1>this a cool list heehee</h1>"
list = [0, 1 , 2... |
from django.test import TestCase
from util.util import UtilABNT
# class TestUtil(TestCase):
# """
# Testes da classe UtilABNT
# """
# def test_nome_comum_bem_formatado(self):
# self.assertEquals('José', UtilABNT.nome_abnt(self, 'José Saramago'))
#
# def test_sobrenome_comum_bem_formatado(s... |
##################################################
# PRICING A DOWN-AND-OUT BARRIER PUT OPTION
# stock obeys GBM with r=0.1, s=0.4 (time unit = year = 252 days), current
# price 50. 60 day european put option, with strike 50, but a barrier at 30
# - below this the option gets knocked out thus reducing risk for seller.
... |
import cv2
import numpy as np
img = cv2.imread('Lenna.png')
rows, cols = img.shape[:2]
M=np.float32([[1,0,40],[0,1,40]])
dst = cv2.warpAffine(img,M,(cols,rows))
cv2.imshow('Original',img)
cv2.imshow('Traslation',dst)
cv2.waitKey(0)
cv2.destroyAllWindows() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.