content stringlengths 5 1.05M |
|---|
import unittest
import pymysql.cursors
# Not a Python dev, this is probably pretty ugly
class TestDjConventions(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.conn = pymysql.connect(
host="localhost",
user="user",
password="password",
db="heli... |
#!/usr/bin/env python
from saml2.saml import NAME_FORMAT_URI
__author__ = 'rolandh'
import json
BASE = "http://localhost:8088"
metadata = open("idp_test/idp.xml").read()
info = {
"entity_id": "%s/idp.xml" % BASE,
"interaction": [
{
"matches": {
"url": "%s/login" % BASE,
... |
import jieba
class TabooChineseChecker:
def __init__(self):
pass
def check(self, sent, word):
segmentation = list(jieba.cut(sent))
if word in segmentation:
return True
else:
return False
|
import csv
import os
from util.singleton import Singleton
class ThrottleFrame:
def __init__(self, time: float, distance: float, speed: float):
self.time = float(time)
self.distance = float(distance)
self.speed = float(speed)
def copy(self):
return ThrottleFrame(self.time, self.... |
"""
LocalStorage
------------
Simple local storage that create directories for packages and
put releases files in it.
"""
import os
import re
import io
import shutil
import pkginfo
from hashlib import md5
from .base import BaseStorage
class LocalStorage(BaseStorage):
NAME = 'LocalStorage'
def __init__(self... |
import abc
import time
class Question:
__metaclass__ = abc.ABCMeta
def __init__(self, name: str):
self.name = name
self.result = None
def __enter__(self):
self.start_time = time.time()
return self
def __exit__(self, *args):
self.end_time = time.time()
... |
#
# Copyright (C) 2013 eNovance SAS <[email protected]>
#
# Author: Frederic Lepied <[email protected]>
#
# 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.apa... |
# -*- coding: utf-8 -*-
import PyWMOFiles.Error
import PyWMOFiles.BUFR
|
"""Minimal example
Implement a equivariant polynomial to fit the tetris dataset
Exact equivariance to :math:`E(3)`
This example is minimal:
* there is dependency on the distance to the neighbors (tetris pieces are made of edges of length 1)
* there is no non-linearities except that the tensor product, therefore this... |
#!/usr/bin/env python3
import os
from typing import Optional
EON = os.path.isfile('/EON')
class Service:
def __init__(self, port: int, should_log: bool, frequency: float, decimation: Optional[int] = None):
self.port = port
self.should_log = should_log
self.frequency = frequency
self.decimation = dec... |
import sys
import matplotlib.pyplot as plt
import torch
from sklearn.decomposition import PCA
def main(model_filepath, input_filepath):
model = torch.load(model_filepath)
images, labels = torch.load(input_filepath)
print([10], "load")
with torch.no_grad():
model.eval()
k = 100
... |
import numpy as np
import math
def selfInductance():
firstAmp = float(input('First Amps: '))
firstrads = float(input('First Rads/second: '))
volt = float(input('Volts: '))
max = firstAmp * firstrads
Henry = (volt / max) * 1000
print(Henry)
print("mH")
selfInductance... |
from . import data
from . import models
from . import metrics
|
# proxy module
from __future__ import absolute_import
from codetools.blocks.compiler_.ast.ast import *
|
"""
"""
from __future__ import absolute_import
from qgis.PyQt.QtWidgets import QMenu, QMessageBox
from .environment import BASE_DIR
from .version import VERSION
#include here the new function for a connection with the menu
from .dikeline_export import DikelineExport
from .observationpoint_export import Ob... |
from app import app
from flask import request
from werkzeug import secure_filename
from os import path, remove as remove_file
from random import randrange
from time import time
from openpyxl import load_workbook
def allowed_ext(filename, allowed=[".xlsx"]):
# Extension
ext = path.splitext(filename)[1]
# E... |
# -*- coding: utf-8 -*-
from urllib.parse import urlparse
from django.contrib.auth import get_user_model
from django.shortcuts import resolve_url
from django.test import TestCase
class SetupTest(TestCase):
def test_initial_setup_redirect(self):
resp = self.client.get(resolve_url('login'))
self.as... |
import logs
import veri
def monitorStuff(Net):
Val = logs.peek(Net)
if Val!=0:
logs.log_error('PANIC activated on %s %s'%(Net,veri.peek(Net)))
return 1
return 0
def monitorStuffs():
panics=0
counts += monitorStuff("tb.dut.merger0.axi_rd_4_merger.a_rcount")
counts += monitorStu... |
#!/usr/bin/python3
from datetime import datetime
import sys
filename="shm-lolo-100-delay"
try:
if sys.argv[1]:
fileName = sys.argv[1]
except IndexError:
print("Using default file name.")
fileName = 'loglistener.txt'
f = open(fileName,"r")
total_count=0
ctr_count=0
RPL_count=0
data_count=0
for line in f:
... |
"""Top-level package for python_project_template."""
__author__ = """Mason Lin"""
__email__ = '[email protected]'
__version__ = '0.1.0'
|
# Write a method/function DISPLAYWORDS() in python to read lines from a text file STORY.TXT, and display those words, which are less than 4 characters.
def displayWords() :
file = open("story.txt", "r")
listObj = file.readlines()
for index in listObj :
word = index.split()
for search in wor... |
# Copyright (c) 2021 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 ap... |
# emacs: -*- mode: python-mode; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the NiBabel package for the
# copyright and license terms.
#
### ### ### #... |
from vvspy import get_trips
"""
Check connections between two stations and alarm on delay.
Note that there are destination.delay and origin.delay.
origin.delay => departure delay on first station
destination.delay => arrival delay on the final station
"""
station_1 = 5006118 # Stuttgart main station
station_2 = 5... |
import torch
import torchvision
import torch.nn as nn
import torch.nn.functional as F
class BnReluConv(nn.Module):
"""docstring for BnReluConv"""
def __init__(self, inChannels, outChannels, kernelSize = 1, stride = 1, padding = 0):
super(BnReluConv, self).__init__()
self.inChannels = inChannels
self.outChannel... |
# coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... |
"""
Better brain parcellations for Region of Interest analysis
"""
import numbers
import numpy as np
from scipy.ndimage import label
from scipy.stats import scoreatpercentile
from sklearn.externals.joblib import Memory
from .. import masking
from ..input_data import NiftiMapsMasker
from .._utils import check_niimg,... |
from django import forms
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin, PermissionRequiredMixin
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q
from django... |
import network
import time
import _thread
def connwifithread(ssid, clave):
nic = network.WLAN(network.STA_IF)
try:
nic.active(True)
except Exception as e:
print("No se pudo activar WiFi: "+str(e))
if nic.active():
print("WiFi activado")
while True:
if not... |
import time
def wait(sec):
time.sleep(sec)
while True:
wait(0.1)
print("----------")
wait(0.1)
print("*---------")
wait(0.1)
print("**--------")
wait(0.1)
print("***-------")
wait(0.1)
print("****------")
wait(0.1)
print("*****-----")
wait(0.1)
print("******... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import unittest
from pytext.config.doc_classification import ModelInput, ModelInputConfig
from pytext.config.field_config import FeatureConfig
from pytext.data import DocClassificationDataHandler, RawData
from pytext.data.fe... |
from werkzeug.utils import cached_property
from xml.etree.ElementTree import parse
from homebank.libraries.banking.account import Account
from homebank.libraries.banking.category import Category
from homebank.libraries.banking.payee import Payee
from homebank.libraries.banking.transaction import Transaction
class Ba... |
"""
This example shows how the Fisher statistics can be computed and displayed.
*Based on example 5.21 and example 5.23 in* [Fisher1993]_.
============= =========== ==========
Data in: Table B2 (page 279)
Mean Vector: 144.2/57.2 (page 130)
K-Value: 109 (page 130)
Fisher-Angle: 2.7 deg... |
abc = 'With three words or four'
stuff = abc.split()
print(stuff)
print(len(stuff))
print(stuff[1])
print('\n')
for i in stuff:
print(i)
line = 'A lot'
etc = line.split()
print(etc)
line = 'first;second;third;fourth'
thing = line.split()
print(thing)
print(len(thing))
thing = line.split(';')
print(thing)
print(len... |
import os
import sys
from unittest.mock import Mock
import pytest
from hg.gfx.sprite_renderer.sprite import Image
from hg.gfx.sprite_renderer.renderer import SpriteRenderer
from hg.res.loaders.image_loader import ImageLoader
from hg.res.loaders.loader import Loader
from hg.res.loaders.sprite_sheet_loader import Sprit... |
"""Imports for Python API.
This file is MACHINE GENERATED! Do not edit.
Generated by: tensorflow/tools/api/generator/create_python_api.py script.
"""
from tensorflow.python.ops.sets import set_difference
from tensorflow.python.ops.sets import set_intersection
from tensorflow.python.ops.sets import set_size
from tensor... |
# Generated by Django 3.2.4 on 2021-07-03 20:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('museum_site', '0063_auto_20210703_2039'),
]
operations = [
migrations.RenameField(
model_name='detail',
old_name='visibile',... |
#!/usr/local/bin/python3
"""Para_breaker.py"""
paragraph = """\
We hold these truths to be self-evident, that all men are created equal, that they are endowed by their Creator with certain unalienable Rights, that among these are Life, Liberty and the pursuit of Happiness. - That to secure these rights, Governments ar... |
#!/usr/bin/python
###########################################################################
# Copyright (c) 2014, Yahoo.
# All rights reserved.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# *... |
import math
def main():
people = int(input("How many people are eating? "))
slices_per_person = float(input("How many slices per person? "))
slices = slices_per_person * people
slices_per_pie = int(input("How many slices per pie? "))
pizzas = math.ceil(slices / slices_per_pie)
print("You need... |
#!/usr/bin/env python
"""
test_python_binding.py
Test that passing types to Python bindings works successfully.
mlpack is free software; you may redistribute it and/or modify it under the
terms of the 3-clause BSD license. You should have received a copy of the
3-clause BSD license along with mlpack. If not, see
ht... |
# `from __future__` has to be the very first thing in a module
# otherwise a syntax error is raised
from __future__ import annotations # type: ignore # noqa # Python 3.6 linters complain
from dataclasses import dataclass, fields
from enum import Enum
import pytest
from omegaconf import OmegaConf, ValidationError
... |
#!/usr/bin/env python
kingdoms = ['Bacteria', 'Protozoa', 'Chromista', 'Plantae', 'Fungi', 'Animalia']
print(kingdoms[0])
print(kingdoms[5])
print(kingdoms[0:3])
print(kingdoms[2:5])
print(kingdoms[4:]) |
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .forms import *
from django.http import HttpResponse
from sep.settings import MEDIA_URL
from django.contrib.sites.shortcuts import get_current_site
from django.utils.encoding import force_bytes, force_text
from ... |
import radio # 导入radio
from mpython import * # 导入mpython
import music # 导入music
CH = 1 # channel变量
radio.on()
radio.config(channel=CH) ... |
"""
MyHDL utility functions
(c) 2019 The Bonfire Project
License: See LICENSE
"""
from myhdl import intbv
from math import log2
def signed_resize(v,size):
result = intbv(0)[size:]
result[len(v):]=v
sign = v[len(v)-1]
for i in range(len(v),size):
result[i] =sign
return result ... |
import numpy as np
import glob
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import matplotlib.colors as color
import math
def ParamToInten(AoP, DoP, Inten, angle):
return ((Inten/2.0) * (1 + DoP*np.cos(math.radians(2*AoP) - 2*math.radians(angle))))
if __name__ == "__main__":
imagedir = "... |
import re
from typing import List
import requests
from youtube_series_downloader.core.channel import Channel
from youtube_series_downloader.core.video import Video
class YoutubeGateway:
__RSS_PREFX: str = "https://www.youtube.com/feeds/videos.xml?channel_id="
__REGEX = re.compile(
r"<entry>.*?<yt:vid... |
# Copyright (c) 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
from __future__ import a... |
from mesa import Agent, Model
from mesa.space import MultiGrid
import networkx as nx
class RunnerAgent(Agent):
''' This class will represent runners in this model '''
def __init__(self, unique_id, model):
super().__init__(unique_id, model)
self.reset_runner_info()
self.day_to_run = []... |
import pytest
from wikidict import gen_dict
@pytest.mark.parametrize(
"locale, words",
[
("fr", "logiciel"), # Single word
("fr", "base,logiciel"), # Multiple words
("fr", "cercle unité"), # Accentued word + space
],
)
@pytest.mark.parametrize("format", ["kobo", "stardict"])
de... |
#!/usr/bin/env python2.7
""" This module is a utility module for Windows.
The Win32 ThreeSpace Utils module is a collection of classes, functions,
structures, and static variables use exclusivly for Windows. All functions
in this module are used to scan for available ThreeSpace devices on the ho... |
from __future__ import (
absolute_import,
unicode_literals,
)
import os
import signal
import sys
import unittest
from pysoa.test.compatibility import mock
standalone = None
def setup_module(_):
"""
We want this setup to run before any of the tests in this module, to ensure that the `standalone` mo... |
from django.conf.urls import url
from rest_framework_jwt.views import obtain_jwt_token
from .views import statistical, users
urlpatterns = [
# 登录
url(r'^authorizations/$', obtain_jwt_token),
# -------------------- 数据统计 --------------------
# 用户总量
url(r'^statistical/total_count/$', statistical.User... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. codeauthor:: Cédric Dumay <[email protected]>
Schema allow to specify a mapping for :class:`logging.LogRecord`. It based on
:class:`marshmallow.Schema`. All schema MUST inherit from
:class:`logging_gelf.schemas.GelfSchema`.
"""
import socket
import time
from m... |
__version__ = "0.0.1"
import logging
from logging import NullHandler
from .vault import get_secret_or_env, get_vault_secret_keys, is_vault_initialised
__all__ = [
"get_secret_or_env",
"get_vault_secret_keys",
"is_vault_initialised"
]
logging.getLogger(__name__).addHandler(NullHandler())
|
# ref: https://www.youtube.com/watch?v=O20Y1XR6g0A&list=PLoVvAgF6geYMb029jpxqMuz5dRDtO0ydM&index=4
#import os
from influxdb import InfluxDBClient
from config import HOST, PORT, USERNAME, PASSWORD, DATABASE, TEMPERATURE, HUMIDITY, ROOM1
# following config moved to config.py file
# InfluxDB credentials
#HOST = o... |
# Code generated by `typeddictgen`. DO NOT EDIT.
"""V1beta1RunAsGroupStrategyOptionsDict generated type."""
from typing import TypedDict, List
from kubernetes_typed.client import V1beta1IDRangeDict
V1beta1RunAsGroupStrategyOptionsDict = TypedDict(
"V1beta1RunAsGroupStrategyOptionsDict",
{
"ranges": Li... |
# coding=utf-8
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------... |
import re
import unittest
import ir_datasets
from ir_datasets.formats import GenericDoc, GenericQuery, TrecQrel
from .base import DatasetIntegrationTest
_logger = ir_datasets.log.easy()
# Note: there's > 100k combinations here, so we are only testing a few cases
class TestCLIRMatrix(DatasetIntegrationTest):
def... |
"""
Python 3.6
PyTorch 0.4
"""
from abc import ABC, abstractmethod
from functools import partialmethod
import logging
import os
import torch
import utils
import Networks.MNIST_model as MNIST_model
import Networks.DCGAN_64 as DCGAN_64
Models = {'mnist': MNIST_model,
'fashion_mnist': MNIST_model,
... |
from datetime import datetime
from typing import List, Optional, Any
from sqlalchemy.orm import Session
from lib import aes
from lib.account.account import Account
from lib.account.account_entity import AccountEntity
from lib.account.account_entity_adapter import AccountEntityAdapter
from lib.db import session_scope
... |
# ---------------------------------------------------------------------
# Report Discovery Link Summary
# ---------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ---------------------------------------------------------------------
# T... |
# import argparse
import logging.config
import optparse
import os
from elastichq import create_app
from elastichq.globals import socketio
from elastichq.utils import find_config
default_host = '0.0.0.0'
default_port = 5000
default_debug = False
default_enable_ssl = False
default_ca_certs = None
default_verify_certs =... |
'''99 Units of Disposable Asset'''
from itertools import chain
# main :: IO ()
def main():
'''Modalised asset dispersal procedure.'''
# localisation :: (String, String, String)
localisation = (
'on the wall',
'Take one down, pass it around',
'Better go to the store to buy some mo... |
x = [ [5,2,3], [10,8,9] ]
students = [
{'first_name': 'Michael', 'last_name' : 'Jordan'},
{'first_name' : 'John', 'last_name' : 'Rosales'}
]
sports_directory = {
'basketball' : ['Kobe', 'Jordan', 'James', 'Curry'],
'soccer' : ['Messi', 'Ronaldo', 'Rooney']
}
z = [ {'x': 10, 'y': 20} ]
# Change the v... |
from types import MethodType
from PySide6.QtCore import QMimeData, QModelIndex, Slot
from PySide6.QtGui import QIcon
from PySide6.QtWidgets import QGridLayout, QHBoxLayout, QLineEdit, QListWidget, QListWidgetItem, QPushButton, QTableWidget, QTextEdit, QWidget, QLabel
from models.datasheet import DatasheetCollection
fro... |
#!usr/bin/python
# -*- coding:utf8 -*-
# 加上锁
import time
import threading
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
time.sleep(1)
print(self)
def __new__(cls, *args, **kwargs):
with cls._instance_lock:
if not hasattr(cls, '_instanc... |
# -*- coding: utf-8 -*- {{{
# vim: set fenc=utf-8 ft=python sw=4 ts=4 sts=4 et:
# Copyright (c) 2017, SLAC National Laboratory / Kisensum Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
... |
import os
import unittest
from pathlib import Path
from pyutil import IOUtils
from .TestSupport import TestSupport
class test_IOUtils(unittest.TestCase):
def test_cd(self):
with TestSupport.get_playground_path():
oldpath = Path.cwd()
testpath = Path("./aaa").resolve()
... |
"""
This app was created to specifically monitor the
OESS-FVD communication. It could be used to generate alarms
when a packetIn is received with current time sent by the FVD
too high compared with the time when the packet was
captured.
"""
from datetime import datetime, timedelta
from libs.core.de... |
import gc
import time
import tensorflow as tf
import numpy as np
from hyperka.et_apps.util import embed_init, glorot, zeros
from hyperka.hyperbolic.poincare import PoincareManifold
from hyperka.et_funcs.test_funcs import eval_type_hyperbolic
class GCNLayer:
def __init__(self,
adj,
... |
import yaml
import os
# CHeck if running from inside jupyter
# From https://stackoverflow.com/questions/47211324/check-if-module-is-running-in-jupyter-or-not
def type_of_script():
try:
ipy_str = str(type(get_ipython()))
if 'zmqshell' in ipy_str:
return 'jupyter'
if 'terminal' in... |
# encoding: utf-8
from datetime import date
import pytest
from mock import Mock
try:
from django.db.models import Value
except ImportError:
Value = Mock()
try:
from django.db.models.functions import Concat
except ImportError:
Concat = Mock(return_value=Mock(output_field=None))
from .app_management.m... |
import importlib
aws_iam = importlib.import_module('aws-iam')
def test_series_upgrade():
assert aws_iam.hookenv.status_set.call_count == 0
aws_iam.pre_series_upgrade()
assert aws_iam.hookenv.status_set.call_count == 1
|
from common_fixtures import * # NOQA
import time
def test_agent_create(super_client):
uri = "sim://" + str(time.time())
agent = super_client.create_agent(uri=uri)
assert agent.state == "registering"
assert agent.uri == uri
assert agent.transitioning == "yes"
agent = super_client.wait_succe... |
# Copyright (c) 2012-2022, Mark Peek <[email protected]>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
from . import AWSObject, AWSProperty, PropsDictType
from .validators import boolean, double, integer
from .validators.batch import (
validate_al... |
# -*- coding: utf-8 -*-
"""
NEUROscience Tool for Interactive Characterization
Curate, visualize, annotate, and share your behavioral ephys data using Python
"""
import os
import sys
import shutil
import copy
import pkg_resources
import collections.abc
import logging
import logging.handlers
import toml
from .version... |
# Generated by Django 3.0.5 on 2021-06-26 00:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myapp', '0011_form_assigned_supervisor_id'),
]
operations = [
migrations.AddField(
model_name='form',
name='action',... |
import torch
import numpy as np
import pandas as pd
import sacred
from datetime import datetime
import h5py
import feature.util as util
dataset_ex = sacred.Experiment("dataset")
@dataset_ex.config
def config():
# Path to reference genome FASTA
reference_fasta = "/users/amtseng/genomes/hg38.fasta"
# Path ... |
from aws_cdk import core
from aws_cdk import aws_s3 as s3
from aws_cdk import aws_ssm as ssm
from aws_cdk import aws_logs as logs
class CdkMinecraftS3Stack(core.Stack):
def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
super().__init__(scope, construct_id, **kwargs)
... |
from checkov.terraform.checks.resource.base_resource_value_check import BaseResourceValueCheck
from checkov.common.models.enums import CheckCategories, CheckResult
class GoogleCloudDNSSECEnabled(BaseResourceValueCheck):
"""
Looks for DNSSEC state at dns_managed_zone:
https://www.terraform.io/docs/provider... |
{
'targets': [
{
'target_name': 'huffin',
'include_dirs' : [
"<!(node -e \"require('nan')\")",
"<(nodedir)/deps/openssl/openssl/include",
'deps/libsodium/src/libsodium/include',
'deps/ed25519-donna',
],
'defines': [
'ED25519_SSE2',
],
'so... |
token = "NjAzODc5NDE2NDE3ODc4MDQ3.XTl0iA.PTZPdcnhpiV0Zm3iNmaMUgpphPg"
prefix = "~"
amqp_url = "amqp://guest:[email protected]:5672/%2f"
redis_url = "redis://127.0.0.1:6379/0"
owner = 446290930723717120
cogs = [
"events",
"general",
]
|
import json
from . import fields
from . import validate
try:
import urllib2 as request
except ImportError:
from urllib import request
ENABLED_HUMAN_VALUE_MAP = {
0 : 'Disabled',
1 : 'Enabled'
}
class Thermostat(object):
"""
This class implements the most basic functionality of communicating w... |
# Silvio Dunst
# Create a tuple that stores the months of the year,
# from that tuple create another tuple with just the summer months (May, June, July),
# print out the summer months one at a time.
# Tuples
months = ("January",
"February",
"March",
"April",
"May",
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Plot the results from the classification of lab by loading in the .pkl files generated by
figure3f_decoding_lab_membership_basic and figure3f_decoding_lab_membership_full
Guido Meijer
18 Jun 2020
"""
import pandas as pd
import numpy as np
import seaborn as sns
from o... |
from qasrl.nn.initializers import PretrainedModelInitializer_Prefixing
|
import csv
class Player:
# 初始化玩家,每人發 20000 遊戲幣以及出發位置為 0
def __init__(self,money = 20000, po = 0):
self.__money = money
self.__po = po
self.__status = 0
# 設定玩家名稱
def setName(self,name,id):
self.__name = name
self.__id = id
with open('players.csv','a',newli... |
import spidev
from .abstract_transport import AbstractTransport
from .gpio_interrupt import GPIOInterrupt
class SPITransport(AbstractTransport):
__READ_FLAG = 0x80
__MAGNETOMETER_READ_FLAG = 0xC0
__DUMMY = 0xFF
data_ready_interrupt: GPIOInterrupt
def __init__(self, spi_device: int, m... |
from django.dispatch import Signal
# This signal is sent when we get a sub
subscription_update = Signal(providing_args=["user"])
gift_accepted = Signal() |
import _plotly_utils.basevalidators
class DimensionsValidator(_plotly_utils.basevalidators.CompoundArrayValidator):
def __init__(
self, plotly_name='dimensions', parent_name='parcoords', **kwargs
):
super(DimensionsValidator, self).__init__(
plotly_name=plotly_name,
pa... |
#!/usr/bin/env python
#
# Can we calculate the flux density of the moon and an antenna G/T based off
# that?
#
# 1/2019 - Kyle Eberhart
#
# Based on - Darko Sekuljica - "Using the Moon as a calibrated noise source
# to measure the G/T figure-of-merit of an X-band satellite receiving station
# with a large a... |
from .data import SHARD_DATA_MAP
from .events import Event
class Telemetry:
def __init__(self, data, url):
self.shard = 'xbox' if 'xbox-' in url else 'pc'
self.events = [
Event.instance(event_data)
for event_data in self.generate_events_data(data)
]
def genera... |
# Copyright 2021 Alibaba Group Holding Limited.
#
# 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 rsm import test1,test2,test3
import numpy as np
from time import time as perf_counter
N = 40
M = 20
V = 20
mem = np.zeros((N,M), dtype=np.int32)
neg = np.zeros((N,V), dtype=np.int32)
out = np.zeros(N, dtype=np.int32)
input = np.zeros(M, dtype=np.int32)
input[0]=1
for i in range(1,M):
input[i] = i*10
test1(m... |
from flask import Flask, request, session, g, current_app
from subprocess import Popen
import pprint, time, threading, os, sys, sqlite3, shutil
# Borg pattern, all processManager objects will have the same states
# meaning they all reference the same processes, lock and thread.
class Borg:
_shared_state = {}
def _... |
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt
import numpy as np
#%matplotlib inline
import random
dados1 = random.sample(range(100), k=20)
dados2 = random.sample(range(100), k=20)
print(dados1)
print(dados2)
plt.plot(dados1, dados2)
print(plt.plot(dados1, dados2))
fig, ax = plt.subplots(... |
__author__ = 'casper'
|
# Time: O(|V| + |E|)
# Space: O(|V| + |E|)
# graph, dfs, bfs
class Solution(object):
def distanceToCycle(self, n, edges):
"""
:type n: int
:type edges: List[List[int]]
:rtype: List[int]
"""
def cycle(parent, v, u):
result = [parent[v], v]
whi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.