content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
from reporter.core import SqlReport
from reporter.connections import get_redcap_link, RedcapInstance
from reporter.uhl_reports.civicrm import get_case_link
from reporter.emailing import (
RECIPIENT_IT_DWH
)
STUDY_NUMBERS_SQL = '''
WITH c (StudyNumber, civicrm_case_id, civicr... |
import subprocess
import progressbar
def cigntool_check_files(files):
print('--== PHASE 1 ==--')
print("Checking files for digital signature")
unver_files = []
vered = 0
f = 0
pb = progressbar.ProgressBar(maxval=len(files), widgets=[progressbar.Bar('=', '[', ']'), ' ', progressbar.SimpleProgr... |
"""
The ``asyncpg`` integration traces database requests made using connection
and cursor objects.
Enabling
~~~~~~~~
The integration is enabled automatically when using
:ref:`ddtrace-run<ddtracerun>` or :func:`patch_all()<ddtrace.patch_all>`.
Or use :func:`patch()<ddtrace.patch>` to manually enable the integration:... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("PAT")
process.MessageLogger = cms.Service(
"MessageLogger",
categories = cms.untracked.vstring('info', 'debug','cout')
)
process.options = cms.untracked.PSet(
Rethrow = cms.untracked.vstring('ProductNotFound')
)
# ... |
#!/usr/bin/env python
import unittest
from ternip.formats.gate import GateDocument
from ternip.timex import Timex
class GateDocumentTest(unittest.TestCase):
def test_get_sents(self):
t = GateDocument("""This POS B 20101010
is POS I
a POS I
sentence POS I
. . I
And POS B
a POS I
second POS I
sentence ... |
import csv
import logging
import os
import SimpleITK as sitk
import numpy as np
import radiomics
from radiomics import featureextractor
from filelock import FileLock
from scipy import ndimage
from random import randint
'''
This file contains functions which interact with the Pyradiomics library.
Frank te Nij... |
"""
This is a simple napari plugin for 3D-viewing of nifty files
(.nii.gz) - a common MRI file format.
"""
from napari_plugin_engine import napari_hook_implementation
@napari_hook_implementation
def napari_get_reader(path):
if isinstance(path, list):
path = path[0]
if not path.endswith(".nii.gz"):
... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import os
from ax.utils.common.testutils import TestCase
class InitTest(TestCase):
def testInitFiles(self) -> ... |
#! /usr/bin/env python3
# -*- coding:utf-8 -*-
###############################################################
# kenwaldek MIT-license
#
# Title: testing oled Version: 1.0
# Date: 29-01-2017 Language: python3
# Description: testing an oled display with i2c o... |
#!/bin/bash
#coding=utf8
def getSequenceLi():
li = []
li.append({'_id': 'pubDictionaryId', 'c': 100})
li.append({'_id': 'transactionsId', 'c': 100})
li.append({'_id': 'demoId', 'c': 100})
li.append({'_id': 'actionTestId', 'c': 100})
li.append({'_id': 'pubReferenceLogId', 'c': 100})
li.appen... |
"""
Function for encoding a rotational cipher (rot13),
also known as a Caesar cipher.
Args:
text: string of text to encoded
key: integer value for shifting Ciphertext
Returns:
encoded: the encoded text of the ciphers
Examples:
- ROT5 `omg` gives `trl`
- ROT... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# pyre-strict
"""
CLI for running a Private Attribute study
Usage:
pa-coordinator create_instance <instance_id> ... |
import datetime as dt
import logging
from typing import Union
logger = logging.getLogger(__name__)
def get_monday(date: Union[dt.date, dt.datetime]):
if isinstance(date, dt.datetime):
date = date.date()
return date - dt.timedelta(days=date.weekday())
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
def has_module(module):
try:
__import__(module)
return True
except ImportError:
pass
|
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from collections import defaultdict
from google.appengine.ext import ndb
from libs import time_util
from model.base_build_model import BaseBuildModel
from ... |
from __future__ import annotations
from abc import ABC
from typing import Callable, Dict, Iterable, Optional, Union
from datasets._typing import ColumnNames
from datasets.context import Context
from datasets.utils import _is_upper_pascal_case
from .mode import Mode
from .program_executor import ProgramExecutor
cla... |
import re, math
import pandas as pd
import gcsfs as gcsfs
def read_csv_gcs(filename , header=None):
# # read file from gcs
# fs = gcsfs.GCSFileSystem(project='careerograph-e9963')
# with fs.open(filename) as f:
# df = pd.read_csv(f,header=header)
# return df
return True
# performs preproces... |
import pandas as pd
import time
import math
import pdb
import os
import gc
class Logger:
def __init__(self):
self.d = []
self.num_rows = 0
def log(self, info):
self.d.append(info)
def save(self, path, append=True):
df = pd.DataFrame(self.d).apply(pd.to_numeric, errors='coerce', downcast='float')
df.in... |
"""Implementation of a stack."""
from linked_list import LinkedList
class Stack(object):
"""Class for a stack."""
def __init__(self, iterable=None):
"""Function to create an instance of a stack."""
self.length = 0
self._stack = LinkedList()
self.top = None
if isinstan... |
"""Implementation of the clear command."""
from mcipc.rcon.client import Client
__all__ = ['clear']
def clear(self: Client, player: str = None, item_name: str = None,
data: int = None, max_count: int = None) -> str:
"""Clears items from player inventory, including
items being dragged by the playe... |
default_app_config = 'event.providers.eventbrite_provider.apps.EventbriteProviderConfig'
|
# -*- coding: utf-8 -*-
name = 'colourise'
version = '0.4.0'
description = (
'If output to Terminal, colourise the piped input '
'text base off some rules.'
)
authors = ['WWFX UK']
# Technically needs bash. Tested rez on Linux and OSX CI with bash
requires = ['platform-linux|osx']
tools = ['colourise', 'c... |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Tag, Recipe
from recipe.serializers import TagSerializer
TAGS_URL = reverse('recipe:tag-list')
class ... |
"""
Question 67 :
Write a program using generator to print the numbers which can be
divisible by 5 and 7 between 0 and n in comma separated form while
n is console input.
Example : If the following n is input to the program : 100
Then, the output of the program should be : 0, 35, 70
Hints : U... |
import pybullet as p
import time
import math
import numpy as np
import random
p.connect(p.GUI)
p.loadURDF("plane.urdf",[0,0,-.2],globalScaling=6.0,useFixedBase=True)
cylId = p.loadURDF("simple_cylinder.urdf",[0,0,0.2],globalScaling=6.0,useFixedBase=False)
cubeId = p.loadURDF("cube.urdf",[2,2,0],globalScaling=0.6,useFi... |
#!/usr/bin/env python3
import asyncio
import time
import ipaddress
import random
import prime
def measure_time(func):
async def wrapper(*params):
start = time.monotonic()
res = await func(params)
end = time.monotonic()
duration = float(end - start)
return (res, duration)
... |
#UTF-8
def stoper(x_object, y_object, side, stop_kords=False):
if stop_kords != False:
stop = True
if side == 0:
for i in stop_kords:
temp = i.split(' ')
x1 = int(temp[0])
y1 = int(temp[1])
x2 = int(temp[2])
... |
from gmt import app, db
from flask import render_template, url_for, request, flash
import gmt
from gmt.models import Forename, Clan, Family, School, Samurai
from sqlalchemy.sql.expression import func
import random
@app.route('/')
@app.route('/home')
@app.route('/index')
def index():
return render_template("index.h... |
import os, logging
from rest_framework import generics
from rest_framework.permissions import AllowAny
from django.views.generic import View
from django.http import HttpResponse
from django.conf import settings
from .models import SimpleCV
from .serializers import SimpleCVSerializer
# Create your views here.
logger... |
from django.shortcuts import render, get_object_or_404
from .models import Kategor, Tovar, Tovar_inphoto, Tovar_img
from django.views.generic.edit import FormView
from django.contrib.auth.forms import UserCreationForm
from django.http import JsonResponse
from django.utils.http import is_safe_url
from django.contrib.aut... |
#
# Copyright (c) 2020 Expert System Iberia
#
"""Implements a factcheckability reviewer based on the ClaimBuster API
"""
def review(item, config):
"""Reviews the incoming item and returns
:param item: a single item or a list of items, in this case the
items must be `Sentence` instances.
:param con... |
#!/usr/bin/env spcli
from seqpy import cout, cerr
from seqpy.cmds import arg_parser
from seqpy.core.bioio import grpparser
from itertools import cycle, combinations
from matplotlib import pyplot as plt
try:
from matplotlib import pyplot as plt
import allel
except:
cexit('ERR: require properly installed ... |
"""
Another hexastore implementation.
An implementation of "Sextuple Indexing for Semantic Web Data Management"
from C. Weiss et al.. This is an implementation for fun only, hence may
be used if really needed, else it is adviced to use something more serious.
Example
-------
import hexastore
store = hexastore.Hexasto... |
"""
This module defines the sources of data used in the predictive analysis library.
User applicatios should import the factory method `get_data_source` in order to
instantiate the classes defined on this module.
"""
import numpy as np
from typing import List
from year_ap_predictive.library_types import SampleDataPo... |
"""This builds a GUI which can
a) load and show IMU data
b) apply an algorithm for stride segmentation and event detection
c) be used to manually add/delete/adapt labels for strides and/or activites.
isort:skip_file (Required import order: PySide2, pyqtgraph, mad_gui.*)
"""
import os
import sys
import warnings
from pa... |
from .WaveGrad2 import WaveGrad2
from .loss import WaveGrad2Loss
from .optimizer import ScheduledOptim |
"""
@file
@brief Ressource for backend
`lightbox2 <https://github.com/lokesh/lightbox2>`_ for directive *image*.
"""
|
import decimal
from refurbished.parser import Product
from app.adapters import apple, slack
from app.domain import commands, model
from app.services import messagebus
def test_available_products(
mocker,
messagebus: messagebus.MessageBus,
refurbished_adapter: apple.RefurbishedStoreAdapter,
slack_ada... |
import random
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Q
from django.shortcuts import render,get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.views import View
from django.view... |
import random
import math
import collections
from time import time
from itertools import compress
from bigchaindb.common import crypto, exceptions
from bigchaindb.common.util import gen_timestamp, serialize
from bigchaindb.common.transaction import TransactionLink, Metadata
import rethinkdb as r
import bigchaindb
f... |
from .baseclock import BaseClock
from beastling.util import xml
class RandomLocalClock(BaseClock):
__type__ = 'random'
def __init__(self, clock_config, global_config):
BaseClock.__init__(self, clock_config, global_config)
self.is_strict = False
self.correlated = clock_config.correlat... |
from zio import *
import sys,os,subprocess,time
'''
checksec --file domain_db
RELRO STACK CANARY NX PIE RPATH RUNPATH FILE
Partial RELRO Canary found NX enabled No PIE No RPATH No RUNPATH domain_db
note:
... |
#!/usr/bin/env python
# .. See the NOTICE file distributed with this work for additional information
# regarding copyright ownership.
# 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... |
lista = list()
while True:
lista.append(int (input ('Declare o número: ')))
while True:
fim = str (input ('Deseja continuar ? '.upper())).upper()[0]
if fim in 'SN':
break
if fim in 'N':
break
lista.sort(reverse=True) #Reverter os valores ordenados dentro da lista... |
from flask import Flask
app = Flask(__name__)
app.jinja_env.auto_reload = True
app.config['TEMPLATES_AUTO_RELOAD'] = True
# Set the secret key to some random bytes. Keep this really secret!
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
from app import routes |
class Solution(object):
# 递归+记忆化,k超大时做优化,退换为无限次买卖
def maxProfit(self, k, prices):
"""
:type k: int
:type prices: List[int]
:rtype: int
"""
if not prices or k<=0:
return 0
n = len(prices)
if k>n/2:
dp = [[0 for _ in xrange(2)] for _ in xrange(n)]
dp[0][0] = 0
dp[0][1] = -prices[0]
for... |
# -*- coding: utf-8 -*-
from .clone import CloneCommand
from .commit import CommitCommand
from .fetch import FetchCommand
from .init import InitCommand
__all__ = ["CloneCommand", "CommitCommand", "FetchCommand", "InitCommand"]
|
from provision.main import parse_args
from typing import Any, List
from azure import eventhub
from azure.cosmosdb import table
import logging
import json
import torch
import argparse
import os
import sys
def create_logger(log_level: int = logging.DEBUG) -> logging.Logger:
logger = logging.Logger(name="processor",... |
from pysdd.util import BitArray
import sys
import os
import logging
from pathlib import Path
logger = logging.getLogger("pysdd")
def test_bitarray1():
b = BitArray(10)
print(b)
assert b[4] is False
assert b[3] is False
assert b[2] is False
b[4] = 1
b[2] = True
print(b)
assert b[4]... |
import os
import sys
import time
import requests
import json
class MajPoll:
def __init__(self, question):
self.question = question
self.user_answers = { }
self.has_ended = False
def vote(self, answer, user):
if self.has_ended:
return # voting has concluded
... |
#!/usr/bin/python
import sys
import ZeroBorg
zb = ZeroBorg.ZeroBorg()
zb.Init()
zb.SetMotor1(0)
zb.SetMotor2(0)
zb.SetMotor3(0)
zb.SetMotor4(0)
|
import csv
import time
import re
status = False
user_name = ''
user_email = ''
user_password = ''
balance = -1
accFile = open('accounts.csv', 'r+')
ticketFile = open('tickets.csv', 'r+')
accReader = csv.reader(accFile)
ticketReader = csv.reader(ticketFile)
location_arg = open('frontend_locations.txt', 'r').readline(... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import re
import sys
from spack import *
class Curl(AutotoolsPackage):
"""cURL is an open source command line tool ... |
# Copyright (c) 2020 ruundii. All rights reserved.
import asyncio
import socket
import os
from typing import Awaitable, Callable, Dict, List, Optional, TYPE_CHECKING
from dasbus.connection import SystemMessageBus
if TYPE_CHECKING:
from hid_devices import HIDDeviceRegistry
OBJECT_MANAGER_INTERFACE = 'org.freedes... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
from django.apps import apps
from django.conf import settings
from django.template import loader
from django.utils.encoding import force_text
from django.utils.translation import activate, deactivate
from . import js_choices_settings as defau... |
'''
Copyright 2022 Airbus SAS
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, software
dis... |
from typing import Optional
import diskcache
import placekey.api
from ..utils.log import getLogger
from .common import CachedAPI, calculate_cache_key
logger = getLogger(__file__)
class PlacekeyAPI(CachedAPI):
"""API for calling placekey that checks the cache first"""
def __init__(self, api_cache: diskcach... |
from app.utils import exceptions
from app.utils import response_factory
from app.utils.constants import JWT_EXPIRATION_TIME
from app.utils import jwt_utils
from app.utils import decorators
|
from mrcp.panel import *
from mrcp.points import *
from mrcp.config import *
class Led(BaseElement):
def __init__(self, pos=Point(0, 0), color=LED_COLOR) -> None:
super().__init__(pos=pos, color=color)
def paint(self):
found = searchLed(self._panel, self._pos)
#print("Found", found, ... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
# Copyright (c) 2019 Thomas Howe
from typing import List, Union
from problem_sets.static.data import data_manager
from problem_sets.static.data.sqlite.test import sqlite_test_util
def clean_start(tables: Union[str, List[str]]):
sqlite_test_util.clean_start(tables)
data_manager.initialize() |
def limpar():
'''==>> Limpa o Terminal.'''
import os
os.system('cls') or None
def leiaInt(txt):
ok = False
valor = 0
while True:
num = input(txt)
if num.isnumeric():
valor = int(num)
ok = True
else:
print('\033[1;31mERRO. Digi... |
biscuits_per_worker = int(input())
workers = int(input())
competetor_biscuits = int(input())
production_for_month = 0
daily_production = biscuits_per_worker * workers
production_for_month += daily_production * 20
for i in range(0, 10):
production_for_month += int((biscuits_per_worker * workers) * 0.75)
print(f"Yo... |
#!/bin/python
import boto
from boto.sqs.message import RawMessage
import json
import os
import sys
data = {
"project": os.environ["CIRCLE_PROJECT_REPONAME"],
"sha": os.environ["CIRCLE_SHA1"][:7]
}
branch = os.environ["CIRCLE_BRANCH"]
if branch == "release":
queue_name = os.environ["SQS_NAME_PROD"]
elif br... |
#!/usr/bin/env python3
from csv import DictReader
def parse_weather(file_: str):
with open(file_, 'r') as f:
reader = DictReader(f)
for row in reader:
print(row['SiteName'],row['Temperature'],row['Weather'])
if __name__ == '__main__':
parse_weather('weather.csv')
|
################################ A Library of Functions ##################################
##################################################################################################
#simple function which displays a matrix
def matrixDisplay(M):
for i in range(len(M)):
for j in range(len... |
import os
class GetSensorTmp():
def __init__(self, sensorID):
self.sensorID = sensorID
self.sensorFile = '/sys/bus/w1/devices/{0}/w1_slave'.format(self.sensorID)
if os.path.isfile(self.sensorFile) == False :
raise IOError('sensor is not found.')
def get(self):
with op... |
""" Test for ESO GSP metadata """
import geopandas as gpd
import pandas as pd
import pytest
from nowcasting_dataset.data_sources.gsp.eso import (
get_gsp_metadata_from_eso,
get_gsp_shape_from_eso,
)
def test_get_gsp_metadata_from_eso():
"""
Test to get the gsp metadata from eso. This should take ~1 s... |
import sqlparser
from sqlparser import ENodeType
# Translates a node_type ID into a string
def translate_node_type(node_type):
for k,v in ENodeType.__dict__.iteritems():
if v == node_type:
return k
return None
# Print node and traverse recursively
def process_node(node, depth=0, name='roo... |
import configparser
import os
import unittest
import unittest.mock as mock
from requests import exceptions
from gras.github.github import GithubInterface
from gras.utils import to_iso_format
class TestGithubInterface(unittest.TestCase):
def setUp(self):
parser = configparser.ConfigParser()
parse... |
# -*- coding: utf-8 -*-
from __future__ import print_function, division
import math
import torch
from torch.nn import Module
from torch.nn.parameter import Parameter
from torch.nn.utils.rnn import PackedSequence
import torch.nn.functional as F
class LSTMHardSigmoid(Module):
def __init__(self, input_size, hidden_... |
"""properly named delivery_location_uuid and delivery_location on Task
Revision ID: 4d2f69dc0c76
Revises: 94bf8e9e0043
Create Date: 2021-01-31 15:06:43.998809
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = '4d2f69dc0c7... |
lineMessage = "Printing Entire File"
print(lineMessage)
print("-" * len(lineMessage))
with open('test.txt') as file_object:
#contents = file_object.readlines()
contents = file_object.read()
print(contents)
print("\n")
lineMessage = "Printing Entire File Line by Line"
print(lineMessage)
print("-" * len(line... |
# -*- coding: utf-8 -*-
# Copyright (c) 2020, Brandon Nielsen
# All rights reserved.
#
# This software may be modified and distributed under the terms
# of the BSD license. See the LICENSE file for details.
import datetime
import unittest
from aniso8601 import compat
from aniso8601.exceptions import (DayOutOfBounds... |
from rest_framework import viewsets
from rest_framework.permissions import IsAuthenticated
from unifier.apps.core.models import Platform
from unifier.apps.drf.v1.pagination import BasePagination
from unifier.apps.drf.v1.serializers import PlatformSerializer, PlatformSerializerDetail
class PlatformViewSet(viewsets.Rea... |
#
# This file is part of GreatFET
#
class DeviceNotFoundError(IOError):
""" Error indicating no GreatFET device was found. """
pass
class DeviceBusyError(IOError):
""" Error indicating the GreatFET is too busy to service the given request. """
pass
class DeviceMemoryError(MemoryError):
""" Erro... |
""""
StockReturns_perc and var_95 from the previous exercise is available in your workspace. Use this data to estimate the VaR for the USO oil ETF for 1 to 100 days from now.
We've also defined a function plot_var_scale() that plots the VaR for 1 to 100 days from now.
""""
def plot_var_scale():
# Plot the forecas... |
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('../TTWO_Fin_Data.csv', header=0, index_col=0, on_bad_lines="skip").transpose()
gtarev = data['Approx. $ Revenue From GTA in Quarter (derived from two rows above)'].str.replace(',', '').astype(float)
nongtarev = data['Approx. $ Revenue From Non-GTA... |
# -*- coding: utf-8 -*-
"""Module providing form utilities and partials"""
import uuid as uuid_tool
from Acquisition import aq_inner
from Products.Five import BrowserView
from plone import api
from plone.protect.utils import addTokenToUrl
class FormFieldBase(BrowserView):
""" Default widget view
Renders the ... |
# Copyright (C) 2017 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Test suite for DELETE requests."""
from integration.ggrc import TestCase
from integration.ggrc.query_helper import WithQueryApi
from integration.ggrc.models import factories
from integration.ggrc.api_hel... |
from deeprobust.image.defense.pgdtraining import PGDtraining
from deeprobust.image.attack.pgd import PGD
import torch
from torchvision import datasets, transforms
from deeprobust.image.netmodels.CNN import Net
from deeprobust.image.config import defense_params
"""
LOAD DATASETS
"""
train_loader = torch.utils.data.Da... |
"""
=======
License
=======
Copyright (c) 2014 Thomas Lehmann
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 u... |
#! /usr/bin/env python
import sys
speeds = dict()
# for the extension we will need another dictionary
# counts = dict()
for line in sys.stdin:
try:
line = line.strip()
station, speed = line.split('\t')
speed = float(speed)
# Add code here to use the data
except ValueError:
p... |
#!/usr/bin/env python
import numpy as np
import os, tempfile
import pickle
from pymvg.camera_model import CameraModel
from pymvg.util import point_msg_to_tuple, parse_rotation_msg
import pymvg.align as mcsc_align
from pymvg.test.utils import _build_test_camera, get_default_options
# --------------------- testing --... |
from sphinx.cmd.build import main
from typing import Dict
import pytest
import re
@pytest.mark.parametrize("test_input_repository_hosting_platform", ["GitHub", "GitLab"])
@pytest.mark.parametrize("test_input_project_name", ["A project", "Another project"])
@pytest.mark.parametrize("test_input_using_r", ["Yes", "No"])... |
# -*- coding: utf-8 -*-
# Copyright 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 requi... |
"""All-purpose utility file with helpers for
- PyTorch tensor processing (flattening, unflattening, vjp, jvp),
- plotting,
- custom gradient checking (gradient wrt parameters, and second-order gradients),
- meters (ema, online average),
- custom learning rate schedules,
- ema model averaging,
- google cloud storage ut... |
from telegram import Update
from telegram.ext import CallbackContext, CommandHandler
from bot.settings import settings
from bot.utils import get_log
from ._utils import require_owner
log = get_log(__name__)
@require_owner
def command(update: Update, context: CallbackContext):
log.debug('Taken command `setting... |
from telethon.errors.rpcerrorlist import BotInlineDisabledError as noinline
from telethon.errors.rpcerrorlist import YouBlockedUserError
from telethon.tl.functions.contacts import UnblockRequest
from userbot import BOT_USERNAME
from userbot import CMD_HANDLER as cmd
from userbot import bot
from userbot.utils import ed... |
##########DEPENDENCIES#############
from dronekit import connect, VehicleMode,LocationGlobalRelative,APIException
import time
import socket
#import exceptions
import math
import argparse
from pymavlink import mavutil
#########FUNCTIONS#################
def connectMyCopter():
parser = argparse.ArgumentParser(descrip... |
import pytest
from types import SimpleNamespace
from sovtoken.test.helpers.helper_inner_general import HelperInnerGeneral
from sovtoken.test.helpers.helper_inner_request import HelperInnerRequest
from sovtoken.test.helpers.helper_inner_wallet import HelperInnerWallet
from .helper_general import HelperGeneral
from .h... |
SLIP39_WORDS = [
"academic",
"acid",
"acne",
"acquire",
"acrobat",
"activity",
"actress",
"adapt",
"adequate",
"adjust",
"admit",
"adorn",
"adult",
"advance",
"advocate",
"afraid",
"again",
"agency",
"agree",
"aide",
"aircraft",
"ai... |
from django import forms
from django.conf import settings
from django.core.files.storage import default_storage as storage
import commonware.log
from tower import ugettext as _
from mkt.site.utils import slug_validator
from .models import BlockedSlug, Webapp
log = commonware.log.getLogger('z.addons')
def clean_s... |
import glob
from fnmatch import fnmatch
from functools import cached_property
from os import path
from typing import List
class FileTreeNode(object):
"""
本类用于识别Python文件结构。
获取文件树,并排除用户指定过滤的部分。
关于文件结构的过滤功能都写在了这个文件夹里,包括以下内容:
#. 对于非 ``python package`` 的部分全部跳过;
#. 跳过由 ``.`` 和 ``_`` 开... |
def make_full_name(given_name, family_name):
"""Return a string in this form "family_name; given_name".
For example, if this function were called like this:
make_full_name("Sally", "Brown"), it would return "Brown; Sally".
"""
full_name = f"{family_name};{given_name}"
return full_name
def extr... |
############################################################################
# Copyright 2015 Valerio Morsella #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may no... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import json
import urllib
import urllib2
from django.utils.translation import ugettext_lazy as _
from geopy import Nominatim
from geopy.exc import GeocoderTimedOut
class GeoLocator(object):
base_address_url = 'http://www.mapquestapi.com/geocoding/v... |
import json
from src.domain.text.caption import Caption
from src.domain.text.emphasis import Emphasis
from src.domain.text.properties import Properties
def test_caption_initializes():
caption = Caption(1, "start", "end", "test text", None)
assert caption.index == 1
assert caption.start == "start"
ass... |
'''题库的核心解释模块'''
import sys
import objects
import datetime #datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
from configuration import *
import os
from random import shuffle
class Application():
'''复习软件'''
def __init__(self):
# 题库文件
self.Qlibrary = {} # 题库{章节A:list(题目对象),章节B:...}
s... |
def init_actions_(service, args):
"""
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
return {
'test': ['install']
}
def test(job):
import sys
try:
log = j.l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.