content stringlengths 5 1.05M |
|---|
from django.contrib import admin
from .models import Trailer
# Register your models here.
admin.site.register(Trailer) |
from sklearn.datasets import load_breast_cancer
dataset=load_breast_cancer()
x=dataset.data
y=dataset.target
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.2)
from logistic_regression import LogisticRegression
clf=LogisticRegression(lr=0.01,n_iters=10... |
# En este ejercicio se nos solicitó:
# 1.- El retorno total y anualizado de tres stocks: SPY, VWO y QQQ entre 2015 y 2021 (ambos inclusive)
# 2.- Graficar el retorno acumulado de los stocks indicados durante ese mismo período
# Para ambos ejercicios se nos indicó que utilizáramos la free API key de Alpha Vantage
impor... |
# Aula 13 (Estrutura de Repetição for)
from time import sleep
for c in range(10, -1, -1):
print(c)
sleep(1)
print('BOOM!')
|
# Collaborators: https://www.decodeschool.com/Python-Programming/Branching-Statements/Divisible-by-3-or-not-in-python#:~:text=Program%20Explanation,3%20using%20print()%20method.
#
for x in range (2, 51):
if x % 3==0:
print ("{} is divisible by 3".format(x))
else:
print ("{} is not divisible b... |
import argparse
import os
from watermark_add_dct import do_singleRun_dct
from watermark_add_dwt import do_singleRun_dwt
from image_utils import encoding
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="main")
# general options
parser.add_argument(
"--inFolder",
type... |
"""Filters that are used in jobfunnel's filter() method or as intermediate
filters to reduce un-necessesary scraping
Paul McInnis 2020
"""
import logging
from collections import namedtuple
from copy import deepcopy
from datetime import datetime
from typing import Dict, List, Optional, Tuple
import nltk
import numpy as... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .ctdet import CtdetTrainer
from .exdet import ExdetTrainer
train_factory = {
'exdet': ExdetTrainer,
'ctdet': CtdetTrainer,
}
|
p1 = int(input('digite o primeiro termo:'))
r = int(input('digite a razõ da P.A'))
d= p1 + (10-1) * r
for c in range(p1-1,d,r):
print(c) |
import factory
import time
import random
from spaceone.core import utils
class MetricFactory(factory.DictFactory):
key = factory.LazyAttribute(lambda o: utils.generate_id('metric'))
name = factory.LazyAttribute(lambda o: utils.random_string())
unit = {
'x': 'Datetime',
'y': 'Count'
... |
# Copyright © 2019 Province of British Columbia
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
import lasagne
from lasagne.regularization import regularize_network_params, l2, l1
import time
import theano
import numpy as np
from theano.tensor import *
import theano.tensor as T
import gc
import sys
sys.setrecursionlimit(50000)
#then import my own modules
import seqHelper
import lasagneModelsFingerprints
#get m... |
"""Profile model."""
# Django
from django.db import models
# Utilities
from feelit.utils.models import FeelitModel
class Profile(FeelitModel):
""" Profile model.
Profile holds user's public data like bio, posts and stats.
"""
user = models.OneToOneField('users.User', on_delete=models.CASCADE)
... |
import re
ncr_replacements = {
0x00: 0xFFFD,
0x0D: 0x000D,
0x80: 0x20AC,
0x81: 0x0081,
0x81: 0x0081,
0x82: 0x201A,
0x83: 0x0192,
0x84: 0x201E,
0x85: 0x2026,
0x86: 0x2020,
0x87: 0x2021,
0x88: 0x02C6,
0x89: 0x2030,
0x8A: 0x0160,
0x8B: 0x2039,
0x8C: 0x0152,... |
"""The Twinkly API client."""
import logging
from typing import Any
from aiohttp import ClientResponseError, ClientSession
from .const import (
EP_BRIGHTNESS,
EP_COLOR,
EP_DEVICE_INFO,
EP_LOGIN,
EP_MODE,
EP_TIMEOUT,
EP_VERIFY,
)
_LOGGER = logging.getLogger(__name__)
class TwinklyClient:... |
"""add private column to group
Revision ID: 9612aba86eb2
Revises: 789ac8c2844f
Create Date: 2021-06-06 10:31:28.453405
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "9612aba86eb2"
down_revision = "789ac8c2844f"
branch_labels = None
depends_on = None
def upg... |
from stormberry.config import Config
import signal
import sys
import stormberry.logging
from stormberry.station import WeatherStation
from stormberry.plugin import ISensorPlugin, IRepositoryPlugin, IDisplayPlugin, PluginDataManager
from stormberry.plugin.manager import get_plugin_manager
class SignalHandling(object):... |
from use_cases.encryption.makeEncryptString import *
from use_cases.encryption.makeDecryptString import *
from use_cases.encryption.makeCreateKeyPair import *
|
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------... |
import abc
class Policy(object, metaclass=abc.ABCMeta):
"""
General policy interface.
"""
@abc.abstractmethod
def get_action(self, observation):
"""
:param observation:
:return: action, debug_dictionary
"""
pass
def reset(self):
pass
class Ex... |
import os
os.chdir("Python/Logging")
# log_settings changes sys.excepthook to log_settings.log_exceptions, so
# importing log_settings is sufficient to capture uncaught exceptions to the
# log file, meanwhile they are also (still) printed to stdout
import log_settings
# adds 'Starting new program!' with timestamp to... |
class IBSException(Exception):
pass
#TODO: This doesn't make sense for negative numbers, should they even be allowed?
class NumericValue():
""" To store a number which can be read to/from LE or BE """
def __init__(self, value):
self.value = value
@classmethod
def FromLEBytes(cls, databytes... |
from pyrocko import automap
import math
import shutil
from pyrocko import model, gmtpy
from pyrocko.moment_tensor import magnitude_to_moment as mag2mom
from pyrocko.moment_tensor import to6
from pyrocko.guts import Object, Float, String, List
class ArrayMap(automap.Map):
stations = List.T(model.Station.T(), optio... |
import sys
import json
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
class Fetcher:
'''
The crawler class used for retrieving information from sodexo's menu page
Note:
Blitman Commons is not yet included in sodexo's page. The class should throw an ... |
import math
def round_up(n, multiple):
"""
can be used to ensure that you have next multiple if you need an int, but have a float
n = number to check
multiple = number you'd like to round up to
EX:
num_ranks = 64
num_ios = 26252
this is not an even number if you divide
returns t... |
## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
# fetch values from package.xml
setup_args = generate_distutils_setup(
packages=["mushr_rhc_ros"], package_dir={"": "src"}
)
setup(install_requires=["numpy"... |
# Copyright 2018 Google, Inc.,
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writin... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from nltk.stem.porter import PorterStemmer
from nltk.tokenize import word_tokenize
import random
from tqdm import tqdm
from summariser.ngram_vector.base import Sentence
from summariser.ngram_vector.state_type import *
from utils.data_helpers import *
# from summariser.utils.data_helpers import *
class Vectoriser:
... |
# coding: utf-8
# In[7]:
import numpy as np
#toy example of fixImages_stackocclusions
#a = np.arange(16).reshape(4, 2, 2)
#b = a + 2
#print("a")
#print(a)
#print(2*'\n')
#print("b")
#print(b)
#print(2*'\n')
#print("stack_axis = 0")
#print(np.stack((a,b), axis=0))
#print(2*'\n')
#print("stack_axis = 1")
#print(np.s... |
# Copyright 2020 Antonio Macaluso
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writ... |
# Generated by Django 3.0.3 on 2020-09-10 12:25
import django.contrib.gis.db.models.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sequence', '0026_sequence_coordinates_ele'),
]
operations = [
migrations.AddField(
mo... |
# -*- coding: utf-8 -*-
"""Query web services."""
import gzip
import logging
from ._bouth23 import bstream, s
from ._exceptions import ISBNLibHTTPError, ISBNLibURLError
from ..config import options
# pylint: disable=import-error
# pylint: disable=wrong-import-order
# pylint: disable=no-name-in-module
try: # pragma:... |
# Copyright 2014, Sandia Corporation. Under the terms of Contract
# DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain
# rights in this software.
"""Functionality for managing scene graphs.
Note that the scenegraph is an internal implementation detail for developers
adding new functionalit... |
__all__ = ["analysis", "data", "geometry", "io", "util"] |
# coding: utf-8
#
from tornado.web import RequestHandler
from tornado.escape import json_decode
class BaseRequestHandler(RequestHandler):
pass
class IndexHandler(BaseRequestHandler):
def get(self):
self.write("Hello ATX-Storage")
|
import os
from Crypto.Protocol.KDF import scrypt
KEY_LENGTH = 32
N = 2**16 ##meant for ram
R = 10
P = 10
import binascii
import bcrypt
from loguru import logger
def generate_bcrypt(password):
if isinstance(password, str):
password = password.encode()
hashed =bcrypt.hashpw(password, bcrypt.gensalt())... |
# -*- coding: utf-8 -*-
from django.conf.urls import url
from django.views.generic import TemplateView
from . import views
app_name = 'url_shorter'
urlpatterns = [
url(r'user_url_list/', views.UserURLListView.as_view(), name="user_url_list"),
url(r'user_url_create/', views.UserURLCreateView.as_view(), name="use... |
#!/usr/bin/python3
#coding=utf-8
"""
A flask based server for calculating.
@author: vincent cheung
@file: server.py
"""
from flask import Flask,render_template,request,redirect,url_for
from flask import send_file, Response
import os
import sys
sys.path.append('../')
from calculate import *
app = Flask(__name__)
@ap... |
if ((True and True) or (not True and True)) and \
(True or True):
pass |
value = '382d817119a18844865d880255a8221d90601ad164e8a8e1dd8a48f45846152255f839e09ab176154244faa95513d16e5e314078a97fdb8bb6da8d5615225695225674a4001a9177fb112277c45e17f85753c504d7187ed3cd43b107803827e09502559bf164292affe8aaa8e88ac898f9447119a188448692070056a2628864e6d7105edc5866b9b9b6ebcad6dc3982952a7674a62015025695225... |
from taichi.misc.util import *
from taichi.two_d import *
from taichi import get_asset_path
if __name__ == '__main__':
scale = 8
res = (80 * scale, 40 * scale)
async = True
if async:
simulator = MPMSimulator(
res=res,
simulation_time=30,
frame_dt=1e-1,
base_delta_t=1e-6,
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import sqlite3 as lite
import sys
con = lite.connect('Database.db')
with con:
cur = con.cursor()
#Create data for the user table
cur.execute("CREATE TABLE users(UserId INT, UserName TEXT, Password TEXT)")
cur.execute("INSERT INTO users VALUES(1,'Adm... |
import itertools
import logging
import os.path
import sys
import time
import click
import pychromecast
from pychromecast.error import PyChromecastError
import pylast
import toml
logger = logging.getLogger(__name__)
# Default set of apps to scrobble from.
APP_WHITELIST = ['Spotify', 'Google Play Music', 'SoundCloud'... |
from this_is_a_package import a_module
a_module.say_hello("ITC") |
# coding: utf-8
"""
CMS Audit Logs
Use this endpoint to query audit logs of CMS changes that occurred on your HubSpot account. # noqa: E501
The version of the OpenAPI document: v3
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from hubspot.cms.a... |
import numpy as np
import time
# Number of random numbers to be generated
nran = 1024
# Generate a random number from the normal distribution
result = [np.random.bytes(nran*nran) for x in range(nran)]
print(len(result), "======>>> random numbers")
# Wait for tsleep seconds
tsleep = 40
print("I am sleeping for {... |
# Example of using StagingAreaCallback for GPU prefetch on a simple convnet
# model on CIFAR10 dataset.
#
# https://gist.github.com/bzamecnik/b9dbd50cdc195d54513cd2f9dfb7e21b
import math
from keras.layers import Dense, Input, Conv2D, MaxPooling2D, Dropout, Flatten
from keras.models import Model
from keras.utils impor... |
from requests import get
READ_SUCCESS_CODE = 200
class ConfigurationGateway(object):
def __init__(self, url, executables_path, repositories_path, results_key):
self.url = url
self.executables_path = executables_path
self.repositories_path = repositories_path
self.results_key = r... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
# -------------------------------------------#
# author: sean lee #
# email: xmlee97@gmail.com #
#--------------------------------------------#
"""MIT License
Copyright ... |
import flask
class RequestDictionary(dict):
def __init__(self, *args, default_val=None, **kwargs):
self.default_val = default_val
super().__init__(*args, **kwargs)
def __getattr__(self, key):
# Enable rd.key shorthand for rd.get('key') or rd['key']
return self.get(key, self.de... |
# library
import pandas as pd
import matplotlib.pyplot as plt
import datetime
import gif
import seaborn as sns
import warnings
warnings.filterwarnings("ignore")
# 関数化する
## git.frameデコレターを使用する
@gif.frame
def my_plot(df, date, x_min, x_max, y_min, y_max):
# 可視化するデータ
d = df[df["date"] <= date]
... |
from collections import defaultdict
from collections.abc import MutableMapping
from copy import deepcopy
from pathlib import Path
from typing import (Any, Dict, List, Literal, Mapping, NamedTuple, Sequence,
Tuple, Union)
import yaml
from more_itertools import unique_everseen
from .md import merge_... |
from secml.array.tests import CArrayTestCases
import numpy as np
import copy
from secml.array import CArray
from secml.core.constants import inf
class TestCArrayUtilsDataAlteration(CArrayTestCases):
"""Unit test for CArray UTILS - DATA ALTERATION methods."""
def test_round(self):
"""Test for CArray... |
from setuptools import setup
setup(
name='__dummy_package',
version='0.0.0',
install_requires=['html-linter==0.1.9'],
)
|
import json, glob
FILES = glob.glob('download/*/*/*/*.json')
good = {}
dups = 0
total = 0
for f in FILES:
with open(f, 'r') as fi:
j = json.load(fi)
for post in j['data']['children']:
i = post['data']['id']
if i == '4hsh42':
continue
if i not in good:
good[i] = post
with... |
import torch
import matplotlib.pyplot as plt
import imageio
import numpy as np
# Create data, 100 points evenly distributed from -2 to 2
# Use unsqueeze to add one more dimension, torch needs at least 2D input (batch, data)
x = torch.unsqueeze(torch.linspace(-2,2,100), dim=1)
# y = x^2 + b
y = x.pow(2) + 0.5 * torch.... |
import logging
import re
import nltk
from django.utils.text import slugify
from oldp.apps.backend.processing import ProcessingError, AmbiguousReferenceError
from oldp.apps.cases.models import Case
from oldp.apps.cases.processing.processing_steps import CaseProcessingStep
from oldp.apps.laws.models import LawBook
from... |
num = int(input("Digite um número inteiro de 0 a 9999: "))
u = num // 1 % 10
d = num // 10 % 10
c = num // 100 % 10
m = num // 1000 % 10
print(f"O numero {num} possui {u} unidades.")
print(f"O numero{num} possui {d} dezenas.")
print(f"O numero{num} possui {c} centenas.")
print(f"O numero{num} possui {m} milhares.")
|
facts=[
'Mumbai was earlier known as Bombay.',
'Mumbai got its name from a popular goddess temple - Mumba Devi Mandir, which is situated at Bori Bunder in Mumbai.',
'On 16 April 1853, Mumbai witnessed the first train movement in India. \
With 14 carriages and 400 passengers, the first train left Bori Bunder, now called... |
# Copyright (c) ZenML GmbH 2021. 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 applica... |
import os
SQLALCHEMY_DATABASE_URI = os.environ.get('FLASK_DATABASE_URI', 'postgres://user:pass@host/db')
SQLALCHEMY_ENGINE_OPTIONS = {'pool_pre_ping':True}
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = b'\xb0\xe2\x16\x16\x15\x16\x16\x16' |
# Copyright (c) 2014, 2020, Oracle and/or its affiliates.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License, version 2.0, as
# published by the Free Software Foundation.
#
# This program is also distributed with certain software (including
# ... |
from target import TargetType
import os
import re
import cv2
import time
import subprocess
import numpy as np
TARGET_DIR = './assets/'
TMP_DIR = './tmp/'
SIMILAR = {
'1': ['i', 'I', 'l', '|', ':', '!', '/', '\\'],
'2': ['z', 'Z'],
'3': [],
'4': [],
'5': ['s', 'S'],
'6': [],
'7': [],
'8... |
from horse import Horse
import random
import os
money = 100
colours = [
"red",
"blue",
"yellow",
"pink",
"orange",
]
def race_horses(horses):
return random.choice(horses)
while money > 0:
print(f"Welcome to the race! You have £{money:.2f}. Your horses are: ")
horses = [Horse.rando... |
"""
Django settings for sandbox project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
im... |
from django.contrib.auth import password_validation, get_user_model
from rest_framework import serializers
from rest_framework.generics import get_object_or_404
from rest_framework.exceptions import ValidationError
from rest_framework.validators import UniqueValidator
from rest_framework_simplejwt.exceptions import In... |
import math
import cmath
import cairo
from random import randint
IMAGE_SIZE = (5000, 5000)
NUM_SUBDIVISIONS = 6
def chooseRatio():
return randint(0, 6)
colors = [(1.0, 0.35, 0.35), (0.4, 0.4, 1.0), (0.1, 1.0, 0.2), (0.7, 0.1, 0.8)]
def chooseColor():
return colors[randint(0, len(colors) - 1)]
Ratio = chooseRat... |
from preprocess.load_data.data_loader import load_hotel_reserve
customer_tb, hotel_tb, reserve_tb = load_hotel_reserve()
# 本书刊登内容如下
# 将iloc函数二维数组的第一维度指定为“:”,提取所有行
# 将iloc函数二维数组的第二维度指定为由列号组成的数组,提取相应的列
# 0:6和[0, 1, 2, 3, 4, 5]表示相同的意思
reserve_tb.iloc[:, 0:6]
|
"""
@authors:
# =============================================================================
Information:
The purpose of this script is to serve as the main code for the user.
Use the user's guide that still has not been written to find out how to use
this tool.
Use your python skills to understand... |
from django.conf.urls import url, include
#from django.contrib import admin
#from django.urls import path
from usuario.views import registar_usuario,editar_usuario,eliminar_usuario
app_name = 'usuario'
urlpatterns = [
url(r'^nuevo$',registar_usuario.as_view() , name="new"),
url(r'^edit_book/(?P<pk>\d+)/$',edita... |
from hashlib import md5
from app import app, db
import sys
if sys.version_info >= (3, 0):
enable_search = False
else:
enable_search = True
import flask_whooshalchemy as whooshalchemy
# This is a direct translation of the association table.
# use the lower level APIs in flask-sqlalchemy to create the table without... |
import numpy as np
import pickle
from collections import defaultdict
import spacy
from spacy.symbols import nsubj, VERB
from models import load_models, generate
import argparse
import torch
nlp = spacy.load("en")
def get_subj_verb(sent):
"Given a parsed sentence, find subject, verb, and subject modifiers."
s... |
# HTTP Error Code
# imported necessary library
import tkinter
from tkinter import *
import tkinter as tk
import tkinter.messagebox as mbox
import json
# created main window
window = Tk()
window.geometry("1000x700")
window.title("HTTP Error Code")
# ------------------ this is for adding gif image in the main window ... |
is_all_upper = lambda t: t.isupper() |
from .drm_service import DRMService
from .fairplay_drm_service import FairPlayDRM
from .aes_drm_service import AESDRM
class TSDRMService(DRMService):
MUXING_TYPE_URL = 'ts'
def __init__(self, http_client):
super().__init__(http_client=http_client)
self.FairPlay = FairPlayDRM(http_client=http... |
#!/usr/bin/python
import yaml
import json
#Reading from YAML file
print "\n***Printing from the YAML file***"
yamlfile = 'yamloutput.yml'
with open (yamlfile) as f:
yamllist = yaml.load(f)
print yamllist
print "\n"
#Reading from JSON file
print "\n***Printing from the JSON file***"
jsonfile = 'jsonoutput.json'... |
# Copyright 2018 StreamSets Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writi... |
import json
import cv2
import matplotlib.pyplot as plt
import numpy as np
import os
from labelme import utils
from skimage import img_as_ubyte
import PIL.Image
import random
JSON_DIR = 'json'
LABELCOLOR = { # 设定label染色情况
'product': 1,
'product': 2,
'product': 3,
'product': 4,
}
VOCVersion = 'VOC2012... |
from setuptools import setup
with open('README.md') as f:
long_description = f.read()
setup(
name='nicebytes',
author='Philipp Ploder',
url='https://github.com/Fylipp/nicebytes',
description='human-readable data quantities',
long_description=long_description,
long_description_content_type=... |
# -*- coding: utf-8 -*-
"""
profiling.tracing
~~~~~~~~~~~~~~~~~
Profiles deterministically by :func:`sys.setprofile`.
"""
from __future__ import absolute_import
import sys
import threading
from .. import sortkeys
from ..profiler import Profiler
from ..stats import RecordingStatistics, VoidRecordingStatis... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Project: Appraise evaluation system
Author: Matt Post <post@cs.jhu.edu>
This script takes a set of parallel files and writes out the XML file used to
setup the corresponding Appraise tasks.
usage:
$ build_xml.py [-h] [-id ID] [-source SOURCELANG] [-target TARGETL... |
import datetime
import discord
from dotenv import dotenv_values
TOKEN = dotenv_values(".env")["TOKEN"]
class Client(discord.Client):
async def on_ready(self):
members = getlist(self.guilds[0])
votes = {}
for member in members:
votes[member] = 0
for member in members:
... |
from django.template.loader import get_template
from django_better_admin_arrayfield.forms.widgets import DynamicArrayWidget
def test_template_exists():
get_template(DynamicArrayWidget.template_name)
def test_format_value():
widget = DynamicArrayWidget()
assert widget.format_value("") == []
assert w... |
import collections
class contributor:
def __init__(self, name, index):
self.name = name
self.index = index
self.ratings = collections.defaultdict(list)
def __str__(self) -> str:
return self.name
def __repr__(self) -> str:
return self.name
... |
import json
import hashlib
from dojo.models import Finding
class TruffleHogJSONParser(object):
def __init__(self, filename, test):
data = filename.read()
self.dupes = dict()
self.items = ()
for line in data.splitlines():
json_data = self.parse_json(line)
f... |
import requests
import csv
key=input('Masukan produk yang akan dicari:')
limit=input('Masukan limit produk:')
hal = input('Masukan berapa halaman ke berapa:')
write = csv.writer(open('eCommerce/hasil/{}.csv'.format(key), 'w', newline=''))
header = ['nama produk','harga','terjual','rating produk','nama toko','lokasi t... |
from pytube import YouTube
from tqdm import tqdm
import ffmpeg
import html
# insert test link here!
yt = YouTube('https://www.youtube.com/watch?v=2A3iZGQd0G4')
audio = yt.streams.filter().first()
pbar = tqdm(total=audio.filesize)
def progress_fn(self, chunk, *_):
pbar.update(len(chunk))
yt.register_on_progress_ca... |
import argparse
import json
import multiprocessing
import os
import pickle
import random
from multiprocessing import Pool, cpu_count
import nltk
import numpy as np
import torch
from tqdm import tqdm
from src.data_preprocessors.transformations import (
NoTransformation, SemanticPreservingTransformation,
BlockS... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from math import exp
import os
import re
import sys
# This code implements the non-linear regression method described in:
# Jean Jacquelin 2009,
# Régressions et équations intégrales,
# sec. REGRESSIONS NON LINEAIRES des genres : PUISSANCE, EXPONENTIELLE, LOGARITHME, WEI... |
from setuptools import setup
setup(name='pkgtest',
version='1.0.0',
description='A print test for PyPI',
author='winycg',
author_email='win@163.com',
url='https://www.python.org/',
license='MIT',
keywords='ga nn',
packages=['pkgtest'],
install_requires=['numpy>=1.1... |
import boto3
import botocore
import sys
import os
class S3Client:
def __init__(self, bucket, key):
self.client = boto3.client('s3')
self.bucket = bucket
self.key = key
def get_content_length(self):
try:
return int(self.client.get_object(Bucket=self.bucket, Key=self.... |
import io
import os
import time
import zipfile
import h5py
import numpy as np
import pandas as pd
from PIL import Image
from django.http import HttpResponse
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework... |
# Hello, I'm party bot, I will be called from wsgi.py once
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler
from Bot.models import TelegramUser, Action, Day, WeekDay, Event, Vote, BotMessage, Advertisement
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Re... |
from trex_stl_lib.api import *
class STLS1(object):
def get_streams (self, direction = 0, **kwargs):
s1 = STLStream(name = 's1',
packet = STLPktBuilder(pkt = Ether()/IP(src="16.0.0.1",dst="48.0.0.1")/UDP(dport=12,sport=1025)/(10*'x')),
mode = STLTXSingleBurst(... |
import collections
from .base import BaseItertool
from .iter_dispatch import iter_
from .tee import tee
_zip = zip
class product(BaseItertool):
"""product(*iterables, repeat=1) --> product object
Cartesian product of input iterables. Equivalent to nested for-loops.
For example, product(A, B) returns t... |
r"""
Lattice posets
"""
#*****************************************************************************
# Copyright (C) 2011 Nicolas M. Thiery <nthiery at users.sf.net>
#
# Distributed under the terms of the GNU General Public License (GPL)
# http://www.gnu.org/licenses/
#*****************************... |
# uncompyle6 version 3.2.4
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)]
# Embedded file name: ctypes.macholib.framework
import re
__all__ = [
'framework_info']
STRICT_FRAMEWORK_RE = re.compile('(?x)\n(?P<location>^.*)(?:^|/)\n(?P... |
# bc_action_rules_bc.py
from pyke import contexts, pattern, bc_rule
pyke_version = '1.1.1'
compiler_version = 1
def speed_up(rule, arg_patterns, arg_context):
engine = rule.rule_base.engine
patterns = rule.goal_arg_patterns()
if len(arg_patterns) == len(patterns):
context = contexts.bc_context(rule)
tr... |
"""
Created_at: 06 Oct. 2019 10:20:50
Target: EPISODES: set nullable `episodes.published_at`
"""
from playhouse.migrate import *
from migrations.models import database
previous = "0002_23052019_migration"
def upgrade():
migrator = PostgresqlMigrator(database)
migrate(migrator.drop_not_null("episodes", "pu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.