content stringlengths 5 1.05M |
|---|
"""
/github/objects/user.py
Copyright (c) 2019-2020 ShineyDev
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 req... |
#!/usr/bin/env python3
import serial
import binascii
import csv
data_entry_len = 14
data_offset = 3
req1 = b"\xA5\xF9\x01\x01\xFB"
req2 = b"\xA6\xF9\x01\x01\xFB"
# open serial port
s = serial.Serial("/dev/ttyUSB0", 19200)
s.timeout = 1
# send a magic request (sniffed from the windows software)
s.write(req1)
# read lo... |
#!/usr/bin/env python
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for
# full license information.
import time
from rest_wrappers.generated.e2erestapi.azure_iot_end_to_end_test_wrapper_rest_api import (
AzureIOTEndToEndTestWrapperRestApi,
)
... |
# -*- coding: utf8 -*-
import os
import re
import json
from datetime import datetime
import requests
enc_dict = os.environ
# 配置学习通账号密码, 必填
USER_INFO = {
'username': '',
'password': '',
'schoolid': '', # 学号登录才需要填写
}
# Server酱消息推送SendKey, 选填
SendKey = ''
SERVER_CHAN_SEND_KEY = enc_dict.get('send_key', SendK... |
t = int(input().strip())
for a0 in range(t):
b,w = input().strip().split(' ')
b,w = [int(b),int(w)]
x,y,z = input().strip().split(' ')
x,y,z = [int(x),int(y),int(z)]
cost = b*x + w*y
x_cost = b*(y+z) + w*y
y_cost = b*x + w*(x+z)
new_cost = min(cost, x_cost, y_cost)
print (new... |
from django.apps import AppConfig
class DfndbConfig(AppConfig):
name = 'dfndb'
|
import mbuild as mb
import numpy as np
class MMM(mb.Compound):
""" Coarse-grained alkane bead containing a CH2-CH2-CH2 group """
def __init__(self):
super(MMM, self).__init__()
self.add(mb.Particle(name='_MMM'))
self.add(mb.Port(anchor=self[0], orientation=[0, 1, 0], separation=0.15), '... |
import math
import numpy as np
import statsmodels.stats.stattools as stattools
from models.settings import TH230_DECAY_CONSTANT, TH230_DECAY_CONSTANT_ERROR
def calculate_outlier_resistant_mean_and_st_dev(data, number_of_outliers_allowed):
medcouple = stattools.medcouple(data)
Q1 = np.percentile(data, 25, in... |
from TikTokApi import TikTokApi
import random
"""
how to get the verifyFp value: browser > tiktok.com > lock icon beside the url >
cookies > www.tiktok.com > s_v_web_id > copy value
"""
verifyFp = input("enter the verify cookie: ")
keyword = input("enter desired keyword:... |
#!/usr/bin/env python
"""Script to generate atest runners based on data files.
Usage: %s path/to/data.file
"""
from __future__ import with_statement
import sys, os
if len(sys.argv) != 2:
print __doc__ % os.path.basename(sys.argv[0])
sys.exit(1)
inpath = os.path.abspath(sys.argv[1])
outpath = inpath.replac... |
import os
import pytest
import random
import six
import numpy as np
import tensorflow as tf
import segmentation_models as sm
from segmentation_models import Unet
from segmentation_models import Unet1D
from segmentation_models import Linknet
from segmentation_models import PSPNet
from segmentation_models import FPN
fro... |
# Program to print fibonacci sequence without memoization
def fib2(n: int) -> int:
if n < 2:
return n
return fib2(n - 1) + fib2(n - 2)
print(fib2(2)) |
import forumsweats.discordbot as discordbot
from forumsweats import numberparser
import discord
name = 'debugnumber'
args = '[number]'
async def run(message, number: str):
await message.channel.send(embed=discord.Embed(
description=str(numberparser.solve_expression(number))
))
|
import binascii
import random
import pytest
from siliqua.wallet.accounts import LinkBlock
from siliqua.wallet.exceptions import InvalidEncryptionKey
from siliqua.wallet.util import (HexDict, Secret, WalletSerializable,
sort_blocks_for_broadcast, wallet_parameter)
SECRET_KEY_A = b'erIm... |
print("My firt menu")
print("1. Hear a joke")
menu_choice = # get the selection
if # put the condition in here#
print("Do you want a rabbit joke or science joke?")
next_menu_choice = # get the next selection
if next_menu_choice == "rabbit":
print("What do you call a happy rabbit?")
print("... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
import time
def dshow_dev():
cam = []
mic = []
ffmpeg = subprocess.Popen(['ffmpeg', '-f', 'dshow', '-list_devices', 'true', '-i', 'dummy', ],
stdout=subprocess.PIPE, stderr=subprocess.PIPE, )
flag = ''
... |
from h5py_sequence import H5PySequence
import numpy as np
from sklearn.multiclass import OneVsRestClassifier, OneVsOneClassifier
import numpy as np
from sklearn.metrics import confusion_matrix, classification_report
from sklearn.svm import SVC
import json
def get_dataset(dir, batch_size):
seq = H5PySequence(dir, ... |
##
## python util function to create dataset from Serial Observations
##
import sys
import numpy as np
from SlidingWindowGenerator import SlidingWindowGenerator
def loadfile(infile):
data = []
with open(infile, 'r') as inf:
data = inf.readlines()
return data
def loadfileWithStrippedNewline(infile... |
# from scipy.optimize import minimize
#
# #testing list of funcitons
#
# def sample(i, l):
# return i*l
#
# class Samp():
# def __init__(self, i):
# self.i = i
# def __call__(self, l):
# return l*self.i
#
# a = [Samp(i) for i in range(10)]
#
# for e in a:
# print(e(3))
#
#
# def objecti... |
import json
import os
import pathlib
import sys
import yaml
import constants as C
import metadata as mm
import util
def main():
db = util.get_db()
cur = db.cursor()
for moviefile in get_movie_files():
print(moviefile)
base_dir = util.get_folder(moviefile)
metadata = mm.get_overri... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 8 09:24:07 2019
@author: madsa
"""
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
import matplotlib
import pickle
import matplotlib.tri a... |
import json
class sudoku():
def __init__(self, size):
self.size = size
self.board = []
self.initialise_board()
def initialise_board(self):
for _ in range(0,self.size):
row = [0]*self.size
self.board.append(row)
def fill_cell(self, row, col, entry):
... |
from tests import SiteTest, app
class StaffEndpoints(SiteTest):
""" Test cases for staff subdomain """
def test_staff_view(self):
""" Check staff view redirects """
response = self.client.get('/', app.config['STAFF_SUBDOMAIN'])
self.assertEqual(response.status_code, 302)
def test... |
#!/usr/bin/env python
#
# test_ohi.py - Test the fsl.atlasq ohi interface, which mimics the behaviour
# of the old atlasquery tool.
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#
import os.path as op
import os
import shlex
import pytest
import numpy as np
impor... |
# -*- coding: utf-8 -*-
# 总调度器 + 多线程控制器
from do.house_selector import HouseSelector
from do.page_extractor import PageExtractor
from do.price_stater import PriceStater
from util.config import ConfigParser
from constant.logger import *
import time
class Do(HouseSelector, PageExtractor, PriceStater):
@staticmetho... |
n = int(input())
s = list(map(int, input().split()))
sol = n*max(s)-sum(s)
print(sol)
|
"""test pattern matching alogrithms"""
from src.pattern_match import boyer_moore
from src.pattern_match import knuth_morris_pratt
def test_pattern_match():
"""test pattern matching algorithms"""
test_cases = (
("ABBCBBD", "BC", [2]),
("ABBCBEBCBD", "BC", [2, 6]),
("BCBCBC", "BC", [0, 2... |
"""
[E] Given a set of numbers that might contain duplicates, find all of its distinct subsets.
Example 1:
Input: [1, 3, 3]
Output: [], [1], [3], [1,3], [3,3], [1,3,3]
Example 2:
Input: [1, 5, 3, 3]
Output: [], [1], [5], [3], [1,5], [1,3], [5,3], [1,5,3], [3,3], [1,3,3], [3,3,5], [1,5,3,3]
"""
# Time: O(N * 2^... |
# -*- coding: utf-8 -*-
import logging
import functools
from faunadb import query as q
from faunadb.client import FaunaClient
#from faunadb.objects import Ref
log = logging.getLogger(__name__)
def log_debug(func):
"""
Ejemplo de implementación de un decorator
"""
# Preserva la información de la funci... |
# Copyright (c) 2020-2021 by Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be found in the LICENSE file.
from pandapipes import pandapipesNet
from pandapipes.multinet.control.run_control... |
from functools import wraps
def query_params(*frb_fred_params):
"""
Decorator that pops all accepted parameters from method's kwargs and puts
them in the params argument. Modeled after elasticsearch-py client utils strategy.
See https://github.com/elastic/elasticsearch-py/blob/3400179153cc13b6ae2c2673... |
import pygame
import math
class Player:
def __init__(self, img, name, sizes):
self.player_img = pygame.image.load(img)
self.width = math.ceil(sizes.display_width/5)
self.height = math.ceil(sizes.display_width/4)
self.player_img = pygame.transform.scale(self.player_img, (self.width, ... |
import turtle
import time
import random
t = turtle.Turtle()
turtle.hideturtle()
t.hideturtle()
t.speed(0)
turtle.tracer(0, 0)
turtle.bgcolor("black")
def drawArray(arr, count, indexAt, col, col2, colFront = "white"):
t.clear()
width = turtle.window_width()
height = turtle.window_height()
t.pu()
he... |
import logging
import shlex
from typing import List
log = logging.getLogger(__name__)
class EasyProcessUnicodeError(Exception):
pass
def split_command(cmd, posix=None) -> List[str]:
"""
- cmd is string list -> nothing to do
- cmd is string -> split it using shlex
:param cmd: string ('ls -l')... |
import time
import torch
from torch.autograd import Variable
from os.path import join
import os
from bayes_nn.util.util import calc_risk, to_tensor, maybe_make_dir
from bayes_nn.training import test
from bayes_nn.model.model_definition import Net
from bayes_nn import conf
from bayes_nn.util.mutilation import * # Impo... |
#!/usr/bin/python
import requests
import xml.etree.ElementTree as ET
import json
import re
import ConfigParser
config_file = r'config.cfg'
config = ConfigParser.ConfigParser()
config.read(config_file)
def loadRSS(url):
resp = requests.get(url)
return resp.content
def parse_cta_xml(xml):
# create... |
from sklearn.utils import resample
import matplotlib.pyplot as plt
from pandas import read_csv
import seaborn as sns
import numpy as np
import pandas as pd
def import_data():
"""Import real data from GitHub."""
observation_features = read_csv(
"https://raw.githubusercontent.com/fabiorodp/IN_STK5000"
... |
from scrounger.core.module import BaseModule
# helper functions
from scrounger.utils.config import Log
from scrounger.utils.general import strings, pretty_grep
import re
class Module(BaseModule):
meta = {
"author": "RDC",
"description": "Checks if the application uses insecure channels",
"... |
if __name__ == '__main__':
password = "12313"
print(
"\n".join([
f'到支付宝搜索口令红包,凭口令"{password}"领取红包!',
"123123"
])
)
|
from django.apps import AppConfig
class OtoConfig(AppConfig):
name = 'oto'
|
from sqlalchemy import Column, ForeignKey, Integer, String, DateTime
from sqlalchemy.orm import relationship
from ..database import Base
class Playlist(Base):
__tablename__ = "playlists"
id = Column(Integer, primary_key=True, index=True)
spotify_id = Column(String, unique=True, index=True)
name = Col... |
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5 import QtCore, QtGui, QtWidgets
from easygraphics.widget import TurtleWidget
from easygraphics import *
from easygraphics.turtle import *
import random
class MyWindow(QWidget):
def __init__(self):
super().__init__()
self._turtleW... |
import abc
from typing import List
from src.auction.auction_ad import AuctionAd
from src.type_definitions import SlateType
# This is an abstract class that specifies how a concrete implementation of an auction should behave.
class Auction(metaclass=abc.ABCMeta):
@staticmethod
@abc.abstractmethod
# Must ... |
from django.shortcuts import render
from django.db import transaction
from rest_framework.authtoken.models import Token
from sensors.models import SensorVerification, Sensor
from api.v1.mailer import TokenEmail
def verify(request):
code = request.GET.get('code')
print code
if code is None:
ret... |
#!/usr/bin/env python
""" Test queries with ModelSEEDDatabase compounds/reactions data """
import unittest
from nosqlbiosets.dbutils import DBconnection
from nosqlbiosets.graphutils import neighbors_graph, shortest_paths,\
set_degree_as_weight
from nosqlbiosets.modelseed.query import QueryModelSEED
qry = QueryMod... |
import logging
from mjooln.atom.zulu import Zulu
from mjooln.atom.key import Key
from mjooln.atom.identity import Identity
logger = logging.getLogger(__name__)
class AtomError(Exception):
pass
class Atom:
""" Unique identifier intended for objects and data sets alike
The timestamp (zulu) defines star... |
import re
import os
import pathlib
import shutil
import tempfile
# default file path for ~/.quicklinks on computer
DEFAULT_FILE = os.path.join(str(pathlib.Path.home()), '.quicklinks')
PERMISSION_ERROR_STRING = '''
Quicklinks cannot access this file, please enable group read write
access by doing the following:... |
# __init__.py
# Created on 7 Jul 2021 for Team Pheasant.
# Copyright © 2021 Qi Tianshi. All rights reserved.
# Package for movement-based functionality.
# Built-in modules
from .TwoWheelDrive import *
# Base classes, for building custom programs
from .utils.DoubleMotorBase import *
|
#!/usr/bin/env python3
import re
from enum import Enum, auto
from typing import Optional
import dataclasses
from PyQt5.QtCore import (Qt, QMimeData, QObject, QSizeF, QRectF, QEvent, pyqtSignal)
from PyQt5.QtGui import (QTextOption, QContextMenuEvent, QTextObjectInterface, QTextFormat, QTextCharFormat,
... |
from django.conf.urls import url
from django.views.generic.base import RedirectView
from . import views
urlpatterns = [
url(r'^index/$', views.index, name='index'),
url(r'^index/(?P<oh_id>\w+)/$',
views.index,
name='index_w_id'),
url(r'^location/$', views.location, name='location'),
ur... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
"""
Time Complexity: O(N)
Space Complexity O(1)
"""
if... |
# -*- coding: utf-8 -*-
from datetime import datetime
import json
import re
from urllib.parse import urlencode
import scrapy
from locations.items import GeojsonPointItem
from locations.hours import OpeningHours
SINGLE_POINT_STATES = [
("0,64.0685,-152.2782,AK"),
("1,20.6538883744,-157.8631750471,HI"),
]
HUN... |
#!/usr/bin/env python
# coding: utf-8
# @Author: lapis-hong
# @Date : 2019/5/19
"""This module used to extract main text from arbitrary html content using CX-extractor."""
from __future__ import unicode_literals
import re
class CxExtractor(object):
"""Cx-extractor implemented in Python,
based on https://gi... |
import io
from PIL import Image
import requests
url = 'http://localhost:5000/rawupload'
albedo = io.BytesIO()
Image.open('albedo.png').save(albedo, format='PNG')
normal = io.BytesIO()
Image.open('normal.png').save(normal, format='PNG')
depth = io.BytesIO()
Image.open('depth.png').save(depth, format='PNG')... |
import datetime
import numpy as np
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import dash
import krakenex
import time
from pykrakenapi import KrakenAPI
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
# configurando api
k = kr... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: addnn/node/proto/node_state.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection... |
#!/usr/bin/env python
################################################################################
# Libraries import
import sys
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
import numpy as np
import glob
########################################################################... |
import math
import numpy as np
EPS = 1e-8
class MCTS():
"""
This class handles the MCTS tree.
"""
def __init__(self, game, nnet, args):
self.game = game
self.nnet = nnet
self.args = args
self.Qsa = {} # stores Q values for s,a (as defined in the paper)
sel... |
import click
import numpy as np
import pickle
import open3d as o3d
import pcp_utils
@click.command()
@click.argument("pcd_file")#config
@click.option("--mode")#config
def main(pcd_file, mode):
if mode == "generated_grasps":
pcds = np.load(pcd_file, allow_pickle=True).item()
scene_pcd = pcp... |
'''
Move a motor back and forth in PV_Mode for with CANopen using the TMCM1636 module
Created on 15.05.2020
@author: JM
'''
if __name__ == '__main__':
pass
import time
from PyTrinamic.connections.ConnectionManager import ConnectionManager
from PyTrinamic.modules.TMCM1636.TMCM_1636 import TMCM_1636
"""
Choo... |
"""Library for the LITE-ON LTR559 digital light and proximity sensor."""
import time
from i2cdevice import Device, Register, BitField
from i2cdevice.adapter import Adapter, LookupAdapter, U16ByteSwapAdapter
__version__ = '0.1.1'
I2C_ADDR = 0x23
PART_ID = 0x09
REVISION_ID = 0x02
class Bit12Adapter(Adapter):
def ... |
# Imports
import sys
import torch
import os
import time
from sbi.inference import SNLE_A, prepare_for_sbi
import numpy as np
import math
# Initial set up
lunarc = int(sys.argv[1])
seed = int(sys.argv[2])
hp_tuning = int(sys.argv[3]) # if hp_tuning = 0, no hyper-param tuning, else hp_tuning for that sample of the hp
s... |
import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp
from abc import ABC, abstractmethod
from tensorflow.experimental.numpy import moveaxis
class Categorical(ABC):
@abstractmethod
def __init__(self, num_categories, copula):
super(Categorical, self).__init__()
self.n... |
import thread
import logging
import os
import datetime
def initLogging(logfile_prefix, level_name, log_name):
LEVELS = {'debug': logging.DEBUG,
'info': logging.INFO,
'warning': logging.WARNING,
'error': logging.ERROR,
'critical': logging.CRITICAL}
datefmt='%Y-%m-%d %H:%M:%S'
## -- Create L... |
#! /usr/bin/env python
''' ------------------------| Python SOURCE FILE |------------------------
Test case helper to stop and start process
@copyright: Copyright (c) by Kodiak Data, Inc. All rights reserved.
'''
import os
import subprocess, signal
import time
from kd.util.logger import getLogger
from kd.util.rc_m... |
from subprocess import call
from word_embedding_paths import word_embeddings
from os.path import exists
from os import mkdir
for c in [2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048]:
name = "svmrbf-c" + str(c)
if exists("/usit/abel/u1/jimmycallin/models/" + name):
print("Model " + name + " already tra... |
from __future__ import division
from __future__ import print_function # use python 3 syntax but make it compatible with python 2
from flask import Flask, Blueprint, jsonify, request
from api import api
from dev import dev
app = Flask(__name__)
app.register_blueprint(dev)
app.register_blueprint(api)
# @app.errorha... |
from i3pystatus.core.command import run_through_shell
from i3pystatus.updates import Backend
class Yaourt(Backend):
"""
This module counts the available updates using yaourt.
By default it will only count aur packages. Thus it can be used with the
pacman backend like this:
.. code-block:: python
... |
# Generated by Django 2.2.13 on 2020-11-16 21:49
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0010_auto_20180808_1339'),
]
operations = [
migrations.CreateMod... |
#!/usr/bin/env python
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import tostring
import sys
import re
import codecs
class Context(object):
"""
Represent a single input word with context.
"""
def __init__(self, cid, word_form, lemma, pos, left_context, right_context):
se... |
#! /usr/bin/env python
try:
from mechanize import Request, urlopen, URLError, HTTPError,ProxyHandler, build_opener, install_opener, Browser
except ImportError:
print "\n[X] Please install mechanize module:"
print " http://wwwsearch.sourceforge.net/mechanize/\n"
exit()
import os
import re
import Que... |
__author__ = 'Matt Borgman'
from peewee import *
db = SqliteDatabase('users.db')
class Customer(Model):
name = CharField()
email = CharField()
password = CharField()
class Meta:
database = db
|
from pylatex import Document, Section, Figure, LongTable, MultiColumn
image_name = "glees.jpg"
class GleesPDF(Document):
def image(self):
geometry_options = {
"margin": "2.5"
}
doc = Document(geometry_options=geometry_options)
with doc.create(Section("Glees",number... |
from app.utilities.data import Data
from app.data.database import DB
import app.engine.skill_component_access as SCA
class SkillObject():
next_uid = 100
def __init__(self, nid, name, desc, icon_nid=None, icon_index=(0, 0), components=None):
self.uid = SkillObject.next_uid
SkillObject.next_uid... |
import subprocess
from subprocess import Popen, PIPE, STDOUT
import time
import os
import signal
from utils import get_nonblocking
CANDUMP_CMD = "candump -L {} > {}"
def plog(s):
print('[CAN] {}'.format(s))
def get_can(cfg):
out_dir = cfg.out_dir
queue = cfg.queue
receive_queue = cfg.receive_queue... |
# Copyright (c) 2021 - present / Neuralmagic, 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 b... |
from togglcmder.toggl.caching import Caching
from togglcmder.toggl.downloader import Downloader
from togglcmder.toggl.commands import Commands
# Helpers that don't fit anywhere else!
def retrieve_downloader_from_context(context: dict) -> Downloader:
downloader = context['downloader']
assert(isinstance(downloa... |
version = "2018-11-06" |
import io
from io import BytesIO
import socket
import struct
import time
import picamera
import base64
import configuration
import utils.motor_driver as motor_driver_helper
import RPi.GPIO as GPIO
import xlsxwriter
from PIL import Image
from datetime import datetime
from time import sleep
workbook = xlsxwriter.Workbo... |
import matplotlib.pyplot as plt
import math
import numpy as np
x = np.linspace(-1, 1, 5000)
y = np.exp(1/(x**2 - 1))
plt.plot(x,y)
plt.show()
|
# -*- coding: utf-8 -*-
"""Development Environment Config"""
# HOST = '127.0.0.1'
DEBUG = True
SECRET_KEY = 'dev'
|
"""
Terms representing list expressions
"""
import importlib
import operator
from abc import ABC, abstractmethod
from pyske.core.opt.fun import compose, curry
from pyske.core.opt.terms import MODULES, Var, Term, RULES_DB, Rule
MODULES.update({'PList': importlib.import_module('pyske.core.list.plist')})
MODULES.update(... |
from django.apps import AppConfig
class ContactmeConfig(AppConfig):
name = 'contactme'
|
# Copyright 2017 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""multiprocessing-related utilities."""
import logging
from multiprocessing import synchronize
class Lock(synchronize.Lock):
def __init__(self, log... |
class Stack():
@property
def size(self) -> int:
return len(self.data)
@property
def is_empty(self) -> bool:
return self.size == 0
def __init__(self) -> None:
self.data = []
def push(self, item):
self.data.append(item)
def pop(self):
if self.is_empt... |
# -*- coding:utf-8 -*-
# --------------------------------------------------------
# Copyright (C), 2016-2021, lizhe, All rights reserved
# --------------------------------------------------------
# @Name: constant.py
# @Author: lizhe
# @Created: 2021/11/20 - 12:12
# ------------------------------... |
# Copyright (c) 2018 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 required by app... |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 31 21:24:14 2020
@author: mat05
"""
import numpy as np
#from torchvision import datasets
import glob
from matplotlib import image
from matplotlib import pyplot
#from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
from PIL impor... |
from functools import (
partial,
)
from itertools import (
islice,
)
import random as _random
from typing import (
Callable,
Iterable,
Iterator,
List,
TypeVar,
)
from azul import (
require,
)
T = TypeVar('T')
# noinspection PyPep8Naming
class generable(Iterable[T]):
"""
Conve... |
import random
caratteri = '''abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ1234567890!?-%&'''
print("\n inserisci quanto caratteri deve essere lunga la password")
lunghezza = int (input ('''\n caratteri@lunghezza-# '''))
password= ""
for x in range (lunghezza):
password+= random.choice (caratter... |
# Lint as: python3
# Copyright 2019 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
"""Tests for zaim_csv_converter.py"""
import csv
from pathlib import Path
from typing import Optional
import pytest
from fixturefilehandler.file_paths import RelativeDeployFilePath
from tests.testlibraries.instance_resource import InstanceResource
from tests.testlibraries.output_csv_file_checker import ErrorCsvFileCh... |
"""Hops default HTTP server example"""
import ghhops_server as hs
import rhino3dm
hops = hs.Hops()
@hops.component(
"/add",
name="Add",
nickname="Add",
description="Add numbers with CPython",
inputs=[
hs.HopsNumber("A", "A", "First number"),
hs.HopsNumber("B", "B", "Second number"... |
import json
import pexpect
from post_rec.Utility import getLogger
logger = getLogger(__name__)
class SimpleTokenizer(object):
def tokenize(self,txt):
return txt.split()
class CoreNLPTokenizer(object):
def __init__(self):
"""
Args:
classpath: Path to the corenlp dir... |
import click
import json
import pathlib
import sqlite_utils
@click.group()
@click.version_option()
def cli():
"Tools for dumping/loading a SQLite database to diffable directory structure"
pass
@cli.command()
@click.argument(
"path", type=click.Path(exists=True, file_okay=True, dir_okay=False), required=... |
""" Test set operators - w_uh_vh elevation erosion.
"""
import unittest, os
import anuga
from anuga import Domain
from anuga import Reflective_boundary
from anuga import rectangular_cross_domain
from anuga import file_function
from anuga.config import netcdf_mode_r, netcdf_mode_w, netcdf_mode_a
from anuga.file_conve... |
from random import shuffle
from typing import Optional
from discord import Client, Message, TextChannel, VoiceChannel
from wavelink import Player, WaitQueue
class QueuePlayer(Player):
bound_channel: Optional[TextChannel]
np_message: Optional[Message]
def __init__(self, client: Client, channel: VoiceChan... |
import sys
import kenlm
from marmot.features.feature_extractor import FeatureExtractor
class SourceLMFeatureExtractor(FeatureExtractor):
def __init__(self, lm_file):
self.model = kenlm.LanguageModel(lm_file)
def get_features(self, context_obj):
#sys.stderr.write("Start SourceLMFeatureExtract... |
# Testing module instance_type.d2
import pytest
import ec2_compare.internal.instance_type.d2
def test_get_internal_data_instance_type_d2_get_instances_list():
assert len(ec2_compare.internal.instance_type.d2.get_instances_list()) > 0
def test_get_internal_data_instance_type_d2_get():
assert len(ec2_compare.intern... |
from auxTarefas import myLists,openTxt,readFunc,writeFunc,readNomeListas,writeNomeListas,getListas,addTarefa,editTarefa,consultFunc,estadoTarefa,closeTarefa,removeFunc,searchTarefa,sortTarefa,mudarLista,mudarNomeLista,criarList,atualiza,removeList,tarefasATerminar
import os
def printMenu():
print('\n\n','\t'*3,'<... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.