content stringlengths 5 1.05M |
|---|
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
from django.db.models import Q
from ct.models import UnitStatus, Response, InquiryCount
from core.common.mongo import c_faq_data, c_chat_context
from .chat import get_lesson_url
class START(object):
"""
Initialize data for viewing a courselet, and go immediately
to first lesson (not yet completed).
... |
from __future__ import absolute_import, unicode_literals
import datetime
from decimal import Decimal
from time import sleep
import requests
from celery import shared_task
from django.contrib.auth import get_user_model
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
from d... |
import pandas as pd
from PIL import Image
import matplotlib.pyplot as plt
import doctest
from typing import Optional
import numpy as np
import math
def check_df_image_size(df: pd.DataFrame, target_column: str) -> None:
"""
Checks image sizes from Pandas DataFrame and adds two additional columns to it with siz... |
import radio
from microbit import *
# Set the queue length to 1 to ensure that the next message is the most recent
radio.on()
#radio.config(queue=1)
state = { 'a': False, 'b': False }
motors = { 'l': 0, 'r': 0 }
pin1.write_digital(0)
# Capacitor: 3.3uF, Resistor: 15kO (I think, could be 10kO)
# Signal resolution: 16,... |
import json
from django.db.models import CharField
from django.contrib.postgres.fields import JSONField
from model_utils.managers import InheritanceManager
from rest_framework.utils.encoders import JSONEncoder
from .graph import AbstractGraph
from .node import AbstractNode
from .edge import AbstractEdge
from .structure... |
from .propagation import UHECRPropagationResult, UHECRPropagationSolverBDF, UHECRPropagationSolverEULER |
import os
import numpy as np
import torch
from PIL import Image
import numpy as np
from torch.autograd import Variable
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import numpy as np
from warpctc_pytorch import CTCLoss
import os
os.chdir('../../')
from train.ocr.dataset impor... |
import delfi.distribution as dd
import delfi.generator as dg
import delfi.inference as infer
import delfi.utils.io as io
import delfi.summarystats as ds
#from delfi.kernel.Kernel_learning import kernel_opt
import numpy as np
import os
import scipy.misc
import sys
def run_smc(model, prior, summary, obs_stats,
... |
__all__ = ['TUPLE', 'LIST', 'DICT']
from .base import Head, heads_precedence
def init_module(m):
from .base import heads
for n,h in heads.iterNameValue(): setattr(m, n, h)
class ContainerHead(Head):
def data_to_str_and_precedence(self, cls, seq):
c_p = heads_precedence.COMMA
s_p = getat... |
#
# -*- coding: utf-8 -*-
#
# This file is part of reclass (http://github.com/madduck/reclass)
#
# Copyright © 2007–14 martin f. krafft <madduck@madduck.net>
# Released under the terms of the Artistic Licence 2.0
#
RECLASS_NAME = 'reclass'
DESCRIPTION = 'merge data by recursive descent down an ancestry hierarchy'
VERSI... |
import json
from channels.generic.websocket import WebsocketConsumer
from .Utils.general import is_valid_input_payload, str_bytes_to_pandas_df
from types import SimpleNamespace
from .MachineLearning.MachineLearning import HyperparameterTuning
class ComputationalNode(WebsocketConsumer):
def connect(self):
... |
'''
author: Wentao Hu(stevenhwt@gmail.com)
to do some addtional experiments
'''
import os
import time
random_seed=2
#experiment setting
mode="test"
#hyperparameter range
dim_range=[10]
dimension=dim_range[0]
lr_range=[0.0002] #initial learning rate
reg_range=[0.01]
#privacy setting
# #for dpmf method
strategy="min... |
import core.mcts_widening as mctswidening
import core.mcts as mctsnotwidening
class Trainer():
"""
Trainer class. Used for a given environment to perform training and validation steps.
"""
def __init__(self, environment, policy, replay_buffer, curriculum_scheduler, mcts_train_params,
m... |
# Generated by Django 3.1.12 on 2021-08-05 17:50
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("polio", "0020_fix_statuses"),
]
operations = [
migrations.RenameField(
model_name="campaign",
old_name="vials_requested",
... |
import tensorflow as tf
class VggBlockWithBN(tf.keras.layers.Layer):
def __init__(self, layers, filters, kernel_size, name, stride=1):
super(VggBlockWithBN, self).__init__()
self.kernel_size = kernel_size
self.filters = filters
self.stride = stride
self.layers = layers
... |
import functools
def try_except_missing_data_decorator_factory( job_name ):
def try_except_missing_data_decorator( func ):
@functools.wraps( func )
def try_except_missing_data_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except ValueError:
... |
from httpx import Response
import respx
mock_api = respx.mock(
assert_all_mocked=False, assert_all_called=False, base_url="http://api.vwa.com"
)
valid_collection = {
"info": {
"name": "invalid collection",
"_postman_id": "my-collection-id",
"schema": "https://schema.getpostman.com/#2.0.... |
import tensorflow as tf
import tensorflow.keras.layers as layers
from .transformer import VALID_CHARS
class InputLayer(layers.Layer):
def __init__(self, num_class, **kwargs):
super(InputLayer, self).__init__(**kwargs)
self.num_class = num_class
self.reshape_layer = layers.Reshape((-1... |
#!/usr/bin/python
# Copyright 2008 Jurko Gospodnetic
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
# Tests different aspects of Boost Builds automated testing support.
import BoostBuild
################################... |
#!/usr/bin/env python3
#=========================================================================
#
# Copyright (c) 2018 Karl T. Diedrich, PhD
#
# 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 Licen... |
import math
import torch.nn as nn
import torch
import torch.nn.functional as F
class HyperDecoder(nn.Module):
def __init__(self, input_dim, outputdim=None):
super(HyperDecoder, self).__init__()
self.input_dim = input_dim
self.fc1 = nn.Linear(input_dim, input_dim)
self.fc2 ... |
INITIATOR='INITIATOR'
PASSIVE='PASSIVE'
SATELITE='SATELITE'
PARTNER='PARTNER'
ORIGINATOR='ORIGINATOR'
ROLE='ROLE'
STATE='STATE'
MSGS="MESSAGES"
ASK_SWAP='ASK_SWAP'
WAIT_ASK_RESPONSE='WAIT_ASK_RESPONSE'
SEND_ACCEPT_SWAP='SEND_ACCEPT_SWAP'
SEND_TABLE='SEND_TABLE'
WAIT_LOCKS_UTABLE='WAIT_LOCKS_UTABLE'
PERFORM_SWAP='PER... |
"""
Creating an Image Dataset from Local PNGs/JPGs
There are two ways two create a data of PNGs/JPGs depending on whether the images are
stored locally on your computer or at a publicly accessible URL. The code snippet
below shows you what to do if the images are on your computer.
"""
from indico import IndicoClient... |
import web
from api import *
from errors import *
from models import Contact, Institution
logger = logging.getLogger(__name__)
class ContactController(object):
"""Handles contact queries"""
@json_response
def OPTIONS(self,name):
return
@json_response
@api_response
@check_token
de... |
from enum import Enum
class Routes(Enum):
HEALTH = ('/health', 'health')
GITHUB = ('/github', 'github')
REGISTER = ('/register', 'register')
STATUS = ('/status', 'status')
COMMENT = ('/comment', 'comment')
MISSING = ('/missing/{eventType}', 'missing')
DEREGISTER = ('/deregister', 'deregist... |
import logging
from concurrent import futures
import grpc
from ray import cloudpickle
import ray
import ray.state
import ray.core.generated.ray_client_pb2 as ray_client_pb2
import ray.core.generated.ray_client_pb2_grpc as ray_client_pb2_grpc
import time
import inspect
import json
from ray.experimental.client import sta... |
from apistar import App, ASyncApp
from apistar_autoapp import AutoApp, AutoASyncApp
from .app import test_from_app_file
def test_empty_autoApp():
app = AutoApp()
assert isinstance(app, App)
assert app.event_hooks == []
def test_empty_autoASyncApp():
app = AutoASyncApp()
assert isinstance(app, ... |
import math
import numpy as np
import matplotlib.pyplot as plt
def imag_residual_plot(f, res_imag_arr, fmt='.-', y_limits=(-5, 5)):
plt.plot(f, res_imag_arr * 100, fmt, label=r'$\Delta_{\,\mathrm{Re}}$')
# Make x axis log scale
plt.xscale('log')
# Set the labels to delta vs f
plt.xlabel('$f$ [Hz]... |
import json
import sqlite3
from typing import List
class SQLiteLoader():
"""Loads data from SQLite.
Loads data from SQLite, converts it and returns a list of dictionaries
for The dictionary list can be processed by PostgresSaver.
"""
SQL = """
WITH x as (
SELECT m.id, group_concat(a.... |
from setuptools import setup
setup(name='lcfcn',
version='0.6.0',
description='LCFCN',
url='git@github.com:ElementAI/LCFCN.git',
maintainer='Issam Laradji',
maintainer_email='issam.laradji@gmail.com',
license='MIT',
packages=['lcfcn'],
zip_safe=False,
install_requi... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab
import matplotlib
plt.style.use('ggplot')
from matplotlib.pyplot import figure
matplotlib.rcParams['figure.figsize'] = (12,8)
pd.options.mode.chai... |
from typing import List
import pytest
from great_expectations import DataContext
from great_expectations.core.batch import BatchRequest
from great_expectations.exceptions import ProfilerConfigurationError
from great_expectations.execution_engine.execution_engine import MetricDomainTypes
from great_expectations.rule_b... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from xml.sax import make_parser
from xml.sax.handler import ContentHandler
import sys
import smallsmilhandler
import json
import urllib.request
class KaraokeLocal():
def __init__(self, file):
parser = make_parser()
self.cHandler = smallsmilhandler.Small... |
from elasticapm.instrumentation.packages.base import AbstractInstrumentedModule
from elasticapm.traces import capture_span
class PyLibMcInstrumentation(AbstractInstrumentedModule):
name = "pylibmc"
instrument_list = [
("pylibmc", "Client.get"),
("pylibmc", "Client.get_multi"),
("pylib... |
"""DNS Authenticator for VitalQIP."""
import json
import logging
import requests
import zope.interface
from certbot import errors
from certbot import interfaces
from certbot.plugins import dns_common
from urllib.parse import urlparse
logger = logging.getLogger(__name__)
@zope.interface.implementer(interfaces.IAuth... |
def addAll(n1,n2):
result = 0
for i in range(n1,n2+1):
result += i
return result
print(addAll(1,10))
|
""" Tests web_automation.py. However, we have to use some of it's functions in order to test other functions. """
import pytest
from tenacity import retry, wait_fixed, stop_after_attempt
HOST = "http://localhost:5000"
DEFAULT_VALUE = "default value"
def verify(func, args, expected_result, wait_time=1, attempts=10):
... |
from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
urlpatterns = patterns('',
url(r'^$', TemplateView.as_view(template_name='chat.html'), name='home'),
)
|
import h5py
import numpy as np
from BaseInputProcessor import BaseInputProcessor
class FileInputProcessor(BaseInputProcessor):
def __init__(self, filename, mode=0):
self.filename = filename
h5file = h5py.File(self.filename, 'r')
var_list = []
for var, g in h5file.items():
... |
from jumpscale import j
import libvirt
from xml.etree import ElementTree
from JumpscaleLib.sal.kvm.BaseKVMComponent import BaseKVMComponent
import random
import re
class Interface(BaseKVMComponent):
"""
Object representation of xml portion of the interface in libvirt.
"""
@staticmethod
def genera... |
'''Desenvolva um programa que leia o primeiro termo de uma PA.
No final, mostre os 10 primeiros termos dessa progressão. obs: usando o while'''
primeiro = int(input(' Primeiro termo: '))
razão = int(input('Razão da PA: '))
termo = primeiro
cont = 1
while cont <= 10:
print(' {} -> '.format(termo), end='')
termo... |
import random
import tetris_blocks
class Randomblock:
def __init__(self):
number_of_possible_blocks = len(tetris_blocks.block_list)
self.maximum = number_of_possible_blocks - 1
def get_random_block(self):
re = random.randint(0, self.maximum)
return tetris_blocks.block_list[re]... |
# Copyright (c) OpenMMLab. All rights reserved.
from .base_tracker import BaseTracker
from .byte_tracker import ByteTracker
from .masktrack_rcnn_tracker import MaskTrackRCNNTracker
from .sort_tracker import SortTracker
from .tracktor_tracker import TracktorTracker
__all__ = [
'BaseTracker', 'TracktorTracker', 'Sor... |
# -*- coding: utf-8 -*-
""" Update an Attendify speakers XLSX file with the current list of
speakers.
Usage: manage.py attendify_speakers_xlsx ep2016 speakers.xlsx
Note that for Attendify you have to download the speakers before
running this script, since they add meta data to the downloaded
file ... |
import json
import urllib.parse
import urllib.request
from typing import Dict
from kenallclient.model import KenAllResult
class KenAllClient:
def __init__(self, api_key: str) -> None:
self.api_key = api_key
@property
def authorization(self) -> Dict[str, str]:
auth = {"Autho... |
# Parameters
MAX_SEQUENCE_LENGTH = 100
DENSE_UNITS = 100
CATEGORIES =3
EPOCHS = 1
BATCH_SIZE = 32
LEARNING_RATE = 0.0001 |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 2.0.10
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info
if version_info >= (2,6,0):
def swig_import_helper():
from os.path import... |
import itertools
BLANK = ''
class Tree(object):
def __init__(self, operator, operand):
self.operator = operator
self.operand = operand
self.parent = None
self.children = list()
def add_child(self, child):
child.parent = self
self.children.append(child)
de... |
#!/usr/bin/env python
# encoding: utf-8
#
# Copyright (c) 2013 Dariusz Dwornikowski. All rights reserved.
#
"""
Providing links to manpages with :linuxman: directiv
"""
from docutils import nodes, utils
from docutils.parsers.rst.roles import set_classes
from string import Template
import re
from sphinx.util import ... |
import numpy as np
import torch
from torch.distributions import Distribution as TorchDistribution
from torch.distributions import Normal as TorchNormal
from torch.distributions import Independent as TorchIndependent
from collections import OrderedDict
import lifelong_rl.torch.pytorch_util as ptu
from lifelong_rl.util... |
#!/usr/bin/python3
# Copyright 2020 Timothy Trippel
#
# 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 o... |
# Generated by Django 2.0.2 on 2018-11-15 02:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0003_auto_20181115_0802'),
]
operations = [
migrations.CreateModel(
name='beer',
fields=[
... |
#!/usr/bin/env python3
from argparse import ArgumentParser
from character import app
if __name__ == '__main__':
description = "Runs the Flask server."
parser = ArgumentParser(description=description)
parser.add_argument("-0", "--public", help="Makes the server world-"
"accessibl... |
#!/bin/env python3
"""
follow : @qywok_exploiter_357
"""
import unittest
class attributes:
def __init__(self):
self.decimal=[128,64,32,16,8,4,2,1]
self.bit=len(self.decimal) # length : 8 bit
class convert:
def __init__(self,value):
self.value=value
def bin2dec(self):
... |
import pandas as pd
import math
import QSTK.qstkutil.qsdateutil as du
import datetime as dt
import QSTK.qstkutil.DataAccess as da
import copy
import numpy as np
'''
import QSTK.qstkutil.tsutil as tsu
import QSTK.qstkstudy.EventProfiler as ep
import csv
'''
#import sys
from datetime import datetime, date
import matplo... |
"""
```nop``` command endpoints.
"""
from flask import Blueprint
from flask import make_response
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from app import irbox
from irbox.errors import IrboxError
nop_blueprint = Blueprint('nop_blueprint', __nam... |
# -*- coding: utf-8 -*-
try:
import pygame
except ImportError:
print("The pygame is not instaled")
from pygame.locals import *
from pygame.sprite import Sprite
from colors import *
# All classes of the game are here
class Characters(Sprite):
'''
Base class for all characters of the game
'''
... |
#! /usr/bin/env python
import sys, os, warnings
from pyorbit import Device
from pyorbit import ConnectError
from pyorbit.services import Status
# Example showing how to get the system uptime from an Orbit Radio.
# The uptime value is requested using it's keypath. The keypath
# can be obtained from the Orbit Radio co... |
import operator
from rtamt.spec.stl.visitor import STLVisitor
class STLCTOffline(STLVisitor):
def __init__(self, spec):
self.spec = spec
def offline(self, element, args):
sample = self.visit(element, args)
out_sample = self.spec.var_object_dict[self.spec.out_var]
if self.spec... |
import random
from musthe import Chord, Note, Interval
import ui
# Chord notation: https://en.m.wikipedia.org/wiki/Chord_notation
# https://en.m.wikipedia.org/wiki/List_of_chords
# --------------------------------
# CLASSES FOR chord types
# --------------------------------
# TRIADS
# ----------------... |
from pathlib import Path
root = Path(__file__).parent.absolute()
import envo
envo.add_source_roots([root])
from pathlib import Path
from typing import Any, Dict, List, Optional, Tuple
from envo import Env, Namespace, env_var, logger, run
from env_comm import StickybeakCommEnv as ParentEnv
p = Namespace("p")
cl... |
#!/usr/bin/env python
# Train Simulator
# hacked by Arno Puder, 4/2003
# modified by Haijie Xiao, 3/2004
from Tkinter import *
import thread, socket, sys, time, os, re, random
debug = 1
def usage ():
print 'usage: train.pyw [--layout1|--layout2]'
sys.exit (-1)
layout = 1
if len (sys.argv) > 1:
if len (... |
from __future__ import unicode_literals
from frappe import _
def get_data():
return[
{
"label": _("Google Data"),
"icon": "icon-cog",
"items": [
{
"type": "doctype",
"name": "Production Entry",
"onboard": 1,
"dependencies": [],
"description": _("Production Entry"),
},
... |
import sys
import pytest
import shutil
import pathlib
from squirrel.addon_sources.gumroad import GumroadProducts
@pytest.fixture
def download_folder():
folder = pathlib.Path('download_test')
if not folder.is_dir():
folder.mkdir(parents=True)
yield folder
shutil.rmtree(folder.as_posix())
@py... |
from unittest import mock
from lib_kafka import message_segmenter
import unittest
import uuid
import time
class TestMessageSegmenter(unittest.TestCase):
def test_segment_message(self):
msg = '0'*(1000*1024)
all_results = list(message_segmenter.segment_message(msg))
self.assertEqual(len(al... |
from typing import List
class Solution:
def maxProfit(self, prices: List[int]) -> int:
"""
:param prices:
:return:
"""
max_profit = 0
peak_value = valley_value = prices[0]
for price in prices:
if peak_value < price:
peak_value = p... |
# Copyright (c) 2019 NVIDIA Corporation
import unittest
from nemo.backends.pytorch.nm import TrainableNM
from .context import nemo
from .common_setup import NeMoUnitTest
class TestNM1(TrainableNM):
def __init__(self, var1, var2=2, var3=3, **kwargs):
super(TestNM1, self).__init__(**kwargs)
@staticmeth... |
import pandas as pd
import numpy as np
import cv2
import math
from PIL import Image
from sklearn.utils import shuffle
from scipy.ndimage import rotate
class AbstractPipeline(object):
def get_model(self):
raise NotImplementedError
def preprocess_image(self, image):
raise NotImplementedError... |
import time
from .base import TimeBased
from .base import TimeBasedUnsynced
class Countdown(TimeBasedUnsynced):
module = 'countdown'
time = 10
tick_rate = -0.01
auto_start = False
def check(self):
return self.status == "RUNNING" and self.time > 0
def timer_stopped(self)... |
import logging
import logging.config
class SpiderRecovery(object):
"""
爬虫的备份恢复类
"""
def __init__(self, isBackupToFile):
self.MODE_NEW = 1
self.MODE_OLD = 0
self.crashDate = None
self.usedData = set()
self.newData = set()
self.isBackupToFile = isBackupTo... |
from ionotomo.astro.real_data import DataPack
from ionotomo.plotting.plot_tools import plot_datapack
from ionotomo.inversion.initial_model import create_initial_model
from ionotomo.geometry.calc_rays import calc_rays
import numpy as np
import os
import logging as log
class Solver(object):
def __init__(self,datapac... |
import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib.patches import Polygon
from davg.lanefinding.ImgMgr import ImgMgr
from davg.lanefinding.BirdsEyeTransform import BirdsEyeTransform
def demonstrate_birdseye_reverse_usage():
img_mgr = ImgMgr(... |
# ROS stuff
import rospy
from urdf_parser_py.urdf import URDF
import yaml
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
import copy
import numpy as np
# KDL utilities
import PyKDL
from pykdl_utils.kdl_kinematics import KDLKinematics
from pykdl_... |
# -*- coding: utf-8 -*-
"""
This is parameter module for Averaged Neuron (AN) model.
These parameters are identical to those in Tatsuki et al., 2016
and Yoshida et al., 2018.
"""
__author__ = 'Fumiya Tatsuki, Kensuke Yoshida, Tetsuya Yamada, \
Takahiro Katsumata, Shoi Shi, Hiroki R. Ueda'
__status__ = '... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'slidecrop\resources\main.ui'
#
# Created by: PyQt5 UI code generator 5.12.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow)... |
def func(x, a=1, b=3):
return x + a - b
print func(2) # 0
print func(5, 2) # 4
print func(3, b=0) # 4
|
from unittest import TestCase
from unittest.mock import Mock, call, patch
from guet.commands import CommandMap
from guet.commands.help import UsageAction
class TestUsageAction(TestCase):
@patch('builtins.print')
def test_prints_all_descriptions_for_registered_commands(self, mock_print):
command_map ... |
# Copyright (C) 2012 Hewlett-Packard Development Company, L.P.
# 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/LICEN... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from math import sqrt
class point_analysis:
"""
analysis point
"""
def __init__(self, target_list, measure_list):
'''
initialize with target and measure data list
'''
self.target_list = target_list
self.measure_... |
"""This module provides the CLI entry point via main().
"""
__version__ = "0.1.0"
from .cli.cli import UppyylSimulatorCLI
def main():
"""The main function."""
prompt = UppyylSimulatorCLI()
prompt.cmdloop()
|
with open("input1.txt","r") as f:
data = f.readlines()
# Data Formats
# List of lines
# Lines are a list, size 2
# Line Format
# - Index 0 = Parent
# - Index 1 = Node
# Dict format:
# Key = Child Node
# Value = Parent Node
Dict = {}
# Loop over every piece of data
for line in data:
line = line.repla... |
import fnmatch
import os
from typing import List
def exist(file_path : str) -> bool:
return os.path.exists(file_path)
def not_exist(file_path : str) -> bool:
return not os.path.exists(file_path)
def is_dir(file_path : str) -> bool:
return os.path.isdir(file_path)
def is_file(file_path : str) -> bool:
... |
"""Container for DL-MONTE FED flavour option parameters
The class structure is:
FEDFlavour
Generic
PhaseSwitch
Each concrete class provides a class method from_string() method to
generate an instance from the appropriate DL CONTROL file entry,
while the __str__() method returns a valid string of the same form.
... |
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without eve... |
import dataclasses
import typing
from flask_sqlalchemy import BaseQuery
from sqlalchemy import func
from geoalchemy2 import Geometry
from airq.lib.clock import timestamp
from airq.lib.geo import haversine_distance
from airq.lib.readings import ConversionFactor
from airq.lib.readings import Pm25
from airq.lib.readings... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0007_auto_20151015_1938'),
]
operations = [
migrations.AlterField(
model_name='channel',
nam... |
import io
class IterStream(io.RawIOBase):
"""Wraps an iterator yielding bytes as a file object"""
def __init__(self, iterator):
self.iterator = iterator
self.leftover = None
def readable(self):
return True
# Python 3 requires only .readinto() method, it still uses other ones... |
from django.shortcuts import render
from django.contrib.auth.decorators import login_required
@login_required()
def index(request):
# GETアクセス時の処理
params = {
}
return render(request, 'home/index.htm', params)
|
import os
from typing import List
import difflib
from robot.api.parsing import (
ModelVisitor,
Token
)
from robot.parsing.model import Statement
from click import style
class StatementLinesCollector(ModelVisitor):
"""
Used to get writeable presentation of Robot Framework model.
"""
def __init... |
from kivy.uix.button import Button
class LanguageButton(Button):
pass
|
import os
from handcash_connect_sdk import HandcashCloudAccount, environments
def test_api_authorization():
auth_token = os.environ["HC_AUTH_TOKEN"]
handcash_cloud_account = HandcashCloudAccount.from_auth_token(auth_token, environments.PROD)
handcash_cloud_account.profile.get_current_profile()
|
from __future__ import print_function
from __future__ import division
import os
import codecs
import collections
from random import shuffle
import numpy as np
import pickle
class Vocab:
def __init__(self, token2index=None, index2token=None):
self._token2index = token2index or {}
self._index2tok... |
# -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import numpy as np
from glumpy import app, gl, glo... |
from discord.ext import commands
import discord, random, aiosqlite3
class Moderation(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command(help="a command to scan for malicious bots, specificially ones that only give you random invites and are fake(work in progress)")
async def s... |
from django.contrib import admin
from . import models
class DeviceAdmin(admin.ModelAdmin):
readonly_fields = ('id',)
admin.site.register(models.DeviceType)
admin.site.register(models.Device)
|
'''texto'''
frase = 'Curso em vídeo Python'
print(frase[9])
print(frase[:10])
print(frase[15:])
print(frase[9:13])
print(frase[9:21])
'''ele vai até o 20, mas não é mto recomendado'''
print(frase[9:21:2])
'''inicio, fim, salto -> v, d, o, P, t, o'''
print(frase[9::3])
'''tamanho do texto'''
print(len(frase))
'''conta... |
# Copyright 2019, OpenTelemetry 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 required by applicable law or agreed to i... |
# coding=utf-8
from OTLMOW.OTLModel.BaseClasses.OTLAttribuut import OTLAttribuut
from OTLMOW.OTLModel.Classes.AIMObject import AIMObject
from OTLMOW.OTLModel.Classes.Put import Put
from OTLMOW.OTLModel.Datatypes.KlPutMateriaal import KlPutMateriaal
from OTLMOW.GeometrieArtefact.VlakGeometrie import VlakGeometrie
# Ge... |
"""
This file demonstrates writing tests using the unittest module. These will pass
when you run "manage.py test".
Replace this with more appropriate tests for your application.
"""
from django.test import TestCase
from feedreader.models import Post
class PostContentTest(TestCase):
def test_relative_url(self):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.