content
stringlengths
5
1.05M
import asyncio import logging from discord.ext import commands import config from classes.bot import Transcript logging.basicConfig(level=logging.INFO) logger = logging.getLogger() logger.setLevel(logging.INFO) handler = logging.FileHandler(filename="botlog.log", encoding="utf-8", mode="w") handler.setFormatter(logg...
from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.views.generic.detail import DetailView from django.views.generic.list import ListView from django.utils.decorators import method_decorator from django.core.exceptions import PermissionDenied from django.contrib.auth.decorators import l...
class Counter(object): def __init__(self, total_number, interval=100, name="Counter"): super(Counter, self).__init__() self.total_number = total_number self.processed_child = 1 self.interval = interval self.name = name print "%s total: %d" % (self.name, self.total_nu...
""" Authors: Sridhar Gopinath, Nishant Kumar. Copyright: Copyright (c) 2020 Microsoft Research 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, including without limitation th...
# -*- coding: utf-8 -*- # Copyright (c) 2010-2017 Tuukka Turto # # 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, including without limitation the rights # to use, copy,...
class pidcontroller0: 'This is a pid controller ' def __init__(self): # Temperature setpoint for the contoller self.aimTemperature = 273.0 + 30 # Gains built from the ML model self.kp = 1.0 self.ki = 1.0 self.kd = 1.0 print("Gains loaded for the PID con...
#!/usr/bin/python # author luke import re ret = re.match("[A-Z][a-z]*","MM") print(ret.group()) ret = re.match("[A-Z][a-z]*","MnnM") print(ret.group()) ret = re.match("[A-Z][a-z]*","Aabcdef") print(ret.group()) print('-'*50) # 需求:匹配出,变量名是否有效 names = ["name1", "_name", "2_name", "__name__"] for name in names: ...
# -*- coding: utf-8 -*- from django.shortcuts import render, redirect, render_to_response from ..forms import roleForm from ..utils import RoleUtil from ..enum.MessageCode import Error from ..utils.PathUtil import Path from ..utils.PathUtil import Html from ..utils import SessionUtil from ..enum.FunctionCode import Fun...
import socket #flag{thank_you_bfox} #list dir sh1=("\xeb\x45\x31\xc0\x31\xff\x47\x47\x47\x47\x01\xf8\x40\x5b\x31\xc9\x31\xd2\xcd\x80" "\x85\xc0\x74\x28\x89\xc3\x31\xd2\x83\xc2\x01\xc1\xe2\x08\x29\xd4\x89\xe1\x31\xc0" "\x83\xc0\x01\xc1\xe0\x07\x83\xc0\x0d\xcd\x80\x89\xc2\x89\xe1\x31\xdb\x80\xc3\x01" ...
import json from chia.types.blockchain_format.program import INFINITE_COST from chia.types.spend_bundle import SpendBundle from chia.types.generator_types import BlockGenerator from chia.consensus.cost_calculator import NPCResult from chia.consensus.default_constants import DEFAULT_CONSTANTS from chia.full_node.bundle...
ckpt_dir = '/WorkSpace/FedOptim/ckpts' data_dir = '/data' tb_dir = '/WorkSpace/FedOptim/runs' download = True num_trains = { 'celeba': 81385, # total 162770 'cifar': 50000, 'coco': 59144, # total 118287 'fmnist': 60000, 'mnist': 60000, 'svhn': 73257, 'voc': 1464, } num_tests = { 'cel...
import subprocess from flask import Response from flask import Flask app = Flask(__name__) @app.route('/<what>') #@app.route('/', defaults={'what': 'moo'}) def cowsay(what): return Response(subprocess.check_output('cowsay %s' % what, stderr=subprocess.STDOUT, shell=True), mimetype = 'text/plain')
from django.shortcuts import render, get_object_or_404 from django.core.exceptions import PermissionDenied from django.contrib.auth.decorators import login_required from django.http import JsonResponse, Http404 from django.contrib.auth.models import User from .models import SharedFolder, SharedFile from myfiles.models...
""" Замыкание (англ. closure) в программировании — функция первого класса, в теле которой присутствуют ссылки на переменные, объявленные вне тела этой функции в окружающем коде и не являющиеся её параметрами. Говоря другим языком, замыкание — функция, которая ссылается на свободные переменные в своей области видимости....
import jesse.helpers as jh from jesse.enums import order_types, sides, order_statuses from jesse.models import Order def test_cancel_order(): order = Order({ 'id': jh.generate_unique_id(), 'symbol': 'BTCUSD', 'type': order_types.LIMIT, 'price': 129.33, 'qty': 10.2041, ...
from ..const import MATERIAL_TAG from ..nodes.outputs import get_active_output def has_material(obj): if len(obj.material_slots) >= 1: for mat_slot in obj.material_slots: if mat_slot.material: if MATERIAL_TAG not in mat_slot.material.keys(): material_output ...
# https://github.com/marquee/noat import cgi # Public: class that manages the public API and stores the working data. # # * text - A string of arbitrary content, to have annotations applied. The # string MAY be empty, but then its annotations MUST only cover # the position 0. # # The instance is...
from inspect import currentframe __all__ = ["add_props_to_ns", "add_classprops_to_ns", "classproperty", "props_as_dict"] def prop_getsetdel(property_name, prefix="_", read_only=False, deletable=False): internal_attr = prefix + property_name def prop_getter(internal_attr): def getter_func(self): ...
# ATMegaZero Sensors Shield # # You can purchase the ATMegaZero Sensors Shield from the ATMegaZero Online Store at: # https://shop.atmegazero.com/products/atmegazero-sensors-shield-compatible-with-the-raspberry-pi # # For full documentation please visit https://atmegazero.com import time import board import busio impo...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright 2011-2020, Nigel Small # # 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 # # Unle...
from OSIM.Modeling.CircuitSystemEquations import CircuitSystemEquations from OSIM.Simulation.CircuitAnalysis.CircuitAnalyser import CircuitAnalyser from OSIM.Simulation.NetToComp import NetToComp #seq = CircuitSystemEquations(NetToComp('Transistor_invers.net').getComponents()) #ca = CircuitAnalyser(seq) #ca.plot_lin(c...
from cms import api from cms.models import Page from django.contrib.auth.models import User from django.core.exceptions import ObjectDoesNotExist from django.test import TestCase from icecream import models class BaseRelationsTestCase(TestCase): LANGUAGE = 'en' PASSWORD = 'pw' TEMPLATE = 'cms_page.html...
"""Auto-delete old resources to make room for new ones.""" from logging import getLogger from robot_server.deletion_planner import RunDeletionPlanner from .run_store import RunStore _log = getLogger(__name__) class RunAutoDeleter: # noqa: D101 def __init__( self, run_store: RunStore, ...
# # Copyright 2021. Futurewei Technologies 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 # # Unl...
import argparse import getpass import os JUPYTER_SERVICE_TEMPLATE = """ [Unit] Description=Jupyter Notebook Service [Service] Type=simple User=%s ExecStart=/bin/sh -c "jupyter lab --ip=0.0.0.0 --no-browser" WorkingDirectory=%s Restart=always [Install] WantedBy=multi-user.target """ JUPYTER_SE...
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2009,2010,2011,2013,2016 Contributor # # 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 t...
#!/usr/bin/env python3 import argparse import re import sys import time from datetime import datetime from jira import JIRA def dump(obj): for attr in dir(obj): print("obj.%s = %r" % (attr, getattr(obj, attr))) def print_help(stream=sys.stderr): help_msg = """Usage: {0} -startdate YYYY-MM-DD -endd...
import logging import os import time from typing import Tuple from pathlib import Path import torch import torch.optim from torch.utils.data import DataLoader # from torch.utils.tensorboard import SummaryWriter from tqdm import tqdm from .common import Transform from .dataset import TLDataset from .model ...
num = 0 while True: num = int(input('Tabuada de qual valor? ')) if num < 0: break for c in range(1, 11): print(f' {c} x {num} = {c * num}') print('=-' * 20)
# -*- coding: utf-8 -*- """Pytest fixtures shared between other modules.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import glob import os import shutil import tempfile import pytest import tensorflow as tf # noinspection PyTrailingSemicolon import ...
"""Météo-France models for the REST API.""" from .forecast import Forecast from .picture_of_the_day import PictureOfTheDay from .place import Place from .rain import Rain from .warning import CurrentPhenomenons from .warning import Full __all__ = ["Forecast", "Place", "PictureOfTheDay", "Rain", "CurrentPhenomenons", "...
import json from .client import Client class ClientJsonInput(Client): def __init__(self, args): super().__init__(args) self.json_data_file = self.get_json_data_file() def get_only_fail_rule(self, rules): """ Function processes array of matched IDs of rules in selected file. ...
"""Module for settings-related code.""" # WORKAROUND: https://mypy.readthedocs.io/en/stable/common_issues.html#using-classes-that-are-generic-in-stubs-but-not-at-runtime # noqa: E501 from __future__ import annotations from typing import Any, List, Optional from dataclasses import dataclass import os import json from p...
# coding: utf-8 # 19-1-30 下午12:36 import jieba def simple(): seg_list = jieba.cut_for_search("小明硕士毕业于中国科学院计算所,后在日本京都大学深造") # 搜索引擎模式 print(seg_list) seg_list = jieba.cut_for_search(''' Home - BBC News 打车回家, http://www.bbc.com/news 跟司机师傅聊天, Visit BBC News for up-to-the-minute news, breaking news, video, ...
n_groups = 16 coarse_X = X.reshape(n_groups, n_neurons//n_groups, timesteps).mean(1) assert coarse_X.shape == (n_groups, timesteps) R = correlation_for_all_neurons(coarse_X) coarse_A = A.reshape(n_groups, n_neurons//n_groups, n_groups, n_neurons//n_groups).mean(3).mean(1) with plt.xkcd(): fig, axs = plt.subplots...
"""ipelago: CLI personal microblog (命令行个人微博客)""" __package_name__ = "ipelago" __version__ = "0.0.5" __author__ = "102419@gmail.com" __license__ = "MIT"
# note from .DynamicMaxPooling import DynamicMaxPooling from .Match import Match from .MatchTensor import MatchTensor from .SparseFullyConnectedLayer import SparseFullyConnectedLayer
import os # 開発 # os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') # from django import setup # setup() # デプロイ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.production') from django import setup setup() import datetime as dt from datetime import date from django.db.models i...
import os import time import warnings import random import argparse import torch import numpy as np import pandas as pd import cv2 from sklearn.model_selection import train_test_split from matplotlib import pyplot as plt import torch.nn as nn import torch.optim as optim import torch.backends.cudnn as cudnn from torch...
import os import warnings import pytest from python_json_config.config_node import ConfigNode def test_creation(config_dict): node = ConfigNode(config_dict) assert node.key1 == 1 assert node.__dict__["_ConfigNode__path"] == [] assert isinstance(node.key2, ConfigNode) nested_node = node.key2 ...
# -*- coding: utf-8 -*- from py2neo import Graph class AnswerSearcher: def __init__(self): self.g = Graph( # host="127.0.0.1", # http_port=7474, user="neo4j", password="ckong") self.num_limit = 20 '''执行cypher查询,并返回相应结果''' def search_main(s...
""" Command line interface description for qtools3. Author: James K. Pringle E-mail: jpringle@jhu.edu """ import argparse from qtools3 import constants def get_parser(): prog_desc = ('Convert files from XLSForm to XForm and validate. ' 'This versatile program can accept .xls or .xlsx files as '...
# -*- coding: utf-8 -*- from loguru import logger from machine.message import Message from machine.plugins.base import MachineBasePlugin from machine.plugins.decorators import listen_to, respond_to class PingPongPlugin(MachineBasePlugin): """Playing Ping Pong""" @respond_to(r"^ping$") @listen_to(r"^pin...
import pandas as pd import numpy as np import pandas_datareader.data as web import datetime import matplotlib.pyplot as plt import json from fbprophet import Prophet plt.rcParams['figure.figsize']=(20,10) plt.style.use('ggplot') #function to get stock data def iex_stocks(symbol, start, end): return web.DataReader...
from . import utils import functools import werkzeug.wrappers.response # noqa: F401 @functools.lru_cache(maxsize=None) def handler(): ''' Get a list of available simulation tools and their versions. Returns: :obj:`werkzeug.wrappers.response.Response`: response which contains a list of el...
#!/usr/bin/python3 # coding : utf-8 import logging def read(file): with open(file, 'rb') as file: fileRead = file.read() logging.debug('\n===READ FILE===\n%s\n===============', fileRead) return fileRead def write(data, file): with open(file, 'wb') as file: logging.debug('...
import pandas as pd from PIL import Image import requests from io import BytesIO import os import math df = pd.read_csv('MetArtworksAugmented.csv') size = 192, 192 def make_thumbnail(objectID, url): try: response = requests.get(url) image = Image.open(BytesIO(response.content)) image.thumb...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. from typing import Tuple, Union import torch.nn as nn from pytorchvideo.accelerator.efficient_blocks.efficient_block_base import ( EfficientBlockBase, ) from pytorchvideo.accelerator.efficient_blocks.no_op_convert_block import ( NoOpConve...
# -*- coding: utf-8 -*- '''数据库调用入口''' import sys from sqlalchemy import MetaData from flask_sqlalchemy import SQLAlchemy as SQLAlchemyOriginal # refer: http://flask-sqlalchemy.pocoo.org/2.3/config/#using-custom-metadata-and-naming-conventions convention = { "ix": 'ix_%(column_0_label)s', "uq": "uq_%(table_na...
# @Title: 查找常用字符 (Find Common Characters) # @Author: Singularity0909 # @Date: 2020-10-15 20:23:38 # @Runtime: 48 ms # @Memory: 13.7 MB class Solution: def commonChars(self, A: List[str]) -> List[str]: ans = '' for c in set(A[0]): v = min([s.count(c) for s in A]) ans = ans +...
# coding: utf-8 import psutil import time import os import re import math import json import sys from flask import Flask, session from flask import request import db import common import requests import config_api from threading import Thread from time import sleep reload(sys) sys.setdefaul...
# Solution of; # Project Euler Problem 313: Sliding game # https://projecteuler.net/problem=313 # # In a sliding game a counter may slide horizontally or vertically into an # empty space. The objective of the game is to move the red counter from the # top left corner of a grid to the bottom right corner; the space a...
#!/usr/bin/env python # coding=utf-8 # Copyright © 2017 ButenkoMS. All rights reserved. Contacts: <gtalk@butenkoms.space> # # 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...
from flask import Flask, request, render_template from src.data import get_data app = Flask(__name__) @app.route("/sobre") def sobre(): return """<h1>Sobre</h1> <p>O Painel CVM é um projeto open-source que resolve uma dor de cabeça para quem cobre mercado financeiro: a imensa quantidade <br>de com...
from django.db.models.signals import post_save from django.dispatch import receiver from social.models import TemuUser, Relationship import logging logger = logging.getLogger(__name__) @receiver(post_save, sender=TemuUser, dispatch_uid="create_user_relationship") def user_relationship_handler(sender, instance, cre...
"""NBT Instructions""" from ._core import (ConstructorInsn, CompileTimeInsn, SingleCommandInsn, RuntimeHeldInsn, READ, WRITE) from ..core_types import (VirtualString, MutableString, Opt, BlockRef, ...
import tensorflow as tf from tensorflow.keras import layers, initializers, optimizers from tensorflow.python.keras.layers.advanced_activations import LeakyReLU #gaussian0_1 = initializers.RandomNormal(mean=0.0, stddev=0.1, seed=None) def build_model(): model = tf.keras.Sequential() model.add(layers.Conv2D(96,...
import os import numpy as np import folium from folium.plugins import MarkerCluster from PySide2 import QtCore, QtGui, QtWidgets from matplotlib.colors import LinearSegmentedColormap import matplotlib.pyplot as plt import matplotlib.cm as mplcm import matplotlib.colors as colors from GridCal.Engine.Core.multi_circuit...
import random import string import json import os KEYS_FILE = os.path.join(os.path.dirname(os.path.realpath(__file__)), "project", "keys_file.json") def get_random_alphanumeric_string(length): letters_and_digits = string.ascii_letters + string.digits result_str = ''.join((random.choice(letters_and_digits) for...
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from einops import repeat from .network import Network class Diffusion(nn.Module): def __init__(self, *args, **kwargs): super().__init__() self.network = Network(*args, **kwargs) @property def device(s...
#pylint: disable=C0103,R0904,R0903,W0201 """ This module demonstrates a possible problem of pyLint with calling __init__ s from inherited classes. Initializations done there are not considered, which results in Error E0203 for self.cookedq. """ __revision__ = 'yo' import telnetlib class SeeTelnet(telnetlib.Telnet): ...
# AARD: function: __main__ # AARD: #1:1 -> #1:2 :: defs: %1 / uses: [@1 4:1-4:6] n = 3 # AARD: #1:2 -> #1:3 :: defs: %2 / uses: %1 [@1 8:6-8:14] { call } # AARD: #1:3 -> #1:4 :: defs: %3 / uses: %2 [@1 8:1-8:14] it = range(n) # AARD: #1:4 -> #1:5, #1:6 :: defs: %4 / uses: %3 [@1 11:5-11:6] for i in it: ...
import matplotlib.pyplot as plt import numpy as np plt.rc('text', usetex=True) plt.rc('font', family='serif') n_t_s = [12.0147179299, 11.9929383362, 11.9632573566, 11.9675865273, 11.9218409371, 11.9574648468, 11.9012440325, 11.9255544399, 11.9439799143, 11.8872206155, 11.8841705191, 11.8525295094, 11.8478403556...
__author__ = 'james'
from flask import flash, redirect, render_template, url_for from flask_login import current_user, login_required, login_user, logout_user from app import app, db from app.forms import LoginForm, RegisterForm from app.models import User @app.route('/index') @login_required def index(): posts = [] return rende...
import pandas as pd import datetime as dt def prompt_office(): path = "sdr_availability/data/" file = "hr.csv" hr_list = pd.read_csv(path + file) offices = pd.DataFrame(hr_list['Office'].unique()) offices.columns = ['Office'] tries = 3 officeOptions = "" officeIndex = list(offices.ind...
from setuptools import setup import re with open('webviewcamera/__init__.py', 'r') as f: version = re.search(r"__version__ = '(.*)'", f.read()).group(1) with open('README.rst', 'r') as f: readme = f.read() setup( name='WebViewCamera', version=version, description='Access and control Canon WebView...
ssb_sequence = Sequence(name='ssb', variable=' diff down from f0', variable_unit='GHz', step=1e6, start=0, stop=100e6) qubit_time = 1e-6 qubit_points = round(qubit_time / resolution) qubit_time_array = np...
""" Bumpversion and generate a changelog straight from your git commits. Usage: git-releaser [options] options: -r --repo [default:os.getcwd()] Path to the repository's root directory -h --help Print this help text -p --promote [default:patch] Major,minor or p...
import json import torch import pandas as pd from pathlib import Path from itertools import repeat from collections import OrderedDict import os import pickle from tqdm import tqdm from PIL import Image import numpy as np import logging from scipy.io import loadmat from datetime import datetime def read_pickle(pickle...
from django.db import models # Create your models here. class UspsServices (models.Model): # id : int serviceName = models.CharField(max_length=1000) serviceDescription = models.TextField() accessFlag = models.BooleanField(default=False)
## Sid Meier's Civilization 4 ## Copyright Firaxis Games 2005 from CvPythonExtensions import * import PyHelpers import CvUtil import ScreenInput import CvScreenEnums import string PyPlayer = PyHelpers.PyPlayer PyInfo = PyHelpers.PyInfo # globals gc = CyGlobalContext() ArtFileMgr = CyArtFileMgr() localText = CyTransla...
from model.contact import Contact from model.group import Group from random import randrange #Меняем все свойства первой группы def test_edit_group(app): if app.group.count() == 0: app.group.create(Group(name="Dog", header="big_dog", footer="little_dog")) old_groups = app.group.get_group_list() ind...
# Copyright 2020 The TensorFlow 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 applica...
import os from Crypto.Cipher import AES from Crypto.Util.Padding import pad, unpad from Sakurajima.utils.merger import ChunkMerger, FFmpegMerger, ChunkRemover from threading import Thread, Lock from progress.bar import IncrementalBar from Sakurajima.utils.progress_tracker import ProgressTracker from Sakurajima.utils.de...
import requests import datetime import discord import asyncio import random import logging import os.path import nekos import hentai from hentai import Hentai import json from hentai import Format from urllib.parse import urlparse from os.path import splitext import random from discord.ext import command...
# terrascript/provider/heroku.py # Automatically generated by tools/makecode.py (24-Sep-2021 15:18:37 UTC) # # For imports without namespace, e.g. # # >>> import terrascript.provider.heroku # # instead of # # >>> import terrascript.provider.heroku.heroku # # This is only available for 'official' and 'partner' provi...
#!/usr/bin/python from optparse import OptionParser from jinja2 import Template from subprocess import call from tempfile import mkstemp import os import ast import itertools from datetime import date, timedelta, datetime import glob import csv import numpy import json from lxml import etree import math parser = Opti...
import numpy as np from dask.distributed import Client from functools import partial, reduce from itertools import product from math import ceil, floor, log10 import operator import sys import time def matrix_to_valuelist(mat): return mat.flatten(order="c") def axes_to_list(x, y): return np.vstack( ...
import src.model.pattern as pattern from src.util import CompilationError # object containing other top-level forms... class Module: def __init__(self, tlforms): self.tlforms = tlforms def __repr__(self): out = [] for form in self.tlforms: out.append(repr(form)) ret...
from .riposte import Riposte # noqa
import uuid from django.contrib.postgres.fields import ArrayField from django.db import models from accounts.models import UserProfile from jobs.choices import APPLICATION_STATUS_CHOICES from .job import Job class Application(models.Model): slug = models.SlugField(unique=True, default=uuid.uuid1, blank=True) ...
# -*- coding: utf-8 -*- """ Created on Sat Mar 9 22:27:31 2019 @author: Philip """ import os import pandas as pd import numpy as np import time from time import gmtime, strftime import json import pickle import copy from MultiWG.WG_Dictionary import Setting_template pd.options.mode.chained_assignment = None # defau...
from cStringIO import StringIO import os import random import numpy as np import PIL.Image import pencroft class PencroftLoader(object): """Opens SOURCE with pencroft. SOURCE is interpreted as folders named for classes containing images for the class. For documentation about this data format: https...
# # This file is part of pretix (Community Edition). # # Copyright (C) 2014-2020 Raphael Michel and contributors # Copyright (C) 2020-2021 rami.io GmbH and contributors # # This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General # Public License as published by ...
import paths import os import SimpleITK as sitk import numpy as np heatmaps_dir = os.path.join('.', 'heatmaps') if not os.path.exists(heatmaps_dir): os.mkdir(heatmaps_dir) seg_name = 'seg_MNI152_1mm' seg_filepaths = [os.path.join(root, name) for root, dirs, files in os.walk(paths.brats2018_training_path) \ for na...
#!/usr/bin/env python # # Copyright 2016 the original author or authors. # # 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 require...
import code, string import DebugCommands g_commandDict = {'r':DebugCommands.RUN, 'run':DebugCommands.RUN, 'q':DebugCommands.QUIT, 'quit':DebugCommands.QUIT, 't':DebugCommands.TEMPLATE, 'template':DebugCommands.TEMPLATE, ...
from dataclasses import dataclass class Margin: block: property block_start: property block_end: property top: property right: property bottom: property left: property class Scroll(Margin): behavior: type margin: type # scroll-margin-inline # scroll-margin-inline-end # scroll-...
from pymongo import MongoClient def displayGroup(results): for result in results: print (result) def firstIsALastIsVowel(collection): key = {'first' : True, "last" : True} cond = {'first' : 'a', 'last' : {'$in' : ["a","e","i","o","u"]}} initial = {'count' : 0} red...
class Task: """ Task are data-type for handle execution of functions (in lazy way) transform results of this function and handle errors. """ def __init__(self, fork): """ :param fork: function to call during fork :type fork: Function(reject, resolve) -> Any """ ...
#------------------------------------------------------------------------------- # Name: version probe # Purpose: platform testing # # Author: Matthias Mueller # # Created: 11.06.2012 # Copyright: (c) Matthias Mueller 2012 # Licence: <your licence> #-----------------------------------...
load("@bazel_skylib//:lib.bzl", "shell") def _asciidoc_impl(ctx): asciidoc = ctx.toolchains["//tools/build_rules/external_tools:external_tools_toolchain_type"].asciidoc args = ["--backend", "html", "--no-header-footer"] for key, value in ctx.attr.attrs.items(): if value: args += ["--att...
from distutils import log from weaverbird.backends.sql_translator.steps.utils.query_transformation import ( apply_condition, build_selection_query, ) from weaverbird.backends.sql_translator.types import ( SQLDialect, SQLPipelineTranslator, SQLQuery, SQLQueryDescriber, SQLQueryExecutor, ...
import os import time import re from tile import Tile from pprint import pprint as pp INPUT_FILE = "input/data.txt" SAMPLE_INPUT_FILE = "input/sample_data.txt" def main(): # get absolute path where script lives script_dir = os.path.dirname(__file__) print("Script location: " + script_dir) # path of ...
# Given a string s, find and return the first instance of a non-repeating character in it. If there is no such character, return '_' # function only iterates over the string once and uses O(1) additional memory # input string contains only lowercase English letters def first_non_repeating_character(s): chars_in_str =...
""" A3A_Logster """ __version__ = "0.1" import os from importlib.metadata import metadata MAIN_DIR = os.path.abspath(os.path.dirname(__file__)) if os.path.islink(MAIN_DIR) is True: MAIN_DIR = os.readlink(MAIN_DIR).replace('\\\\?\\', '') def set_env(): """ Sets some enviroment variables to be availabl...
import crispy.modules import logging import pkgutil import textwrap import threading logger = logging.getLogger(__name__) from .. network.server_type import RPyCServer from .. network.service import CrispyService from . client import CrispyClient from .. lib.fprint import * class CrispyServer(threading.Thread): ...
# Copyright (c) 2013 Mirantis, 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...
import uuid from . import settings import os import datetime async def get_file_info(file, project_id): file_id = str(uuid.uuid4()) + "&" + project_id file_path = os.path.join( settings.MEDIA_ROOT, project_id, str(datetime.datetime.utcnow().date()), file_id + "." + file.filenam...