content stringlengths 5 1.05M |
|---|
__version__ = '2.0.0'
BKC_TORCH_VERSION = '1.8.1'
BKC_TORCHVISION_VERSION = '0.9.1'
BKC_TF_VERSION = '2.4.2'
|
import os
from transformers import AutoTokenizer
from tqdm import tqdm
from common_utils import clean_text
def data_to_token_classification(filenames, tokenizer, save_filename, reverse=False, overwrite=True):
print(f"save file: {save_filename}")
dir_name = os.path.dirname(save_filename)
if not os.path.exi... |
<!--
Copyright (c) 2017 AT&T Intellectual Property. 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... |
import collections
import string
from typing import List
from flask import Flask, request, abort
app = Flask(__name__)
def sum_chars_count(words_counter) -> int:
return sum(words_counter.values())
def split_to_words(s: str) -> List[str]:
return s.split()
def count_ascii_letters(word_list: List[str]):
... |
rule map_bwa_index:
input:
raw + "reference.fasta"
output:
mock = touch(maps + "reference"),
aux = expand(
maps + "reference.{extension}",
extension = "amb ann bwt pac sa".split(" ")
)
params:
prefix = maps + "reference"
log: maps + "bwa_in... |
from redbot.core import commands
from datetime import datetime, timezone
class Wingspan(commands.Cog):
"""Wingspan game related commands"""
def __init__(self, bot):
self.bot = bot
@commands.command()
async def expansion(self, ctx: commands.Context):
"""Time until Wingspan European exp... |
r"""
A brief overview of VQE
=======================
.. meta::
:property="og:description": Find the ground state of a Hamiltonian using the
variational quantum eigensolver algorithm.
:property="og:image": https://pennylane.ai/qml/_images/pes_h2.png
.. related::
tutorial_quantum_chemistry Building ... |
class Status:
def __init__(self, status_bytes, cog) -> None:
'''
Stores the current cog/processor status. built each time a command is executed
See documentation for what each bit is
'''
self._status_bytes = status_bytes
stat1 = int.from_bytes(status_bytes[0:4], 'lit... |
from abc import ABC
from abc import abstractmethod
from typing import Optional
__all__ = ["ModeBase"]
class ModeBase(ABC):
fmt: str = "%(message)s"
datefmt: str = "%Y-%m-%d %H:%M:%S"
def __init__(
self, fmt: Optional[str] = None, datefmt: Optional[str] = None
) -> None:
self.fmt = fm... |
from pycalltrace import CallTrace
def func1():
print('ok')
def func2():
func1()
def func3():
func2()
def func4():
func3()
def file_filter(filename):
if filename.find('calc') != -1:
return True
return False
with CallTrace(filter_func=lambda x: x.find('calc') == -1):
func4()
# ... |
from pyzabbix import ZabbixAPI
import argparse
from configparser import ConfigParser
import sys
json_geo = {
"type": "FeatureCollection",
"features": []
}
cfg = ConfigParser()
cfg.read(f'{sys.path[0]}/conf')
zabbixURL = cfg.get('Zabbix', 'url')
zabbixUser = cfg.get('Zabbix', 'user')
zabbixPassword = cfg.get('... |
import hashlib
import hmac
import random
import string
# Generate a "Provably Fair" number between 1 and n
SERVER_SEED_LENGTH = 64
def generate(client_seed: str, nonce: int, max_number: int = 10000):
client_seed = ''.join( # Random 16 character server seed with only lowercase and digits
random.SystemRa... |
keyboard.send_keys('<ctrl>+r') |
from ..free_module import FreeModuleElement
from ..symmetric import SymmetricGroupElement
from ..symmetric import SymmetricRingElement, SymmetricRing
from ..surjection import SurjectionElement
from ..utils import partitions, pairwise
from itertools import product, combinations
from math import floor, factorial
clas... |
# -*- coding: utf-8 -*-
import datetime as dt
from flask.ext.login import UserMixin
from metapp2.extensions import bcrypt
from metapp2.database import (
Column,
db,
Model,
ReferenceCol,
relationship,
SurrogatePK
)
class Group(SurrogatePK, Model):
__tablename__ = 'groups'
date_created ... |
import os
from jans.pycloudlib import get_manager
from hybrid_setup import HybridBackend
from ldap_setup import LDAPBackend
from couchbase_setup import CouchbaseBackend
from sql_setup import SQLBackend
from spanner_setup import SpannerBackend
from upgrade import Upgrade
def main():
manager = get_manager()
... |
# --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Code starts here
#Load dataset in a dataframe data.
data= pd.read_csv(path)
#Save the value counts of Loan_Status in a variable called loan_status
loan_status= data['Loan_Status'].value_count... |
from PyInquirer import style_from_dict, Token, prompt, Separator
def ratio_graphic(local, remote):
total = local + remote
local_ratio = int((round(local/total, 1) * 10) / 2)
remote_ratio = int((round(remote/total, 1) * 10) / 2)
return local_ratio * "🁢" + ( (5 - local_ratio) * "-" ) + ( (5 - remote_r... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from autohome.items import AutohomeItem
class Bmw8Spider(CrawlSpider):
name = 'bmw8'
allowed_domains = ['car.autohome.com.cn']
start_urls = ['https://car.autohome.com.cn/pic/se... |
import torch
import logging
from ..multi_tensor_apply import multi_tensor_applier
from ._amp_state import _amp_state, master_params
from itertools import product
# from apex_C import scale_check_overflow
def scale_check_overflow_python(model_grad, scale, master_grad, check_overflow=False):
# Exception handling fo... |
import argparse
from sys import argv
import dns.resolver
from os import system, name
verm = '\033[31;1m'
verd = '\033[32;1m'
f = '\033[m'
t = '\033[1;4m'
dns = dns.resolver.Resolver()
parser = argparse.ArgumentParser(
prog='DNS brute',
description='Programa de brute force para DNS; by: Spyware'
)
parser.add... |
# -*- coding: utf-8 -*-
from .user import (
ChangeUserPassword,
UserLogin,
UserLogout,
UserSignup,
UserProfile,
EmailValidation,
PasswordResetRequest,
PasswordReset,
Users,
UserException,
EmailSettings,
Settings
)
from .project import (
ProjectDetails,
Projects,... |
######################################################################
# Copyright 2016, 2017 John Rofrano. 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
#
# https://ww... |
import discord
import os
import json
from discord.ext import commands
with open("config.json") as f:
config = json.load(f)
def owner_check(ctx):
return ctx.message.author.id == config.get('owner')
class owner(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.cou... |
import torchvision.transforms as transforms
import torchvision.datasets as datasets
from torch.utils.data import DataLoader, ConcatDataset
from .misc import ClassSampler, GaussianNoise
__all__ = ['load_MNIST', 'load_CIFAR']
DATA = './data'
def load_MNIST(batch_size = 256, num_workers = 4):
dataloader = dataset... |
import pytest
from tests.utils import (
check_dynamodb_fixtures,
check_kinesis_fixtures,
check_s3_fixtures,
check_sqs_fixtures,
)
def test_top_level_imports():
pass
class TestMockWithMoto:
@pytest.mark.usefixtures("kinesis_moto")
def test_kinesis_fixtures(self, kinesis_streams):
... |
# 7. Реализовать проект «Операции с комплексными числами».
# Создайте класс «Комплексное число», реализуйте перегрузку
# методов сложения и умножения комплексных чисел.
# Проверьте работу проекта, создав экземпляры класса
# (комплексные числа) и выполнив сложение и умножение созданных
# экземпляров. Проверьте корректно... |
#!/usr/bin/env python
# coding=utf-8
# aeneas is a Python/C library and a set of tools
# to automagically synchronize audio and text (aka forced alignment)
#
# Copyright (C) 2012-2013, Alberto Pettarin (www.albertopettarin.it)
# Copyright (C) 2013-2015, ReadBeyond Srl (www.readbeyond.it)
# Copyright (C) 2015-2017, A... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import hashlib
import time
from model._base import Base
from peewee import CharField, IntegerField, PrimaryKeyField
class User(Base):
id = PrimaryKeyField()
user = CharField(max_length=32, unique=True)
name = CharField(max_length=32)
pwd = CharField(max_l... |
# -*- coding: utf-8 -*-
import os
from mmpy_bot import __version__
os.environ["DJANGO_SETTINGS_MODULE"] = "settings"
extensions = ["sphinx.ext.autodoc", "sphinx.ext.todo"]
templates_path = ["_templates"]
source_suffix = ".rst"
master_doc = "index"
project = "mmpy_bot"
copyright = "2016, "
version = __version__
rele... |
#!/usr/bin/env python2
from distutils.core import setup
setup(name='python-aliencoinrpc',
version='0.1',
description='Enhanced version of python-jsonrpc for use with Aliencoin',
long_description=open('README').read(),
author='Jeff Garzik',
author_email='<jgarzik@exmulti.com>',
main... |
from pyprintplus import Log
import time
class Notify():
def __init__(self, show_log=True, test=False):
self.logs = ['self.__init__']
self.show_log = show_log
self.started = round(time.time())
self.test = test
@property
def setup_done(self):
from _apis.models import... |
from setuptools import find_packages, setup
setup(
name='client',
packages=find_packages(),
description='FEDn client for FEDBIRD example.',
author='Scaleout Systems AB',
license='',
)
|
import socket
import select
def run():
HOST = '127.0.0.1' # The server's hostname or IP address
PORT = 8888 # The port used by the server
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.setblocking(False)
line = ""
while line !... |
import os
import subprocess
import sys
BENCHMARKS = [
'bubble_sort_benchmark',
'bubble_sort_benchmark2',
'bubble_sort_benchmark3',
# 'insertion_sort_benchmark',
# 'insertion_sort_benchmark2',
# 'insertion_sort_benchmark3',
# 'quick_sort_benchmark',
# 'quick_sort_benchmark2',
# 'quick_sor... |
#!/usr/bin/env python3
import time
import threading
import RPi.GPIO as GPIO
from lights import sunset, cleanup
RUNNING = False
duration = 30
def reset():
global RUNNING
RUNNING = False
def pushed(channel):
global RUNNING
if not RUNNING:
print("Button pushed")
RUNNING = True
... |
#!/usr/bin/env python
# trivial script to display any possible asterisms found
import pickle, sys
data = pickle.load(open(sys.argv[1],'rb'))
for x in data:
if len(x) > 4:
if sum(x[1:5]) != 0:
print(x)
|
def make_text_vectors(Text,XY,Anchor,Size):
if Anchor=='left':
X0=XY[0]
Y0=XY[1]
elif Anchor=='right':
X0=XY[0]-len(Text)*FontSize*Size
Y0=XY[1]
else:
X0=XY[0]-(len(Text)*FontSize*Size)/2
Y0=XY[1]
Res=[]
for Chr in Text:
Part=make_vector_let... |
from typing import Dict, List, Optional, Union, Any
from pydantic import BaseModel, Field
from haystack import Document
class QueryRequest(BaseModel):
query: str
params: Optional[dict] = None
class FilterRequest(BaseModel):
filters: Optional[Dict[str, Optional[Union[str, List[str]]]]] = None
class Que... |
import matplotlib.pyplot as plt
import torch
import torchvision
from torchvision import datasets, transforms
from tqdm import tqdm
from learners.classifier import Network, Trainer, Sample
from learners.util import get_batch
def test_network_single():
ndim_x = 28*28
n_actions = 10
net = Network(ndim_x, n_a... |
import copy
import numpy as np
import prettytable
class MonteCarloSolver(object):
"""Base Class for Markov Chain Monte Carlo Methods"""
def __init__(self, problem, params):
"""Basic parameters for a Monte Carlo Solver
problem: an ising.SpinGlass object.
params: dictionary of s... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.12
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
"""
IDA Plugin SDK API wrapper: dbg
"""
from sys import version_info
if version_info >= (2,6,0):
def swig_i... |
import gdal
# 读取要切的原图
in_ds = gdal.Open("./data/GF2_PMS1_E102_9_N25_1_20201213_L1A0005307913_ORTHO_PSH.tif")
print("open tif file succeed")
width = in_ds.RasterXSize # 获取数据宽度
height = in_ds.RasterYSize # 获取数据高度
outbandsize = in_ds.RasterCount # 获取... |
import numpy as np
class HeatIndex():
def __init__(self):
self.name = "Heat Index Function"
self.description = "This function combines ambient air temperature and relative humidity to return apparent temperature in degrees Fahrenheit."
self.doConversion = False
def getPar... |
import shutil
import os
train_test_set_file = open('./CUB_200_2011/train_test_split.txt')
train_list = []
test_list = []
for line in train_test_set_file:
tmp = line.strip().split()
if tmp[1] == '1':
train_list.append(tmp[0])
else:
test_list.append(tmp[0])
# print(len(train_list))
# print('^... |
import uuid
from app import users
from app.core.identify.sso import sso_account_record
from app.web import bp_api
from app.common.decorators import *
from app.core.lib import *
from app.common.func import is_manager, format_request, format_response
from app.model.exception import *
from app.common.util import *... |
import pandas as pd
import pyproj
from preprocess.load_data.data_loader import load_hotel_reserve
customer_tb, hotel_tb, reserve_tb = load_hotel_reserve()
# 분,초를 도로 변환하는 함수 정의
def convert_to_continuous(x):
# 아래의 식으로 실행하면 약간의 오차가 발생,
# 정확한 값으로 계산하고 싶을 땐, 문자열로 변환한 후 도,분,초의 값을 숫자로 변환하여 계산
x_min = (x * 100 - in... |
import unittest, random, sys, time
sys.path.extend(['.','..','py'])
import h2o_hosts,h2o_glm
import h2o, h2o_cmd, h2o_import as h2i
from pprint import pprint
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_errors()
@classmethod
def setUpClass(cls):
localhost = h2... |
r"""分数评估的主文件,可计算准确率,召回率,F1值,BLEU值
"""
import PRF, BLEU, sys
def evaluate(cn_file, en_file, en_ref_file):
PRF.calculate_F1(cn_file, en_file)
BLEU.BLEU(en_file, en_ref_file)
if __name__ == '__main__':
if len(sys.argv) != 4:
sys.exit(
'Expect three parameters\n such as: python evaluat... |
#!/usr/bin/python3
#
# Author: Jan Belohoubek
# Date: 09/2020
#
# Plot BIN size vs. BIN cnt
#
import numpy as np
import matplotlib.pyplot as plt
from scipy import optimize
import scipy.stats as stats
import math
import statistics
from scipy.stats import norm
# cmdline args
import argparse
parser = argparse.Argument... |
#!/usr/bin/env python
# compatibility with python 2/3:
from __future__ import print_function
from __future__ import division
import numpy as np
def init():
# Accepted file types
global ftypes
ftypes = {}
ftypes['1d'] = ['S1D',
's1d',
'ADP',
... |
# 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... |
import numpy as np
import os
import pickle
import streamlit as st
import sys
import urllib
from PIL import Image
import enhancement_options
from enhancement_names import *
import filter_options
from filter_names import *
import effect_options
from effect_names import *
import cv2
def call_filter(filter_choose,imag... |
from marty.commands import Command
from marty.printer import printer
WELLKNOW_TREE_ATTR_ORDER = ('filetype', 'mode', 'uid', 'gid', 'atime', 'mtime',
'ctime')
def tree_attr_sorter(value):
value = value[0]
try:
first = WELLKNOW_TREE_ATTR_ORDER.index(value)
except ValueE... |
# Copyright (c) 2022 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
#
# Un... |
import time as t
limit = 75
input_file = r"C:\Users\PLANETARY SCIENCE\Dropbox\AAG\AAG_SLD.dat"
output_file = r"C:\Users\PLANETARY SCIENCE\Dropbox\AAG\AAG_SLD_HUM.dat"
running_log = r"C:\Users\PLANETARY SCIENCE\Desktop\IoIO\data\AAG\AAG_SLD.log"
ooutput_txt = ""
while True:
try:
t.sleep(2)
with ope... |
import abc
import os
import typing
import pathlib
from collections import Iterable
from tqdm import tqdm
from torch.utils.data import Dataset as TorchDset
class Dataset(TorchDset):
"""
Extension of PyTorch's Datasets by a ``get_subset`` method which returns a
sub-dataset.
"""
def get_subset(se... |
import RPi.GPIO as GPIO
from manager import GrowStage
from enum import Enum
class Mode(Enum):
on = 0
off = 1
auto = 2
class State(Enum):
on = 0
off = 1
class Instrument():
def __init__(self, name):
self.name = name
self.mode = Mode.auto #whether it is forced on/off or allowed ... |
import datetime
import pendulum
import pytest
from dagfactory import utils
class TestGetStartDate(object):
now = datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)
cet = pendulum.timezone("Europe/Amsterdam")
utc = pendulum.timezone("UTC")
def test_date_no_timezone(self):
... |
#!/usr/bin/env python
# Copyright 2016 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... |
import torch
nmbr = 312 # the number you want to find the square root of.
start = torch.ones(1, requires_grad=True) # initial guess
for epoch in range(50):
loss = (start**2 - nmbr)**2 # the loss function
loss.backward()
#print('epoch %i:'%epoch,float(start.grad)) #-> printing gradients
start.data -= start.grad *... |
# ******************************************************************************
# Copyright 2017-2018 Intel Corporation
#
# 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.apa... |
# -*- coding: utf-8 -*-
import re
import nltk
import os
import csv
def get_pos_features(words):
tags=[]
# words=' '.join(i for i in wordsl)
pos_tags ={
'JJ':0,
'JJR':0,
'JJS':0,
'MD':0,
'NN':0,
'NNP':0,
'PR':0,
'RB':0,
'RBR':0,
'RBS':0,
'UH':0,
'V':0,
'W':0,
}
for item in words:
print (item)
pr... |
# cryptoCache functions used to communicate with contracts
# Import necessary libraries
from dotenv import load_dotenv
from web3 import Web3
import os
import json
import pandas as pd
def pull_token_ids(color_token):
# Instantiate variable
not_processed_token_ids = []
pink_contract_address = '0x541b0A62B9... |
# Author : CheihChiu
# Date : 2017-06-06
import flask
import logging
from flask import request
import os.path
import sys
import time
import cnn_captcha_break
import tensorflow as tf
import numpy as np
from PIL import Image
import requests
from io import BytesIO
logger = logging.getLogger('general')
exc_logger = ... |
from django.shortcuts import render
from .models import Book, Author, BookInstance, Genre
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.mixins import PermissionRequiredMixin
def index(request):
numBooks=Book.objects.all().count()
numInstance... |
"""
Schedule mainter is main module to run separated along with Bot as is scheduler the
task given by it. Huey will work along with the following dependency
for flexibility such as `RedisDB <https://redis.io/>`_ and along with
`Walrus <https://walrus.readthedocs.io/>`_ a lightweight and hight level api
Python utiliti... |
from tkinter import *
import tkinter as tk
from tkinter import ttk
from pytube import YouTube
from tkinter import filedialog, messagebox
from tkinter.messagebox import showinfo
ydl_opts = {
'format': 'bestaudio/best',
'extractaudio': True,
'audioformat': 'mp3',
'outtmpl': '%(title)s.f%(f... |
#!/usr/bin/env python
import rospy
from geometry_msgs.msg import Twist
from geometry_msgs.msg import Point
from gazebo_msgs.msg import ModelStates, ModelState
from gazebo_msgs.srv import SetModelState
from ds_sensor_msgs.msg import Dvl
import numpy as np
import math
from tf.transformations import euler_from_quaternion... |
import codecs
import hashlib
import json
from optparse import make_option
import os
import datetime
import shutil
from django.conf import settings
from django.core.management.base import BaseCommand
from django.utils.timezone import utc
from django.utils.translation import ugettext as _
from pythonnest.colors import ... |
from turtle import *
forward(150)
right(90)
forward(150)
right(90)
forward(150)
right(90)
forward(150)
done()
|
from django.db.models.signals import post_save, pre_delete
from django.dispatch import receiver
from django.utils.text import slugify, Truncator
from opencivicdata.core.models import (Organization as OCDOrganization,
Person as OCDPerson,
Pos... |
from flask import render_template, request, Blueprint
from app.models import Post
main = Blueprint("main",__name__)
@main.route('/')
@main.route("/home")
def home():
posts = Post.query.all()
return render_template("index.html", posts=posts, title="Home page")
@main.route("/about")
def about():
return r... |
"""
1. Clarification
2. Possible solutions
- Brute force
- Sort and find
3. Coding
4. Tests
"""
# # T=O(n^4), S=O(1), Time Limit Exceeded
# class Solution:
# def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
# n = len(nums)
# if n < 4: return []
# nums.sort()
# ... |
# -*- coding:utf-8 -*-
import os
import argparse
import numbers
import easydict
import yaml
import copy
import json
from . import file_utils
def parser_work_space(work_dir, flags: list = [], time=True):
"""生成工程空间
flag = [cfg.net_type, cfg.width_mult, cfg.input_size[0], cfg.input_size[1],
cfg.loss_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
### dotfiles.__main__
"""
dotfiles.__main__ --- a shim to dom
"""
import dotfiles.cli
if __name__ == "__main__":
dotfiles.cli.cli.main()
|
{
'targets': [
{
'target_name': 'bcrypt_lib',
'sources': [
'src/blowfish.cc',
'src/bcrypt.cc',
'src/bcrypt_node.cc'
],
'include_dirs' : [
"<!(node -e \"require('nan')\")"
],
'conditions': [
[ 'OS=="win"', {
'defines': [
... |
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.md')) as f:
readme = f.read()
setup(
name="nlpml",
version="0.1",
author="Johann Petrak",
author_email="johann.petrak@gmail.com",
... |
import setuptools
def readme():
with open("README.rst", "r") as fh:
return fh.read()
print(setuptools.find_packages())
setuptools.setup(
name = "zipfanalysis",
version = "0.6",
author = "Charlie Pilgrim",
author_email = "pilgrimcharlie2@gmail.com",
description = "Tools for analysing Zipf's law",
long_desc... |
# --------------------------------------------------------
# Tensorflow Faster R-CNN
# Licensed under The MIT License [see LICENSE for details]
# Written by Xinlei Chen
# --------------------------------------------------------
from __future__ import absolute_import
from __future__ import division
from __future__ impor... |
from ..utils import Object
class CheckPhoneNumberConfirmationCode(Object):
"""
Checks phone number confirmation code
Attributes:
ID (:obj:`str`): ``CheckPhoneNumberConfirmationCode``
Args:
code (:obj:`str`):
The phone number confirmation code
Returns:
Ok
... |
import string
import random
signe = '/?#><!-'
def pw_gen(size = 8, chars=string.ascii_letters + string.digits + signe):
p = ''.join(random.choice(chars) for c in range(size))
return p
def pw_gen_num(size = 8, chars=string.digits):
p = ''.join(random.choice(chars) for c in range(size))
retu... |
"""Initialization of API app."""
from __future__ import annotations
from typing import Any, Optional, Tuple
from flask import Flask, jsonify
from trickster.config import Config
from trickster.endpoints import external, internal, utility
from trickster.routing.router import Router
from werkzeug.exceptions import HT... |
import time
from threading import Thread
from time import sleep
#Definindo a classe time
class IntervalRunner(Thread):
def __init__(self, interval, function, *args, **kwargs):
super(IntervalRunner,self).__init__()
self.interval = interval
self.function = function
sel... |
import errno
import os
from motey.configuration.configreader import config
class BaseRepository(object):
"""
Base repository to wrapp database handling.
"""
def __init__(self):
"""
Constructor of the class.
"""
self.db = None
directory = config['DATABASE']['pa... |
import logging
from typing import List
from .ResultsObject import ResultsObject
from .utils import *
logger = logging.getLogger(__name__)
class Profile(ResultsObject):
"""Linkedin User Profile Object"""
attributes = ['personal_info', 'experiences',
'skills', 'accomplishments', 'interests'... |
#!/usr/bin/env python
# coding: utf8
#
# Copyright (c) 2020 Centre National d'Etudes Spatiales (CNES).
#
# This file is part of LIBSGM
#
# https://github.com/CNES/Pandora_libsgm
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# Y... |
import sys
import os
import re
from lxml import etree
try:
import dbus
import dbus.mainloop
import dbus.mainloop.glib
pass
except ImportError:
dbus=None
pass
if "gi" in sys.modules: # gtk3
import gi
gi.require_version('Gtk','3.0')
from gi.repository import Gtk as gtk
... |
"""
Example implementation of a NMEAMessage file reader
using the NMEAReader iterator functions
Created on 7 Mar 2021
@author: semuadmin
"""
from pynmeagps import NMEAReader, VALCKSUM, GET
import pynmeagps.exceptions as ube
class NMEAStreamer:
"""
NMEAStreamer class.
"""
def __in... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import sys
import json
import logging
import os
import time
import numpy as np
# sys.path.append('../../../examples/nas/darts')
from .model import CNN
from sklearn.manifold import TSNE
from abc import abstractmethod
from datetime import datetime
... |
import requests
import pyotp
import ConfigParser
DEFAULT_USER = "nobody"
CONFIG_LOC = "/home/joshua/Dev/pam-android-fingerprint/Desktop/config"
def pam_sm_authenticate(pamh, flags, argv):
print "Preparing to authenticate using fingerprint"
config = ConfigParser.ConfigParser()
config.readfp(open(CONFIG_L... |
from mcstats import mcstats
def create_ore_stat(title, oreId, oreName):
mcstats.registry.append(
mcstats.MinecraftStat(
'mine_' + oreId + '_ore',
{
'title': title,
'desc': oreName + ' ore mined',
'unit': 'int',
},
... |
import os
import torch
import matplotlib.pyplot as plt
from tqdm import tqdm
from .box_processes import BoxProcesses
from .metric import Metric
class Trainer:
def __init__(self, DEVICE):
self.DEVICE = DEVICE
# Training Records
self.train_mean_losses = None
self.val_mean_los... |
SPLASH_URL = 'http://localhost:8050/render.html'
|
# Modulo Tabela de Símbolos
# Direitos reservados por Fabricio Silva Cardoso e Pedro Ignácio Trevisan
#
# Programa responsavel por guardar as informações e os indetificadores.
#
# Este módulo serve para verificar, armazenar e buscar os identificadores.
#
# Todos os tipos estão disponiveis no... |
from math import sqrt
from statistics import mean
def std_dev(arr):
average = mean(arr)
return round(sqrt(sum((val - average) ** 2 for val in arr) / len(arr)), 1)
# or
# return round(statistics.pstdev(arr), 1)
# pstdev is population standard deviation, while stdev is sample standard devia... |
indice =1
factor = 1
number = int(input("insert n: "))
while indice <= number:
factor = factor * indice
indice = indice + 1
print (" Factor(%d) = %d" %(number,factor))
# %d allow you get the inserted string by imput#
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/18 18:15
# @Author : gsg
# @Site :
# @File : din.py
# @Software: PyCharm
import gc
import os
import numpy as np
import pandas as pd
import ast
import tensorflow as tf
from sklearn.preprocessing import LabelEncoder
# from keras import backend as K
dat... |
from getratings.models.ratings import Ratings
class NA_Maokai_Bot_Aatrox(Ratings):
pass
class NA_Maokai_Bot_Ahri(Ratings):
pass
class NA_Maokai_Bot_Akali(Ratings):
pass
class NA_Maokai_Bot_Alistar(Ratings):
pass
class NA_Maokai_Bot_Amumu(Ratings):
pass
class NA_Maokai_Bot_Anivia(Ratings):
... |
# GFM_LogStep.py
#
# A formatter plugin for Logarithmically stepped hash tables formatted
# for GitHub-Flavored Markdown (GFM), e.g. as used by Steemit
# articles.
#
# Generally not imported directly.
# Use TableFormatters.GetFMT("gfm_logstep", ...) to get instance.
#
import textwrap
from .common import *
@register_fo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.