content stringlengths 5 1.05M |
|---|
def main():
download_nested()
download_flat()
# Yuck
def download_nested():
print("Lets download a file")
if s.check_download_url():
if s.check_network():
if s.check_dns():
if s.check_access_allowed():
print("Sweet! we can download...")
... |
# -*- coding: utf-8 -*-
"""__init__.py: Django package container"""
from __future__ import unicode_literals
from __future__ import print_function
__author__ = 'Steven Klass'
__version_info__ = (1, 2, 3)
__version__ = '.'.join(map(str, __version_info__))
__date__ = '8/10/17 11:41'
__copyright__ = 'Copyright 2017 IC M... |
# -*- encoding: utf-8 -*-
"""
Flask Web App - Generated by www.AppSeed.us
AppSeed - developed by RoSoft | www.RoSoftware.ro
Licence: MIT
"""
import os.path
# Only cfg is here ..
class AppConfig(object):
# comon vars here
APP = 'app'
SECRET_KEY = "_9^MHFJhtTrNHFhdDdfdGJJJJJJ%$fVGhaXsa_!@#"
class Config... |
#!/usr/bin/env python3
"""
Ensures that the second code snippet in top-level README.md works.
"""
from leap_ec.algorithm import generational_ea
from leap_ec import ops, decoder, representation
from leap_ec.binary_rep import initializers
from leap_ec.binary_rep import problems
from leap_ec.binary_rep.ops import mut... |
# -*- coding: utf-8 -*-
"""
Created on Thu Dec 3 15:50:45 2020
@author: kahg8
"""
import tensorflow as tf
# Helper libraries
import numpy as np
from tensorflow.keras.wrappers.scikit_learn import KerasClassifier
from tensorflow.keras.optimizers import RMSprop,Adagrad,Adam
from tensorflow.keras.models import Model,... |
class JmeterTemplate:
def __init__(self):
'''
Jmx 模板文件
'''
self.temp = '''<?xml version="1.0" encoding="UTF-8"?>
<jmeterTestPlan version="1.2" properties="4.0" jmeter="4.0 r1823414">
<hashTree>
{test_plan}
<hashTree>
{thread_group}
<hashTree>
<ConstantTime... |
import itertools
import matplotlib.pyplot as plt
import numpy as np
def ceildiv(a, b):
return -(-a // b)
def plots_from_files(imspaths, figsize=(10,5), rows=1, titles=None, maintitle=None):
"""Plots images given image files.
Arguments:
im_paths (list): list of paths
figsize (tup... |
# -*- coding: utf-8 -*-
"""Main module."""
import os
import sys
import invoke
import click
def quote_line(input_line):
"""
Wraps ``input_line`` with double quotes.
Useful for paths with spaces.
:param input_string: string (if not a string, ``str(input_line)`` applied)
:returns: string
"""... |
from PIL import Image
from OpenGL.GL import *
from ctypes import c_void_p, c_short
import itertools
class Point(object):
def __init__(self, x, y, z):
self.x = float(x)
self.y = float(y)
self.z = float(z)
class Color(object):
def __init__(self, r, g, b, a = 1.0):
se... |
# Copyright 2019 Splunk, Inc.
#
# Use of this source code is governed by a BSD-2-clause-style
# license that can be found in the LICENSE-BSD2 file or at
# https://opensource.org/licenses/BSD-2-Clause
import pytest
import random
from jinja2 import Environment
from .sendmessage import *
from .splunkutils import *
from ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This file is part of tbucket daemon released under the MIT license.
# See the LICENSE file for more information.
import json
import six
import tornado.web
import tornado.gen
from tornado.web import stream_request_body
from tornado.web import HTTPError
from tornadis imp... |
import numpy as np
import pandas as pd
def hla_dict(file_name):
index=1
dict_hla={}
with open(file_name) as f:
for line in f:
line=line.strip()
dict_hla[line]=index
index=index+1
return dict_hla
def pro_sample_hla_code(df_sample_hla,dict_hla):
... |
"""Platform for go-eCharger sensor integration."""
import logging
from homeassistant.util.dt import utcnow
from homeassistant.const import (TEMP_CELSIUS, ENERGY_KILO_WATT_HOUR)
from homeassistant.helpers.entity import Entity
from homeassistant.const import CONF_HOST
from goecharger import GoeCharger
from . import DOM... |
import asyncio
import botocore.client
from botocore.exceptions import OperationNotPageableError
from botocore.history import get_global_history_recorder
from botocore.paginate import Paginator
from botocore.utils import get_service_module_name
from botocore.waiter import xform_name
from .paginate import AioPageIterat... |
import numpy as np
import pandas as pd
import re
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.cross_validation import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.learning_curve import validation_curve
from sklearn.linear_model import LogisticRegression
from sk... |
"""调用min_max模块中的多个函数"""
import min_max
x = float(input('实数x:'))
y = float(input('实数y:'))
z = float(input('实数z:'))
print('x和y中的最小值是{},最大值是{}。'.format(*min_max.min_max2(x, y)))
print('y和z中的最小值是{},最大值是{}。'.format(*min_max.min_max2(y, z)))
print('x和z中的最小值是{},最大值是{}。'.format(*min_max.min_max2(x, z)))
p... |
import numpy as np
from nbodykit.lab import cosmology
from utils import partial_derivative
def write_bases(rmin, rmax, saveto, ncont=300, **kwargs):
bases = get_bases(rmin, rmax, ncont=ncont, **kwargs)
np.savetxt(saveto, bases.T)
nprojbins = bases.shape[0]-1
return nprojbins, saveto
def get_bases(r... |
#define crypto_verify_PRIMITIVE "16"
#define crypto_verify crypto_verify_16
#define crypto_verify_BYTES crypto_verify_16_BYTES
#define crypto_verify_IMPLEMENTATION crypto_verify_16_IMPLEMENTATION
#define crypto_verify_VERSION crypto_verify_16_VERSION
#define crypto_verify_16_tweet_BYTES 16
#define crypto_verify_16_twee... |
#!/usr/local/bin/python3.3
L = [1, 2, 3]
print(L)
print("Then length of L is %d" % len(L))
L = [1, 2, 3] + [4, 5, 6]
print("Now L is %s" % L)
L = ["Ni!"] * 4
print(L)
L = [1, 2]
L = str(L) + "34"
print(L)
L = [1, 2]
L = L + list("34")
print(L)
print(3 in [1, 2, 3])
for x in [1, 2, 3]:
print(x, end=" ")
print();
... |
#!/usr/bin/env python
import sys, os, re
classes_ignore_list = (
'OpenCV(Test)?Case',
'OpenCV(Test)?Runner',
'CvException',
)
funcs_ignore_list = (
'\w+--HashCode',
'Mat--MatLong',
'\w+--Equals',
'Core--MinMaxLocResult',
)
class JavaParser:
def __init__(self):
... |
#!/usr/bin/env python
'''Farmware Tools Tests: device'''
from __future__ import print_function
import time
from farmware_tools import app, device
def run_tests(TEST, app_login):
'Run device tests.'
COORDINATE = device.assemble_coordinate(1, 0, 1)
OFFSET = device.assemble_coordinate(0, 0, 0)
URL = 'ht... |
# coding:utf-8
__author__ = "gaunt"
from . import SysRoleAuthorities
def get_authorities(role_id):
sql = SysRoleAuthorities.select(SysRoleAuthorities.authority).where(SysRoleAuthorities.role_id == role_id)
result = [f for f in sql.dicts()]
return result
|
import pathlib
from nose.tools import assert_raises
from nose.tools import eq_
import ebus
from ebus import FieldDef
from ebus import MsgDef
from ebus.types import IntType
from ebus.types import TimeType
from .util import cmp_
TESTDATAPATH = pathlib.Path(__file__).parent / "testdata"
def test_msgdefs0():
"""M... |
from enum import Enum
class Instructions(Enum):
RIGHT = 1
DOWN = 2
LEFT = 3
UP = 4
SPEED_UP = 5
SPEED_DOWN = 6
TURN_LEFT = 7
TURN_RIGHT = 8
DIRECTIONS = [
Instructions.RIGHT,
Instructions.DOWN,
Instructions.LEFT,
Instructions.UP,
]
SPEED_CHANGES = [
Instructions.S... |
#
# Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0
#
# or in the "license" file ... |
VERSION = (0, 10, 2)
default_app_config = 'sitegate.config.SitegateConfig'
|
d = float(input('Quanto dinheiro você tem na caeteira: R$ '))
print('Com R${} você pode comprar\n{}U$ {:.2f}{}'.format(d, '\033[1;32m', d/5.27, '\033[m'))
print('{}€ {:.2f}{}'.format('\033[1;36m', d/6.39, '\033[m'))
print('{}¥ {:.2f}{}'.format('\033[1;31m', d*20.77, '\033[m'))
|
from pathlib import Path
import pytest
from monitor.sensors import DS18B20Sensor, SensorType, SensorInitError, SensorMeasurementError, SensorConfigError
@pytest.fixture
def good_measurement():
return '''bd 00 4b 46 ff ff ff ff ff ff : crc=ff YES
bd 00 4b 46 ff ff ff ff ff ff t=27772'''
def test_ds18b20_in... |
import torch
import torch.nn.functional as F
# Pleasant : Maximize vca_fake = 1
# # Loss is lowest when -1 * 1 = -1, highest when -1 * 0
def loss_vca_gen_pleasant(vca_fake):
loss = -torch.mean(vca_fake)
return loss
# Unpleasant: Maximize vca_fake = 0
def loss_vca_gen_unpleasant(vca_fake):
loss = torch.mean(vca_... |
import numpy as np
import matplotlib.pyplot as plt
from . import transform
def plot_pulse(pulse, m=1000, ptype='ex', phase='linear',
omega_range=[-np.pi, np.pi],
linewidth=2, fontsize='x-large', labelsize='large'):
figs = []
n = len(pulse)
fig, ax = plt.subplots()
ax.plot... |
"""
********************************************************************************
* Name: spatial_attributes_rws.py
* Author: nswain
* Created On: December 17, 2018
* Copyright: (c) Aquaveo 2018
********************************************************************************
"""
from tethysext.atcore.models.resource... |
# -*- encoding: utf-8 -*-
"""
Fully Coded App by AppSeed.us
License: MIT
For more apps please access https://appseed.us/
Copyright (c) 2019 - present AppSeed.us
"""
import os
# Grabs the folder where the script runs.
basedir = os.path.abspath(os.path.dirname(__file__))
# Only cfg is here ..
class AppConfig(object):... |
"""
Integration test for train_standard_classifiers
"""
import configparser
import os
from pathlib import Path
import pytest
from lib.testing import get_mlflow_stub
from processes.train_standard_classifiers.classifiers import train_classifiers
vscode_config = configparser.ConfigParser()
vscode_config.read("lab/proc... |
from textx import metamodel_for_language
from textx import get_children_of_type
from textx.exceptions import TextXSemanticError
import os
import pytest
from item_lang.properties import (
get_property,
has_property,
get_all_possible_properties,
get_all_possible_mandatory_properties,
get_property_set,... |
from .http import HTTPDependency
from dvc.remote.https import HTTPSRemote
class HTTPSDependency(HTTPDependency):
REMOTE = HTTPSRemote
|
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Valiant Systems and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from frappe import _
from frappe.desk.form.linked_with import get_linked_doctypes
class Sect... |
from __future__ import annotations
from collections import defaultdict
from icecream import ic
class SchoolOfLanternfish:
fish: defaultdict[int, int]
count: int = 0
def __init__(self) -> None:
self.fish = defaultdict(int)
def add_fish(self, clock_day, count=1):
self.fish[clock_day] +... |
def test_importability():
from ansicolor import black # noqa
from ansicolor import blue # noqa
from ansicolor import cyan # noqa
from ansicolor import green # noqa
from ansicolor import magenta # noqa
from ansicolor import red # noqa
from ansicolor import white # noqa
from ansicol... |
import module
module.
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-08-30 09:06
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('tasks', '0032_add_skill_permission'),
('tasks', '0028_auto_20170817_1546'),
]
opera... |
"""A RESTful Wagtail enclosure"""
__version__ = '0.2.2'
default_app_config = 'wagtailnest.apps.WagtailnestConfig'
|
'''
@author: Marco Bonvini
'''
import numpy
import pandas as pd
from estimationpy.fmu_utils.csv_reader import CsvReader
from estimationpy.fmu_utils import strings
import pyfmi
import logging
logger = logging.getLogger(__name__)
class InOutVar():
"""
This class represents a generic input or output variable of... |
#! usr/bin/env python
from airflow import DAG
from airflow.operators import BashOperator
from datetime import datetime, timedelta
__author__ = "Jonathan Hilgart"
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2017, 3, 1),
'email': ['jonathan.hilgar... |
# Generated by Django 3.2.7 on 2021-11-06 20:31
from django.db import migrations, models
import django.db.models.deletion
import django_extensions.db.fields
class Migration(migrations.Migration):
dependencies = [
("expense", "0001_initial"),
]
operations = [
migrations.CreateModel(
... |
# -*- coding: utf-8 -*-
# Copyright (C) 2016-2017 Mag. Christian Tanzer All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at
# #*** <License> ************************************************************#
# This module is part of the package GTW.__test__.
#
# This module is licensed under th... |
import torch.nn as nn
from lib.rpn_util import *
from models import resnet
import torch
import numpy as np
from models.deform_conv_v2 import *
def dynamic_local_filtering(x, depth, dilated=1):
padding = nn.ReflectionPad2d(dilated) # ConstantPad2d(1, 0)
pad_depth = padding(depth)
n, c, h, w = x.size()
... |
from app.utils.common import Choices
from .geometry import Vector
class Directions(Choices):
up = 'up'
right = 'right'
down = 'down'
left = 'left'
@classmethod
def delta(cls, direction):
delta = Vector(0, 0)
if direction == cls.up:
delta.set(0, -1)
elif dir... |
from base64 import b64encode, b64decode
from getpass import getpass
from hashlib import sha256
from os import environ
from Crypto import Random
from Crypto.Cipher import AES
from .._config import *
class Crypto:
'''
Helper class for encrypting and decrypting data.
Asks for user-defined... |
import numpy as np
import pandas as pd
import os
import nltk
from nltk.corpus import stopwords, twitter_samples
from nltk.stem import PorterStemmer
from nltk.tokenize import TweetTokenizer
import re
import pickle
from collections import OrderedDict
import torch
from src.config import cfg
from gensim.models import FastT... |
#!/usr/bin/env python
__author__ = 'dcrawford'
from EPPs import glsapiutil
from xml.dom.minidom import parseString
from optparse import OptionParser
api = None
def limslogic():
def writecsv():
content = ['Input Plate, Input Well, Output Plate, Output Well']
for art in sortedArtifacts:
... |
import time
import torch
from .metrics import Metric
def print_progress(batch_idx, batch_size, total_size, prefix="", suffix=""):
current = batch_idx * batch_size
ratio = current / total_size
shift = 0
n = 10
while n <= total_size:
shift += current < n
n *= 10
bar_numbers = "... |
# 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
from tabulator.parser import Parser
from tabulator.helpers import reset_stream
class ExcelXMLParser(Parser):
options = []
def __init__(self, loader, force_parse, **options):
self.__loader = loader
self.__force_parse = force_parse
self.__extended_rows = None
self.__encoding = N... |
import importlib
import importlib.machinery
import importlib.util
import logging
import os
import sys
import time
import traceback
import winreg
from pathlib import Path
from types import ModuleType
from typing import List, Dict, Set, Iterable, Any, Tuple, Callable, Optional
import natlink
from natlink.config import L... |
# coding: utf-8
"""
Talend Management Console Public API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import abs... |
from tests.utils import file_response
from documenters_aggregator.spiders.cook_county import Cook_countySpider
test_response = file_response('files/cook_county_event.html',
url='https://www.cookcountyil.gov/event/cook-county-zoning-building-committee-6')
spider = Cook_countySpider()
item... |
# Lint as: python3
"""Tests for loudness_predictor."""
import tensorflow.compat.v2 as tf
import data_processing
class DataProcessingTest(tf.test.TestCase):
def setUp(self):
"""Sets up inputs, predictions and targets."""
super(DataProcessingTest, self).setUp()
self.expected_batch_size = 3
self.data... |
from cron_validator import CronValidator
def is_valid(expression: str) -> bool:
if not expression:
return False
_input = expression.split()
if len(_input) < 6:
return False
try:
CronValidator.parse(" ".join(_input[:5]))
except ValueError:
return False
return... |
import open3d as o3d
import os
import numpy as np
from pyntcloud import PyntCloud
def voxel_filter(point_cloud, leaf_size):
'''
function: point cloud voxelization through randomly sampling
args:
point_cloud
leaf_size
return:
filtered points
'''
filtered_points = []
... |
from logic_gates.gates import Circuit, nand
from logic_gates.model import Model
__all__ = ['Model', 'Circuit', 'nand']
|
from flask import Flask
app = Flask(__name__)
'''
before_request = {before, befores}
'''
@app.before_request
def before():
print('before')
@app.before_request
def befores():
print('befores')
'''
after_request = {after, afters}
{afters,after} = eversed(after_request)
'''
@app.after_request
def after(re... |
from ftplib import FTP
HOST = 'ftp1.at.proftpd.org'
with FTP(HOST) as ftp:
ftp.login()
ftp.set_debuglevel(2)
ftp.set_pasv(False)
print(ftp.dir())
print(ftp.getwelcome())
print(ftp.sendcmd('PWD'))
print(ftp.sendcmd('SYST'))
print(ftp.voidcmd('PWD'))
print(ftp.dir())
# with open('... |
import time
import pandas as pd
def stock_main():
start_time = time.time()
# take 0.49767 s
df = pd.read_csv("prices-split-adjusted.csv")
elapsed_time = time.time() - start_time
print(elapsed_time)
print(df.head())
# https://stackoverflow.com/questions/15943769/how-do-i-get-the-row-count-o... |
# This script downsamples sensor suite data from 20kHz to 10Hz and
# adds estimated timestamps based on average count and sample rate
import matplotlib.pyplot as plt
IN_FILE = '../ColdFlow2_2022_Mar_29/data/coldflow-sensors-125.txt'
OUT_FILE = '../ColdFlow2_2022_Mar_29/data/coldflow-sensors-125-avg.csv'
OUT_SCALED_F... |
# Giovanna Pavani Martelli - 19173
# Maria Luiza Sperancin Mancebo - 19186
# Vinicius Martins Cotrim - 19040
# MATERIA - TI502: ROBO SEGUIDOR DE LINHA DESVIADOR DE OBSTACULO E MANDADOR DE FOTO
from controller import Robot
import math
import socket
import struct
import sys
import _thread
import base64 #imports de biblio... |
"""Read all glyphs from the demo font, and write them out again.
This is useful for testing round-tripping stability, but also to
update the font when the GLIF format changes. The third application
is to update the contents.plist file in case glyphs have been added
or removed.
"""
import os
from robofab.test.testSupp... |
# -*- coding: utf-8 -*-
from __future__ import division, unicode_literals
import collections
from . import config
from . import lexers
from .messages import *
from .htmlhelpers import *
from .widlparser.widlparser import parser
ColoredText = collections.namedtuple('ColoredText', ['text', 'color'])
class IDLUI(object)... |
import requests
import pprint
query = "select id from sample_phenopackets.ga4gh_tables.gecco_phenopackets where json_extract_scalar(phenopacket, '$.subject.sex') = 'MALE' limit 3"
payload = "{\"query\":\"" + query + "\"}"
payload = {'query':query}
headers = {
'content-type': 'application/json'
}
next_url = "https... |
import numpy as np
from numerical import splines
from numerical.utils.interpolation import repeat_args
def interpolate(values, grid, batch_size=16):
""" Builds function which is an interpolation function on nodes with computer values in these nodes.
Args:
values: list of function values in grid node... |
# @Title: 子集 II (Subsets II)
# @Author: KivenC
# @Date: 2018-07-25 15:22:43
# @Runtime: 52 ms
# @Memory: N/A
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
res = [[]]
temp = 0
... |
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from django.urls import reverse
from project_core.tests import database_population
class ProposalsExportZip(StaticLiveServerTestCase):
port = 9998
def setUp(self):
self._proposal = database_population.create_proposal()
s... |
import sqlite3
from sqlite3 import Error
# DATABASE_MEMORY = ':memory:'
DATABASE_MEMORY = 'python-methods.db'
def run_query(create_table_sql):
try:
cursor = conn.cursor()
cursor.execute(create_table_sql)
return cursor
except Error as e:
print(e)
def insert_album(artist, tit... |
import socket
from this import d
import time
import sys
from threading import Thread
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# GLOBAL VARIABLES
IP = 'localhost'
PORT = 9999
MAX_USERS = input("Max Connections: ")
MSG = ""
# MODE = input("Data Mode - (1) or Announcement Mode - (2)")
D... |
# Generated by Django 3.0.4 on 2020-03-31 21:33
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('reading', '0006_readinglistmetadata'),
]
operations = [
migrations.AddField(
model_name='readinglis... |
'''
(*)~---------------------------------------------------------------------------
Pupil - eye tracking platform
Copyright (C) 2012-2018 Pupil Labs
Distributed under the terms of the GNU
Lesser General Public License (LGPL v3.0).
See COPYING and COPYING.LESSER for license details.
------------------------------------... |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0.
# This script is used to update License end year for those hand crafted files
# Auto-generated files will be automatically updated by code-generator when published to release candidate in our code pipeline
# Sim... |
import io
import os
import tarfile
import multiprocessing as mp
mp.set_start_method("spawn", True)
test_file = "./test.tar"
def test_decrypt():
reader, proc = get_reader(test_file)
with os.fdopen(reader, "rb", buffering=4096) as fr:
# load data to memory
byte_array = io.BytesIO(fr.read())
... |
import pandas as pd
import plotly.graph_objects as go
import numpy as np
from collections import deque
from pathlib import Path
class Protein(object):
aa_df = pd.read_csv(Path(__file__).parent.parent/'data/amino_acid_properties.csv')
aa_df = aa_df.rename(columns={"hydropathy index (Kyte-Doolittle method)": ... |
__all__ = ['imread', 'imsave']
from skimage.utils.dtype import convert
try:
import imread as _imread
except ImportError:
raise ImportError("Imread could not be found"
"Please refer to http://pypi.python.org/pypi/imread/ "
"for further instructions.")
def imread(fna... |
#!/usr/bin/env python
"""
bioBakery Workflows: stats visualization workflow
Copyright (c) 2019 Harvard School of Public Health
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction... |
from nonebot.rule import Rule
from nonebot.typing import T_State
from nonebot.adapters.cqhttp.bot import Bot
from nonebot.adapters.cqhttp.event import Event
from omega_miya.utils.Omega_Base import DBBot, DBFriend, DBBotGroup, DBAuth
class OmegaRules(object):
# Plugin permission rule
# Only using for group
... |
from pathlib import Path
from utils.file_handling import *
def setup_toml() -> None:
if Path('config/config.toml').exists():
with open("config/config.toml", "r+") as file, open("config/base_config.toml", "r") as base_file:
# Adds any extra fields from the base config file when updating the bot... |
'''
indexing is helpful for analysing and manipulating data for find insight.
slicing :: numpy array can be sliced.
'''
#np is alias for numpy
import numpy as np
arr = np.array( [[-1, 2, 0, 4],
[-3, 5, 7, 3],
[5, 3, -4, 2],
[6, -5, 1, 6]] )
# slicing with first 2... |
from django.apps import AppConfig
class AppBusConfig(AppConfig):
name = 'app_bus'
|
from django.apps import AppConfig
class GroupsConfig(AppConfig):
name = 'groups'
|
''' Instrução break: A instrução break interrompe a execução do laço de repetição
onde está contido. ''' |
#! /Users/michael/anaconda3/bin/python
# @Date: 2018-09-26 08:08:10
import pymongo
import json
# Connect to mongo
db = pymongo.MongoClient()['instagram']
col = db['col']
data = []
for item in col.find({}):
item.pop('_id')
data.append(item)
res = json.dumps({"data": data})
with open('data.json', 'w', enc... |
#!/usr/bin/env python
import os
from kernelio import KernelManager
from progress import ProgressMonitor
SRC = 'desert_no_mountains'
DST = ( 'desert_no_sea', 'desert_no_sunset', 'desert_no_trees',
'mountains_no_desert', 'mountains_no_sea', 'mountains_no_sunset',
'mountains_no_trees', 'sea_no_desert', 'sea_no_mountains... |
import logging
from pathlib import Path
import pandas
from typing import Dict, Any, Tuple
from datetime import datetime
import numpy as np
try:
import cv2
from cv2 import VideoWriter_fourcc as fourcc
except ImportError:
cv2 = fourcc = None
try:
from matplotlib.pylab import figure
from matplotlib.c... |
from flask import render_template, redirect, url_for, abort, flash, request,\
current_app, make_response , send_file
from flask_login import login_required, current_user
from flask_sqlalchemy import get_debug_queries
from . import main
from .forms import EditProfileForm, EditProfileAdminForm , GenerateScheduleForm
... |
from client.main import run_client
run_client()
|
import time
import threading
import Queue
class WorkerThread(threading.Thread):
def __init__(self, taskQueue):
threading.Thread.__init__(self)
self.taskQueue = taskQueue
def run(self):
while True:
time.sleep(0.05)
task = self.taskQueue.get()
result =... |
import telethon as te
from telethon import TelegramClient, events
from telethon.utils import get_display_name
api_id = <api_id>
api_hash = <api_hash>
client = te.TelegramClient('anon', api_id, api_hash)
@client.on(events.NewMessage())
async def my_event_handler(event):
await client.get_dialogs()
se... |
# Copyright 2020 Inspur
#
# 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... |
# coding: utf-8
import typing
from sqlalchemy import Boolean
from sqlalchemy import Column
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import Text
from sqlalchemy.orm import relationship
from rolling.server.document.base import SqliteNumeric
from roll... |
lista = list()
try:
nome = str(input('\033[1:31:41mNome do Atleta:\033[m '))
print('-'*20)
for c in range(1, 6):
salto = float(input(f'\033[1:31:40mDigite altura do {c}º:\033[m '))
lista.append(salto)
lista.sort(reverse=True)
med = 0
for c in lista[1:4]:
med = sum(lista)... |
import skia, struct, tempfile
from pathlib import Path
from fontTools.pens.transformPen import TransformPen
from fontTools.misc.transform import Transform
from fontTools.pens.basePen import BasePen
from coldtype.pens.datpen import DATPen, DATText
from coldtype.geometry import Rect, Edge, Point
from coldtype.pens.dra... |
"""
This script tests the sampling of truncated Poisson variable.
"""
import torch
from estimation.truncated_poisson import TruncatedPoisson
rate = torch.Tensor([0.1, 0.6, 0.7, 5])
dist = TruncatedPoisson(rate)
sample = dist.sample()
print(sample) |
# -*- coding: utf-8 -*-
"""Pipeline logging process
This module will log all events generated by the pipeline process
Author:
Elvin Ellis Smith Jr
Example:
$ python PipelineLogger.py
To-do:
* NA
Changelog:
* 2021-05-01: Initial release
License:
MIT <https://mit-license.org/>
... |
#!BPY
"""
Name: 'Lightmap UVPack'
Blender: 242
Group: 'UVCalculation'
Tooltip: 'Give each face non overlapping space on a texture.'
"""
__author__ = "Campbell Barton aka ideasman42"
__url__ = ("blender", "blenderartists.org")
__version__ = "1.0 2006/02/07"
__bpydoc__ = """\
"""
# ***** BEGIN GPL LICENSE BLOCK *****
#... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.