content stringlengths 5 1.05M |
|---|
from django.views.generic import ListView, CreateView, UpdateView
from django.utils.decorators import method_decorator
from django.contrib.admin.views.decorators import staff_member_required
from django.shortcuts import get_object_or_404, redirect, reverse,render
from django.urls import reverse_lazy
from django.contrib... |
# Example taken from https://keras.io/getting-started/sequential-model-guide/#examples
import sys
sys.path.insert(0, '../..')
from reloading import reloading
import keras
from keras import backend as K
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.optimizers import SGD
from ... |
# coding: utf-8
import unittest
from problems.univalued_binary_tree import Solution
from problems.utils.leetcode import deserialize_tree_str
class TestCase(unittest.TestCase):
def setUp(self):
self.solution = Solution()
def test(self):
test_data = [
{'tree_str': '[1,1,1,1,1,null,... |
import os
import pandas as pd
from sklearn.svm import LinearSVC
import bacpacs
import util
def run_cli(args):
wd = args.working_directory
bp = bacpacs.Bacpacs(wd)
if args.mode == 'merge':
bp.merge_genome_files()
elif args.mode == 'reduce':
pass
elif args.mode == 'create_pfs':
... |
#!/usr/bin/env python3
# -*-
"""
class Mysql to manage de db access for the programm analog-mesure-on-digital-pin
"""
import socket
import sys
import tkinter as tk
import mysql.connector
class Mysql_amod:
def __init__(self, ip_db_server):
# version infos
VERSION_NO = "0.01.01"
... |
SA, PA, XA = input().split()
SB, PB, XB = input().split()
PA = int(PA)
PB = int(PB)
if PA > PB:
print(SA)
elif PA < PB:
print(SB)
elif PA == PB:
print(-1)
|
class Solution:
def intToRoman(self, num: int) -> str:
int2RomanMap = {1 : "I", 5 : "V",
10: "X", 50: "L",
100 : "C", 500 : "D",
1000 : "M",
4: "IV", 9: "IX",
40: "XL", 90: "XC",
... |
import pandas as pd
from pymatgen.core import Composition
binaries = pd.read_csv('binary_band_gap.csv')
# We create a column holding the Composition object.
# Note the use of list comprehension in Python.
binaries['composition'] = [Composition(c) for c in binaries['Formula']]
electronegs = [[el.X for el in c] for c in... |
from src.services.monolithic.services import default_ticker
class TempMonitor:
def __init__(self, temperature_sensor):
self.temperature_sensor = temperature_sensor
self.temperature_changed_listeners = []
self.last_temp = None # any real temperature should be different
@default_tic... |
"""Const for Twinkly."""
DOMAIN = "twinkly"
# Keys of the config entry
CONF_ENTRY_ID = "id"
CONF_ENTRY_HOST = "host"
CONF_ENTRY_NAME = "name"
CONF_ENTRY_MODEL = "model"
# Strongly named HA attributes keys
ATTR_HOST = "host"
# Keys of attributes read from the get_device_info
DEV_ID = "uuid"
DEV_NAME = "device_name"
... |
import os.path
import shutil
import tarfile
from pathlib import Path
import pytest
from cleo import CommandTester
from devtools import debug
from autojail.extract import BoardInfoExtractor, DeviceTreeExtractor
from autojail.main import AutojailApp
test_data_folder = os.path.join(os.path.dirname(__file__), "test_data... |
from big_ol_pile_of_manim_imports import *
from scipy import signal as sp
def Range(in_val,end_val,step=1):
return list(np.arange(in_val,end_val+step,step))
class Anim_1_1(ThreeDScene):
def construct(self):
axis_config = {
"y_max" : 0,
"y_min" : 0.0001,
... |
from nider.core import Font
from nider.core import Outline
from nider.models import Content
from nider.models import Header
from nider.models import Image
# TODO: change this fontpath to the fontpath on your machine
roboto_font_folder = '/home/ovd/.local/share/fonts/Roboto/'
text_outline = Outline(1, '#efefef')
he... |
from typing import List
import numpy as np
import torch
def point_form(boxes: torch.Tensor) -> torch.Tensor:
"""Convert prior_boxes to (x_min, y_min, x_max, y_max) representation for comparison to point form ground truth data.
Args:
boxes: center-size default boxes from priorbox layers.
Return:
... |
#!/usr/bin/env python3
import pytest
import json
import re
import multiplex
class TestRequirements:
requirements_json = "requirements-pass.json"
req_presets_def_ess_empty = "requirements-presets-def-ess-empty.json"
req_presets_empty = "requirements-presets-empty-pass.json"
req_single_escape = "requir... |
from pathlib import Path
import logging
from typing import MutableMapping
import toml
logger = logging.getLogger(__name__)
class Configuration():
def __init__(self):
self.__config_file_path : str
self.__config : MutableMapping
def load(self, config_file_path: str = './config.toml'):
l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2019 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
"""
Stores configuration for git projects in a worktree
Delegates most of the work to :py:mod:`qisrc.git`` and
:py:mod:`qis... |
#!/usr/bin/env python3
from collections import defaultdict
import sys
import re
def extract(s):
return [int(x) for x in re.findall(r'-?\d+', s)]
def main(args):
data = [extract(s.strip()) for s in sys.stdin]
map = defaultdict(int)
doubled = 0
for _, x, y, l, w in data:
for i in range(l):... |
# Оберган Татьяна
# Программа засекает время пирамидальной сортировки (случайного, отсорт.,
# обратно отсорт. массивов по 3 заданным размерностям массивов.
from tkinter import *
from tkinter import messagebox
from time import time
from random import randint
# start_time = time()
ro... |
from django import forms
from maps.models import DataTable
#This class contains form fields like start, end, mode
class InputForm(forms.ModelForm):
MODE_CHOICES = [ ('DRIVING', 'DRIVING'), ('WALKING', 'WALKING')]
Start = forms.CharField(label='Start Location', max_length=100)
End = forms.CharField(label=... |
#!/usr/bin/env python
import logging
import ConfigParser
from exception import ConstructorError
from exception import OperationError
from util import Util
logger = Util.getLogger(__name__)
class Helper:
@classmethod
def createRpcMaster(self, cfgFile):
@classmethod
def loadConfig(self, cfgFile):
config = C... |
import dataclasses
from dis_snek.client import Snake
from dis_snek.models import Guild
from dis_snek.models import Member
from ElevatorBot.backendNetworking.http import BaseBackendConnection
from ElevatorBot.backendNetworking.results import BackendResult
from ElevatorBot.backendNetworking.routes import destiny_clan_g... |
# -*- coding: utf-8 -*-
#
# (C) 2013 Internet Initiative Japan Inc.
# All rights reserved.
#
# Created on 2011/01/27
# @author: yosinobu@iij.ad.jp
"""Provide list of Trac environment name."""
import dircache
import os
from trac.config import ListOption
from trac.core import *
from trac.env import open_environment
fro... |
# SDT3Parser.py
#
# Callback target class for the ElementTree parser to parse a SDT3
from .SDT3Classes import *
class SDT3Parser:
# Define the element tags of the SDT3
includeTag = 'include'
domainTag = 'domain'
importsTag = 'imports'
modulesTag = 'modules'
moduleClassTag = 'moduleclas... |
from django.contrib.auth.models import Group
from django.db import models
class ShibIgnoredGroupsMixin(models.Model):
shib_ignored_groups = models.ManyToManyField(
Group,
verbose_name='Shibboleth ignored groups',
blank=True,
help_text='Groups that Shibboleth will ignore when adjusting '
'this user\'s group... |
import json
import os
import argparse
import numpy as np
import oneflow as flow
import oneflow.nn as nn
import oneflow.optim as optim
from model.model import simple_CNN
from model.dataloader import create_batches_rnd
def get_args():
parser = argparse.ArgumentParser("""Speaker Identification Demo Train""")
p... |
import pyvisa as visa
import numpy as np
import json
import time
class HP34420A_HP34970A(object):
def __init__(self, spec):
rm = visa.ResourceManager()
self.spec = spec
self.hp420A = rm.open_resource(spec['port_bridge'])
self.hp970a = rm.open_resource(spec['port_scanner'])
def... |
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
"""Startup script to be used by VSCode.
VSCode does not support the concept of console scripts, or entry points:
https://python-packaging.readthedocs.io/en/latest/command-line-scripts.html#the-console-scripts-entry-point
This file is a copy of the actual implementation... |
import pybullet_envs
from stable_baselines3 import TD3_PER
model = TD3_PER('MlpPolicy', 'HumanoidBulletEnv-v0', verbose=1, tensorboard_log="results/long_TD3_PER_HumanoidBullet/")
model.learn(total_timesteps=3000000)
|
# import modules
import mcpi.minecraft as minecraft
import pibrella
from math import sqrt
from time import sleep
# connect python to minecraft
mc = minecraft.Minecraft.create()
# start program here
# hide the treasure
treas_x = 100
treas_y = 5
treas_z = 20
# main loop
while True:
# get player position
x, y, ... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from biostarPython.service import face_pb2 as face__pb2
class FaceStub(object):
# missing associated documentation comment in .proto file
pass
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Cha... |
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
from ipywidgets import (
interactive,
IntSlider,
widget,
FloatText,
FloatSlider,
ToggleButton,
VBox,
HBox,
Output,
interactive_output,
Layout,
FloatRangeSlider,
Checkbox,
)
de... |
""" Reusable boilerplate for widgets
"""
# pylint: disable=broad-except,no-member,too-few-public-methods
import ipywidgets as W
import traitlets as T
from ._version import module_name, module_version
class WXYZ_MODE:
"""locations of WXYZ execution
Should probably be an enum.
"""
kernel = "kernel"
... |
#!/bin/python3
import math
if __name__ == '__main__':
arr = []
for _ in range(6):
arr.append(list(map(int, input().rstrip().split())))
maxSum = - math.inf
for i in range(6):
for j in range(6):
if i < 4 and j < 4:
sum_ = (arr[i][j] + arr[i][j+1] + arr[... |
salario = float(input('\nDigite o seu salário: '))
if salario <= 1250:
aumento = 15/100*salario
print('Você terá um aumento de 15%. \nSalário atual: \33[1;33mR${:.2f}\33[m ' .format(salario+aumento))
else:
aumento = 10/100*salario
print('Você terá um aumento de 10%. \nSalário atual: \33[1;33mR${:.2f}\33... |
GENERAL_TYPE = ["thankyou", "greeting", "moreinfo", "goodbye", "book"]
INFORMABLE_TYPE = ['inform', 'switch_frame', 'confirm']
REQUESTABLE_TYPE= ['request', 'affirm', 'negate', 'request_alts', 'request_compare']
|
import rmsd
import numpy as np
from qml.data.alchemy import NUCLEAR_CHARGE
from qml.fchl import generate_representation
from qml.fchl import generate_displaced_representations
import wrapper
def main():
description = """
Based on a list of molecules, train a representation-set and alpha set.
Output the npy fil... |
'''OpenGL extension APPLE.float_pixels
This module customises the behaviour of the
OpenGL.raw.GL.APPLE.float_pixels to provide a more
Python-friendly API
Overview (from the spec)
This extensions adds texture types, texture internal formats and
color buffers composed of both 32 bit and 16 floating point... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on Aug 18, 2016
@author: Joerg Weingrill <jweingrill@aip.de>
'''
import os
import config
class WiFSIPPressure():
def __init__(self):
import matplotlib
matplotlib.use('Agg')
self.plotpath = config.plotpath
self.... |
#learned_societies.py
"""DEPRECATED
THIS MODULE COULD BECOME DESCRIPTION OF LEARNED SOCIETIES CLASS.
CURRENTLY GATHERED INFORMATION HAS TO BE STORRED SOMEWHERE. JSON?
Module dedicated to getting data about learned societies
The module is connecting to different websites that unite different
learned societies.
Current... |
from .eLABJournalObject import *
import graphviz
import requests
class ExperimentFile(eLABJournalObject):
def __init__(self, api, data, response):
"""
Internal use only: initialize f object
"""
if ((data is not None) & (type(data) == dict) &
("expJournalID" in data) &... |
import pandas as pd
import os
import re
from datetime import datetime
EV_PATTERN = re.compile('^ev_dump_.*\.csv$', re.IGNORECASE)
DEVICE_SCHEMA = {
'timestamp': 'str',
'device_id': 'str',
'event_type': 'str',
'event_payload': 'str'
}
def __clean_timestamp(rawValue:str) -> datetime:
try:
i... |
#!/usr/bin/env python
from distutils.core import setup
setup(name='pyeurofx',
version='0.6.4',
description='Python module to get and parse daily and historical FX rates from ECB',
long_description='Please visit https://github.com/supercoderz/pyeurofx for more details',
author='Narahari Allamraju',
auth... |
# -*- coding: utf-8 -*-
#from core.sockets.client import SocketClient
#from core.sockets.server import SocketServer
#from core.sockets.messages import Message
|
import os
import re
import git
import csv
import glob
import click
import shutil
import importlib
import proselint
from blessings import Terminal
CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])
# variables to hold error and warning count
err_cnt = 0
warn_cnt = 0
# list to hold check results
err_list = []... |
from django.db import models
from django.contrib.postgres import fields as postgres_fields
class Event(models.Model):
id = models.BigAutoField(primary_key=True)
data = postgres_fields.JSONField(default='{}')
created_at = models.DateTimeField(auto_now_add=True, db_index=True)
created_at_turn = mod... |
print isinstance(3,int)
print isinstance(3.1,float)
print isinstance(3,type(3))
print isinstance(3.1,type(3.1))
print isinstance("foo",str)
print isinstance("foo",type("foo"))
print isinstance([],list)
print isinstance([],type([1,2,3]))
print isinstance(None, type(None))
print isinstance(True, bool)
print isinstance(Tr... |
import time
import quasardb
import logging
import numpy as np
FIREHOSE_TABLE = "$qdb.firehose"
POLL_INTERVAL = 0.1
logger = logging.getLogger('quasardb.firehose')
def _init():
"""
Initialize our internal state.
"""
return {'last': None,
'seen': set()}
def _get_transactions_since(conn, ... |
from jira import TracJiraLink
|
# We use logical operators to form logic as the name suggests.\
# They operate against the boolean variables.
# They are: AND, OR and NOT
# AND: X and Y (If both are true)
# OR: X or Y (If anyone of them is true)
# NOT X: If X is not true.
x=20
y=30
# AND
print((x == 20 and y == 30)) # True
print((x == 25 and y == 30... |
# Copyright 2021 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, ... |
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/05_image_button.ipynb (unless otherwise specified).
__all__ = ['ImageButton']
# Internal Cell
from functools import partial
import base64
from pathlib import Path
from ipyevents import Event
from ipywidgets import Image, VBox, Layout, Output, HTML, Label
from traitlet... |
#!/usr/bin/env python3
"""
Author : Michael Son <mson0129@gmail.com>
Date : 2021-10-06
Purpose: Rock the Casbah
"""
import argparse
# --------------------------------------------------
def get_args():
"""Get command-line arguments"""
parser = argparse.ArgumentParser(
description='Gashlycrumb',
... |
# -*- coding: utf-8 -*-
################################################################################
# LexaLink Copyright information - do not remove this copyright notice
# Copyright (C) 2012
#
# Lexalink - a free social network and dating website platform for the Google App Engine.
#
# Original author: Alexan... |
import os
import re
import random
import pytube
import urllib.request
import moviepy.editor as mp # pip install moviepy
def removeDownloadFile(dir):
print("start delete")
for f in os.listdir(dir):
print("deleting file",f)
os.remove(os.path.join(dir, f))
dir = './videos' #direcctory where ... |
import os, sys
from loguru import logger
from core.plugins import import_modules, get_plugins
import_modules("modules")
from modules import Command
from core.bot import SedsBot
from core.env import SERVER, SERVER_PORT, ALLOWED_NICKS, BOT_NICKNAME, LOGFILE
if __name__ == "__main__":
logger.add(
sys.stdo... |
from .iotNode import IotNode
class IotBotHead(IotNode):
""" the base class for a robotic head with horizontal and/or vertical movements """
def __init__(self, name, parent, horizontalSteering, verticalSteering):
""" construct a head
name: the name of the node
parent: parent IotNode obj... |
"""
All location related functions and converters.
The main entry point is `location_processing` which gets `location` and
`source_ip_address` and basing on this information generates precise location
description.
[query] --> [location] --> [(lat,long)] -->
^
... |
# pylint: disable=invalid-name,arguments-differ,abstract-method
import numpy as np
from allennlp.common.testing import ModelTestCase
class TestBidirectionalLanguageModel(ModelTestCase):
def setUp(self):
super().setUp()
self.expected_embedding_shape = (2, 8, 14)
self.set_up_model(self.FIX... |
from mrf.mrfStructuresPara import *
###########################
##parallel implementation
###########################
class ParaPolysomeDetectionMRF(ParaMRF):
def __init__(self, G):
ParaMRF.__init__(self, G)
self._pathProb = np.ndarray((self._totalNodes, self._totalNodes))
... |
from django.apps import AppConfig
class AuthappConfig(AppConfig):
name = 'authapp'
|
# Generated by Django 3.2.7 on 2021-09-17 14:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('example', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='examplegdprmodel',
name='first_name',... |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
#
# File: learner.py
#
from copy import deepcopy
import numpy as np
import torch
from scipy.optimize import least_squares, minimize
from torch.autograd import backward
from torch.nn.utils import parameters_to_vector, vector_to_parameters
from ceem import utils
from ceem.opt_criteria import GroupCriterion, STRParamCr... |
from django.contrib import admin, messages
from .models import InputTemplate
from .service import InputTemplateService
@admin.register(InputTemplate)
class InputTemplateAdmin(admin.ModelAdmin):
list_display = ('id', 'code', 'name', 'filepath', 'owner',)
def generate_entity(self, request, queryset):
... |
# From https://github.com/wjh720/QPLEX/, added here for convenience.
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import pickle as pkl
class Qatten_Weight(nn.Module):
def __init__(self, args):
super(Qatten_Weight, self).__init__()
self.name = 'qatten... |
import os
from setuptools import find_packages, setup
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
with open('README.md') as f:
long_description = f.read()
setup(
name='mlmr',
packages=find_packages(),
version='1.0.0',
description='This library will help you easi... |
import numpy as np
import numba
import scipy.optimize as sopt
import json
sin = np.sin
cos = np.cos
atan2 = np.arctan2
sqrt = np.sqrt
sign = np.sign
exp = np.exp
class sys8bus2syn2cig_class:
def __init__(self):
self.t_end = 10.000000
self.Dt = 0.0010000
self.decimation = 10.000000... |
from . import const
from . import lib
from . import wrapper
from . import logger
from .wrappedfunction import WrappedFunction
from .event_bus_listener import EventBusListener
import HABApp.core.events
import HABApp.core.files
import HABApp.core.items
import HABApp.core.EventBus
import HABApp.core.Items
|
def lambda_handler(event, context):
print("event " + str(event))
print("context " + str(context))
ec2_reg = boto3.client('ec2')
regions = ec2_reg.describe_regions()
for region in regions['Regions']:
region_name = region['RegionName']
instances = Ec2Instances(region_name)
dele... |
import sys
import os
import csv
def get_orig_dicts(orig_filename):
orig = {}
orig_codes = {}
with open(orig_filename, newline='') as orig_file:
for line in orig_file:
line = line.rstrip()
if line != '':
code, play = line.split(': ')
orig[play... |
from abc import abstractmethod
from typing import Any, Dict
from datetime import datetime
from collections import defaultdict
from ..observer import Observer
from ...typedefs.enums import ExecutionState
class Notification(Observer):
def __init__(self, **kwargs: Any) -> None:
super().__init__(**kwargs)
... |
# -*- coding: utf-8 -*-
import click
from blink1.blink1 import blink1
@click.command()
@click.option('--color', default='white', help='What colour to set the Blink(1)')
@click.option('--fade', default=0.2, help='Fade time in seconds')
def shine(color, fade):
with blink1(switch_off=False) as b1:
b1.fade_to... |
#!/usr/bin/python3
## Required
## pip3 install feedparser
## pip3 install requests
import feedparser
import requests
import json
from datetime import datetime, timedelta
from time import mktime
from requests.auth import HTTPBasicAuth
#######################
# Config #
#######################
# Debug logg... |
"""This module contains the general information for AdaptorFcIfFrameStatsHist ManagedObject."""
from ...ucscmo import ManagedObject
from ...ucsccoremeta import UcscVersion, MoPropertyMeta, MoMeta
from ...ucscmeta import VersionMeta
class AdaptorFcIfFrameStatsHistConsts():
DUMPED_FRAMES_NA = "NA"
DUMPED_FRAME... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
## Our Project
# Project layout:
# proj/__init__.py
# /celery.py
# /tasks.py
# ---------------------------
# proj/celery.py
"""
from __future__ import absolute_import, unicode_literals
from celery import Celery
app = Celery('proj',
broker='amqp://',
... |
import time
import torch.nn as nn
import torch.nn.functional as F
import torch
from utils.logger import *
class AttnDecoderRNN(nn.Module):
def __init__(self, hidden_size, output_size, max_length, n_layers=1, dropout_p=0.1):
super(AttnDecoderRNN, self).__init__()
self.hidden_size = hidden_size * 2... |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... |
from floating_instance import FloatingInstance
from commonse.utilities import sectional2nodal
import numpy as np
class SparInstance(FloatingInstance):
def __init__(self):
super(SparInstance, self).__init__()
# Parameters beyond those in superclass
self.params['number_of_offset_columns'] =... |
# -*-coding: utf-8 -*-
"""
@Project: python-learning-notes
@File : acc.py
@Author : panjq
@E-mail : pan_jinquan@163.com
@Date : 2019-07-12 18:22:29
"""
import matplotlib
# matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
from sklearn import metrics
import numpy as np
def plot_acc_curv... |
# Examples from the README, which are also on the web page.
import iegenlib
S1 = iegenlib.Set("{[s,i]: 0<=s && s<T && 0<=i && i<N}")
print "S1 = ", S1
R1 = iegenlib.Relation("{[s,i]->[0,s,1,i,0]}")
print "R1 = ", R1
# The following Python statements are examples on how to apply operations
# (such as Apply, ... |
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
DATA_DIR = os.path.abspath(os.path.join(BASE_DIR, 'data'))
|
# -*- coding: utf-8 -*-
""" SRU: Search/Retrieval via URL APIクラス."""
import requests
from xml.etree import ElementTree
from .abs_api import AbstractAPI
class RecordData(object):
title = None
creator = None
description = None
publisher = None
language = None
def __init__(self):
pass
... |
import Adafruit_BBIO.GPIO as GPIO
import time
GPIO.setup("P9_41", GPIO.OUT)
while 1:
GPIO.output("P9_41", GPIO.HIGH)
time.sleep(1)
GPIO.output("P9_41", GPIO.LOW)
time.sleep(1)
GPIO.cleanup()
|
from typing import Any, Optional
from aether.ontology.base import Category, Relation
from aether.ontology.person import Person
class Student(Category):
pass
class School(Category):
pass
class Study(Relation):
def __init__(self, person: Person, subject: Optional[Any] = None):
self.person = pe... |
#!/usr/bin/env python
import os
from distutils.core import setup
setup(
name='pdfdocument',
version='3.2',
description='Programmatic wrapper around ReportLab.',
long_description=open(
os.path.join(os.path.dirname(__file__), 'README.rst')).read(),
author='Matthias Kestenholz',
author_ema... |
def timeline(ds):
ds.chart("Date:T", "Commits:Q")
ds.width(630)
ds.height(150)
ds.color("green")
ds.raencs()
c = ds.line_num_()
ds.timestamps("Date")
ds.drop_nan("Commits")
ds.lreg("Timestamps", "Commits")
ds.chart("Date:T", "Regression:Q")
ds.color("grey")
c1 = ds.line_(... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class NoisyLinear(nn.Module):
"""
Noisy weights in a linear layer from the NoisyNets paper
"""
def __init__(self, input_size, output_size, sigma_init=0.5):
"""
y = Wx+b, except each element of W and b ... |
import mxnet as mx
from typing import Union, Tuple, Optional, List
def argsort(x: mx.ndarray.ndarray.NDArray,
axis: int = -1,
descending: bool = False,
stable: bool = True)\
-> mx.ndarray.ndarray.NDArray:
return mx.nd.array(mx.nd.argsort(mx.nd.array(x), axis=axis, i... |
# -*- coding: utf-8 -*-
"""
単純な表形式のデータを展開するサンプルです。
掲載場所 https://www.data.go.jp/data/dataset/mof_20170208_0033/resource/23ec2641-a47d-4bb2-a5c0-f91368955855
データ https://www.houjin-bangou.nta.go.jp/setsumei/images/cities.pdf
"""
#%%
from logging import addLevelName
import os,sys
sys.path.append(os.path.join(os.path.dir... |
import abc
from collections import defaultdict
from typing import Dict, Iterator, List, Optional, Tuple, Type, Union
class CrossType(abc.ABC):
# which python typing module imports are needed
_pythonotherimports: Dict[str, List[Union[str, None]]]
def __init__(self) -> None:
self._pythonotherimport... |
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... |
# -*-coding:utf-8 -*
######################################################################################################################
# This file runs a set of Riemann problems for the one dimensional Euler equations with stiffened gas equation of state.
# It uses the class exact_rs_stiffenedgas to compute t... |
################################################################################
"""
`electricpy.capacitor` Package - Capacitor Specific Methods.
Filled with methods related capacitors.
"""
################################################################################
import numpy as _np
def vcapdischarge(t, Vs, R, ... |
from typing import cast, Any, Dict, TypeVar
T = TypeVar("T")
def merge_kwargs(base_dict: T, **kwargs: Any) -> T:
"""Return arbitrary typed dictionary with some keyword args merged in."""
return cast(T, {**cast(Dict, base_dict), **kwargs})
|
# Generated by Django 3.1.2 on 2020-10-22 15:25
import django.contrib.auth.validators
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0005_auto_20201022_2044'),
]
operations = [
migrations.AlterField(
model_name='cu... |
from allennlp.common.util import JsonDict
from allennlp.data import Instance
def get_fields_to_compare(
inputs: JsonDict, instance: Instance, input_field_to_attack: str
) -> JsonDict:
"""
Gets a list of the fields that should be checked for equality after an attack is performed.
# Parameters
inp... |
import socket
import asyncio
async def handle_request(client, loop):
await loop.sock_sendall(client, b"HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: 11\r\n\r\nhello world\r\n")
client.close()
async def run_server(loop):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
... |
"""
Copyright 2020 EUROCONTROL
==========================================
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.