content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import chardet
import codecs
def WriteFile(filePath, lines, encoding="utf-8"):
with codecs.open(filePath, "w", encoding) as f:
actionR = '' #定位到[Events]区域的标记
for sline in lines:
if '[Events]' in sline:
actionR = 'ok'
f.write(sline)
continu... | python |
from screenplay import Action, Actor
from screenplay.actions import fail_with_message
class _if_nothing_is_found_fail_with_message(Action):
def __init__(self, action: Action, fail_actions: list, message: str):
super().__init__()
self.action = action
self.fail_actions = fail_actions
... | python |
# 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
# distributed unde... | python |
from .base import *
BOOST_PER_SECOND = 80 * 1 / .93 # boost used per second out of 255
REPLICATED_PICKUP_KEY = 'TAGame.VehiclePickup_TA:ReplicatedPickupData'
REPLICATED_PICKUP_KEY_168 = 'TAGame.VehiclePickup_TA:NewReplicatedPickupData'
def get_boost_actor_data(actor: dict):
if REPLICATED_PICKUP_KEY in actor:
... | python |
#!/usr/bin/env python3
# Copyright (c) 2019 The Unit-e Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.mininode import sha256
from test_framework.regtest_mnemonics import regtest_mnemonics
from t... | python |
from sanic import Sanic
from sanic.blueprints import Blueprint
from sanic.response import stream, text
from sanic.views import HTTPMethodView
from sanic.views import stream as stream_decorator
bp = Blueprint("bp_example")
app = Sanic("Example")
class SimpleView(HTTPMethodView):
@stream_decorator
async def p... | python |
import argparse
class ArgumentParser(argparse.ArgumentParser):
def __init__(self):
self.parser = argparse.ArgumentParser(description="Robyn, a fast async web framework with a rust runtime.")
self.parser.add_argument('--processes', type=int, default=1, required=False)
self.parser.add_argumen... | python |
r = 's'
while r == 's':
n1 = int(input('Digite o 1º valor: '))
n2 = int(input('Digite o 2º valor: '))
print(' [ 1 ] SOMAR')
print(' [ 2 ] Multiplicar')
print(' [ 3 ] Maior')
print(' [ 4 ] Novos Números')
print(' [ 5 ] Sair do Programa')
opcao = int(input('Escolha uma operação: '))
... | python |
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 28 10:00:06 2017
@author: ldn
"""
EndPointCoordinate=((-3.6,0.0,7.355),(123.6,0.0,7.355)) #west & east end point
rGirderRigidarmCoordinate=((10,8.13,0),(15,8.3675,0),(20,8.58,0),
(25,8.7675,0),(30,8.93,0),(35,9.0675,0),(40,9.18,0),(45,9.2675,0),(50,9.33,0),(55,9.36... | python |
#
# PySNMP MIB module SGTE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SGTE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:53:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:1... | python |
from django import forms
from django.contrib.auth.models import User
from .models import Profile
class UserCreationForm(forms.ModelForm):
username = forms.CharField(label='اسم المستخدم', max_length=30,
help_text='اسم المستخدم يجب ألا يحتوي على مسافات.')
email = forms.EmailField(... | python |
class Seat:
"""Seat contains features of the seat"""
def __init__(self):
self.left_handed = False
self.special_needs = False
self.broken = False
# Describes sid of person sitting there
self.sid = -1
# Used for ChunkIncrease
# True to use the seat, False ... | python |
nJoints = 16
accIdxs = [0, 1, 2, 3, 4, 5, 10, 11, 14, 15]
shuffleRef = [[0, 5], [1, 4], [2, 3],
[10, 15], [11, 14], [12, 13]]
edges = [[0, 1], [1, 2], [2, 6], [6, 3], [3, 4], [4, 5],
[10, 11], [11, 12], [12, 8], [8, 13], [13, 14], [14, 15],
[6, 8], [8, 9]]
ntuImgSize = 224
h36mImgSize... | python |
# -*- coding: utf-8 -*-
from ConfigParser import NoOptionError
import calendar
import datetime
from taxi import remote
from taxi.exceptions import CancelException, UsageError
from taxi.projects import Project
from taxi.timesheet import (
NoActivityInProgressError, Timesheet, TimesheetCollection, TimesheetFile
)
fr... | python |
"""This module will contain everything needed to train a neural Network.
Authors:
- Johannes Cartus, QCIEP, TU Graz
"""
from os.path import join
from uuid import uuid4
import tensorflow as tf
import numpy as np
from SCFInitialGuess.utilities.usermessages import Messenger as msg
from SCFInitialGuess.nn.cost_functio... | python |
from django.contrib import admin
from . import models
from django.conf import settings
admin.site.register(models.OfferCategory)
class OfferAdmin(admin.ModelAdmin):
if settings.MULTI_VENDOR:
list_display = ['title', 'total_vendors', 'starts_from', 'ends_at']
list_filter = ('vendor',)
else:
... | python |
from __future__ import annotations
from amulet.world_interface.chunk.interfaces.leveldb.base_leveldb_interface import (
BaseLevelDBInterface,
)
class LevelDB4Interface(BaseLevelDBInterface):
def __init__(self):
BaseLevelDBInterface.__init__(self)
self.features["chunk_version"] = 4
se... | python |
import unittest
from ui.stub_io import StubIO
class StubIOTest(unittest.TestCase):
def setUp(self):
self.io = StubIO()
def test_method_write_adds_argument_to_output_list(self):
self.io.write("test")
self.assertEqual(self.io.output, ["test"])
def test_method_set_input_add... | python |
import unittest
from kafka_influxdb.encoder import heapster_event_json_encoder
class TestHeapsterEventJsonEncoder(unittest.TestCase):
def setUp(self):
self.encoder = heapster_event_json_encoder.Encoder()
def testEncoder(self):
msg = b'{"EventValue":"{\\n \\"metadata\\": {\\n \\"name\\": \\... | python |
import os
import numpy as np
from PIL import Image
import subprocess
import cv2
def vision():
output = False # False: Disable display output & True: Enable display output
# subprocess.run(["sudo fswebcam --no-banner -r 2048x1536 image3.jpg"], capture_output=True)
# subprocess.run("sudo fswebcam /home/pi/... | python |
# 生成矩形的周长上的坐标
import numpy as np
from skimage.draw import rectangle_perimeter
img = np.zeros((5, 6), dtype=np.uint8)
start = (2, 3)
end = (3, 4)
rr, cc = rectangle_perimeter(start, end=end, shape=img.shape)
img[rr, cc] = 1
print(img)
| python |
# -*- coding: utf-8 -*-
import logging
from openstack import exceptions as openstack_exception
from cinderclient import client as volume_client
from cinderclient import exceptions as cinder_exception
import oslo_messaging
from oslo_config import cfg
from BareMetalControllerBackend.conf.env import env_config
from comm... | python |
class nodo_error:
def __init__(self, linea, columna, valor, descripcion):
self.line = str(linea)
self.column = str(columna)
self.valor = str(valor)
self.descripcion = str(descripcion)
errores = [] | python |
import pytest
from telliot_core.apps.core import TelliotCore
from telliot_core.queries.price.spot_price import SpotPrice
from telliot_core.utils.response import ResponseStatus
from telliot_core.utils.timestamp import TimeStamp
@pytest.mark.asyncio
async def test_main(mumbai_cfg):
async with TelliotCore(config=mu... | python |
from swockets import swockets, SwocketError, SwocketClientSocket, SwocketHandler
handle = SwocketHandler()
server = swockets(swockets.ISSERVER, handle)
handle.sock = server
while(True):
user_input = {"message":raw_input("")}
if len(server.clients) > 0:
server.send(user_input, server.clients[0], server.clients[0]... | python |
from tkinter import *
root = Tk()
root.geometry('800x800')
root.title('Rythmic Auditory Device')
root.configure(background="#ececec")
f = ("Times bold", 54)
def next_page():
"""Go to next page of GUI
Function destroys current calibration page and moves on to next main page.
"""
root.destroy()
i... | python |
from functools import lru_cache
import requests
from six import u
from unidecode import unidecode
_synset_sparql_query = """
SELECT ?item ?itemLabel WHERE {{
?item wdt:P2888 <http://wordnet-rdf.princeton.edu/wn30/{}-n>
SERVICE wikibase:label {{ bd:serviceParam wikibase:language "{}". }}
}}
"""
_wikidata_url = 'h... | python |
#!/usr/bin/env python
# encoding: utf-8
import sys
if sys.version_info.major > 2:
import http.server as http_server
import socketserver
else:
import SimpleHTTPServer as http_server
import SocketServer as socketserver
Handler = http_server.SimpleHTTPRequestHandler
# python -c "import SimpleHTTPServer;... | python |
# -*- coding: utf-8 -*-
"""
Authors: Tim Hessels
Contact: t.hessels@un-ihe.org
Repository: https://github.com/TimHessels/SEBAL
Module: SEBAL
Description:
This module contains a compilation of scripts and functions to run pySEBAL
"""
from SEBAL import pySEBAL
__all__ = ['pySEBAL']
__version__ = '0.1'
| python |
import unittest
import smartphone
from parameterized import parameterized, parameterized_class
TEST_PHONE_NUMBER = '123'
class SmartPhoneTest(unittest.TestCase):
def setUp(self):
super().setUp()
self.phone = smartphone.SmartPhone()
@parameterized.expand([
('idle', smartphone.CallState.IDLE, f'Has ca... | python |
#!/usr/bin/env python
import Bio; from Bio import SeqIO
from Bio.SeqRecord import SeqRecord
import urllib2
import sys
import StringIO
import os
base = os.path.expanduser('~')
prot_folder = base + '/biotools/uniprot_proteomes/'
fasta_records = []
if len(sys.argv) == 1:
accession = input('Enter UNIPROT proteome acces... | python |
import os
import math
import cereal.messaging as messaging
import cereal.messaging_arne as messaging_arne
from selfdrive.swaglog import cloudlog
from common.realtime import sec_since_boot
from selfdrive.controls.lib.radar_helpers import _LEAD_ACCEL_TAU
from selfdrive.controls.lib.longitudinal_mpc import libmpc_py
from... | python |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2011 Fourth Paradigm Development, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "Licen... | python |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | python |
"""
This file is part of genofunc (https://github.com/xiaoyu518/genofunc).
Copyright 2020 Xiaoyu Yu (xiaoyu.yu@ed.ac.uk) & Rachel Colquhoun (rachel.colquhoun@ed.ac.uk).
"""
import os
import unittest
from genofunc.extract_metadata import *
this_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
data_di... | python |
from .atmosphere import Atmosphere
from .generalized_atmosphere import GeneralizedAtmosphere
from .generalized_matching import GeneralizedMatching
from .psycop import PSYCOP
from .illicit_conversion import IllicitConversion
from .logically_valid_lookup import LogicallyValidLookup
from .matching import Matching
f... | python |
import demistomock as demisto
from CommonServerPython import * # noqa # pylint: disable=unused-wildcard-import
from CommonServerUserPython import * # noqa
import requests
import traceback
from typing import Dict, Any
# Disable insecure warnings
requests.packages.urllib3.disable_warnings()
TYPES = {
'threatType... | python |
from typing import Optional
from odmantic import Model
class Person(Model):
name: str
age: Optional[int]
john = Person(name="John")
print(john.age)
#> None
| python |
""" Implementation of DRO models """
import gurobipy as grb
import numpy as np
from time import time
def train_classifier(Kernel, labels_raw, all_epsilon, all_kappa, nc):
print('Train class ', nc + 1, '...')
t = time()
n_samples = Kernel.shape[0]
alpha = np.zeros((n_samples, len(al... | python |
import sys
if len(sys.argv) != 2:
print("Usage: python buildcml.py <cml file>")
exit(1)
infile = sys.argv[1]
# file names
outfile_md = "docs/" + infile.split(".")[0] + ".md"
outfile_txt = infile.split(".")[0] + ".txt"
# file buffers
md_buffer = "# Controller Layouts\n"
txt_buffer = ""
with open(infile, "r") as ... | python |
from dataclasses import field
from datetime import datetime
from typing import List, Optional
from pydantic.dataclasses import dataclass
@dataclass
class TypeA:
one: str
two: float
@dataclass
class TypeB(TypeA):
one: str
three: bool = field(default=True)
@dataclass
class TypeC(TypeB):
four: ... | python |
import requests
import unittest
class TestStringMethods(unittest.TestCase):
'''def test_000_operacoes_ola1(self):
r = requests.get('http://localhost:5000/ola/marcio')
self.assertEqual(r.text,'ola marcio')
r = requests.get('http://localhost:5000/ola/mario')
self.assertEqual(r.... | python |
from pytest import (fixture, mark)
from wrdpzl import(Board, Solver)
@fixture(scope='module')
def words():
with open('words.txt') as file:
return list(map(str.strip, file.readlines()))
@fixture(scope='module')
def solver(words):
return Solver(words)
@mark.timeout(0.5)
@mark.parametrize('board', [
... | python |
# Copyright (c) 2017-2021 Analog Devices Inc.
# All rights reserved.
# www.analog.com
#
# SPDX-License-Identifier: Apache-2.0
#
import PMBus_I2C
from encodings import hex_codec
import codecs
from time import *
from array import array
import math
import sys
if sys.version_info.major < 3:
input = ... | python |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""Url Ent... | python |
import queue
import time
from threading import Thread
import cv2
from scripts import centerface_utils
TARGET_WIDTH = 640
TARGET_HEIGHT = 640
TARGET_FPS = 30
class CameraDemo:
"""Multi-threaded python centerface detection demo."""
def __init__(self, runner: centerface_utils.CenterFaceNoDetection) -> None:
... | python |
#!/usr/bin/env python
'''
ASMO Configuration
Author:
Rony Novianto (rony@ronynovianto.com)
'''
# Run web to support any programming language via RESTful web service
# Run local if a higher performance is required (e.g. using ASMO with machine learning)
is_running_local = False
host = 'http://localhost... | python |
def double_first(vec):
try:
first = vec[0]
parsed = int(first)
return parsed * 2
except IndexError:
print("no first item")
except ValueError:
print("invalid first item")
if __name__ == '__main__':
numbers = ["42", "93", "18"]
empty = []
strings = ["tofu"... | python |
import numpy as np
# initial values
ARRAY = []
with open("xoData.txt") as f:
for line in f:
ARRAY.append([int(x) for x in line.split()])
# step function (activation function)
def step_function(sum):
if sum >= 0:
return 1
return -1
# calculateing output
def calculate_outpu... | python |
from yargy.utils import Record
| python |
import networkx as nx
import numpy as np
from copy import deepcopy
from collections import defaultdict
from ylearn.utils import to_repr
from . import prob
from .utils import (check_nodes, ancestors_of_iter, descendents_of_iter)
class CausalGraph:
"""
A class for representing DAGs of causal structures.
A... | python |
import typing
import uuid
from datetime import datetime
class SetType:
_all: typing.Set = set()
def __init__(self, api_name: str, desc: str):
self.name = str(api_name)
self.desc = desc
SetType._all.add(self)
def __eq__(self, other):
if not isinstance(other, Se... | python |
# coding=utf8
import re
from decimal import Decimal
from typing import Union
MAX_VALUE_LIMIT = 1000000000000 # 10^12
LOWER_UNITS = '千百十亿千百十万千百十_'
LOWER_DIGITS = '零一二三四五六七八九'
UPPER_UNITS = '仟佰拾亿仟佰拾万仟佰拾_'
UPPER_DIGITS = '零壹贰叁肆伍陆柒捌玖'
class ChineseNumbers:
RULES = [
(r'一十', '十'),
(r'零[千百十]', '零... | python |
"""
Configuration module for ladim
"""
# ----------------------------------
# Bjørn Ådlandsvik <bjorn@imr.no>
# Institute of Marine Research
# 2017-01-17
# ----------------------------------
# import datetime
import logging
from typing import Dict, Any
import numpy as np
import yaml
import yaml.parser
from netCDF4 im... | python |
# TODO: put the name flexstring in the Class.
# Class is not "Named" and its names are not interned.
# Sym continues like today. Meth is named.
import os, re, sys
import collections
from logging import info
# Tuning.
MEMORY_LEN = 0x8000 # Somewhat arbtrary.
SYM_VEC_LEN = 256
CLASS_VEC_LEN = 256
# Leave a little ga... | python |
"""
This file contains the full ImageFeaturizer class, which allows users to upload
an image directory, a csv containing a list of image URLs, or a directory with a
csv containing names of images in the directory.
It featurizes the images using pretrained, decapitated InceptionV3 model, and
saves the featurized data t... | python |
#!/usr/bin/env python3
# Copyright (c) 2016 Anki, 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 in the file LICENSE.txt or at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unles... | python |
# --------------
# Importing header files
import numpy as np
# Path of the file has been stored in variable called 'path'
#New record
new_record=[[50, 9, 4, 1, 0, 0, 40, 0]]
#Code starts here
data = np.genfromtxt(path, delimiter=',', skip_header=1)
print(data, data.shape)
census = np.concatenate((... | python |
import sys
sys.path.append(r'F:\geostats')
from geostats import Scraping
from get_groupinfo import *
from get_eventsInfo import *
from urllib.error import HTTPError
import time,random,os
def generate_groupdf(groups):
groups_df = []
for j,group in enumerate(groups):
try:
record = get_groups... | python |
# Pulls in images from different sources
# Thomas Lloyd
import numpy as np
import flickrapi
import urllib.request
# make private
api_key = '55d426a59efdae8b630aaa3afbac4000'
api_secret = '72f4bde28a867f41'
keyword1 = 'toulouse'
def initialize(api_key, api_secret):
flickr = flickrapi.FlickrAPI(api_key, api_secre... | python |
# Copyright 2021 UW-IT, University of Washington
# SPDX-License-Identifier: Apache-2.0
from sis_provisioner.management.commands import SISProvisionerCommand
from sis_provisioner.models.group import Group
class Command(SISProvisionerCommand):
help = "Prioritize groups for importing"
def handle(self, *args, *... | python |
from usuarios import Usuario
class Admin(Usuario):
def __init__(self, first_name, last_name, username, email):
super().__init__(first_name, last_name, username, email)
# self.priv = []
self.privileges = privileges()
# def show_privileges(self):
# print("\nPrivilegios:")
# ... | python |
import FWCore.ParameterSet.Config as cms
from RecoVertex.BeamSpotProducer.BeamSpot_cfi import *
| python |
# Copyright (c) 2015-2019 The Botogram Authors (see AUTHORS)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, mod... | python |
#!/usr/bin/python
# Copyright 2022 Northern.tech AS
#
# 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... | python |
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sparse_ho.utils_plot import configure_plt, discrete_cmap
save_fig = True
# save_fig = False
configure_plt()
fontsize = 18
current_palette = sns.color_palette("colorblind")
algorithms = ['grid_search10', 'random', 'bayesian', 'grad_searc... | python |
# -*- coding: utf-8 -*-
from rest_framework.permissions import BasePermission
from v1.models.Board import Boards
from v1.models.Permissions import READ, WRITE, DELETE
class BoardPermission(BasePermission):
def has_object_permission(self, request, view, obj):
if view.action in ['get_states', 'retrieve']:... | python |
import socket
import struct
import time
import thread
from nc_config import *
NC_PORT = 8888
CLIENT_IP = "10.0.0.1"
SERVER_IP = "10.0.0.2"
CONTROLLER_IP = "10.0.0.3"
path_reply = "reply.txt"
len_key = 16
counter = 0
def counting():
last_counter = 0
while True:
print (counter - last_counter), counter... | python |
import logging
import numpy as np
import kubric as kb
from kubric.renderer.blender import Blender as KubricBlender
logging.basicConfig(level="INFO") # < CRITICAL, ERROR, WARNING, INFO, DEBUG
world_matrix = {
"bunny": np.array(
(
(-1.0, 3.2584136988589307e-07, 0.0, 0.7087775468826294),
... | python |
import pygame
def compare_surfaces(surf_a: pygame.Surface, surf_b: pygame.Surface):
if surf_a.get_size() != surf_b.get_size():
return False
for x in range(surf_a.get_size()[0]):
for y in range(surf_a.get_size()[1]):
if surf_a.get_at((x, y)) != surf_b.get_at((x, y)):
... | python |
from django import forms
from django.contrib import admin
from emoji_picker.widgets import EmojiPickerTextarea
from .attachment import DisplayImageWidgetStackedInline
class TranslationModelForm(forms.ModelForm):
text = forms.CharField(
required=True,
label="Text übersetzt",
help_text="Hi... | python |
#coding = utf-8
import os
import Config
from Function import Function
class File(object):
def __init__(self, srcFileName, isKeep = False, dstFileName = None):
self.srcFileName = srcFileName
self.isKeep = isKeep
self.dstFileName = dstFileName
self.testFuncs = []
self.codeLines = None
self.__readCode(... | python |
from django.db import models
from django.contrib.auth.models import AbstractUser
import uuid
# esta clase define el perfil de usuario y extiende de AbstractUser
# por que solo se necesitaba eliminar los campos de first_name y last_name
# el resto del contenido se podia conservar
class profile(AbstractUser):
"""Def... | python |
# -*- coding: utf-8 -*-
import subprocess
import pytest
# Use an empty temporary HOME and unset CASA_BASE_DIRECTORY (see
# conftest.py)
pytestmark = pytest.mark.usefixtures("isolate_from_home")
def test_help():
retval = subprocess.call(['casa_distro', '--help'])
assert retval == 0
def test_help_subcomma... | python |
import yaml
from typing import List, Union, List, Any, Dict, Tuple
import typing
import enum
import attr
import attrs_strict
from attrs_strict import type_validator
class MissingAttribute(Exception):
pass
def yaml_dump(d):
return yaml.dump(d, Dumper=yaml.Dumper)
def self_attributes(self, attrs):
retur... | python |
import requests
from requests.exceptions import HTTPError, ConnectionError
from .resources.functions import validate_protocol
class WordPressAPI:
""" WP API Object Definition """
def __init__(self, domain, username, password, protocol="https", namespace="wp-json"):
""" Object constructor """
... | python |
# The MIT License (MIT)
#
# Copyright 2020 Barbara Barros Carlos, Tommaso Sartor
#
# This file is part of crazyflie_nmpc.
#
# 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... | python |
#!/usr/bin/env python3
import sys
# read input file
with open(sys.argv[1], 'r') as fd:
partitions = fd.readlines()
# init
part1 = 0
part2 = 0
seat_ids = []
# part1
for partition in partitions:
# row
left = 128
row = 0
for letter in partition[:7]:
left = int(left / 2)
if letter ==... | python |
#!/usr/bin/env python
# coding: utf-8
import logging
def get_logger(obj, level=None):
logging.basicConfig()
logger = logging.getLogger(obj.__name__)
if level is not None:
logger.setLevel(level)
return logger
| python |
from django.test import TestCase
from .mixins import TwoUserMixin, ProposalMixin
from consensus_engine.models import ConsensusHistory
from django.utils import timezone
# models test
class ConsensusHistoryTest(TwoUserMixin, ProposalMixin, TestCase):
def test_snapshot(self):
p = self.create_proposal_with_t... | python |
"""
Script for performing a fit to a histogramm of recorded
time differences for the use with QNet
"""
from __future__ import print_function
import sys
from matplotlib import pylab
import numpy
import scipy.optimize as optimize
def fit(bincontent=None, binning=(0, 10, 21), fitrange=None):
"""
Fit function
... | python |
from easydict import EasyDict
pong_dqn_gail_config = dict(
exp_name='pong_gail_dqn_seed0',
env=dict(
collector_env_num=8,
evaluator_env_num=8,
n_evaluator_episode=8,
stop_value=20,
env_id='PongNoFrameskip-v4',
frame_stack=4,
),
reward_model=dict(
... | python |
class MyClass:
def method1(self):
print('myClass method1')
def method2(self, someString):
print("myclass method2 " + someString)
class MyOtherClass(MyClass):
def method1(self):
MyClass.method1(self)
print("anotherClass method1")
def main():
c = MyClass()
c.method... | python |
# WikiBot
#
# Made by Aryan Takalkar
import speech_recognition as speech
import wikipedia
import pyttsx3
engine = pyttsx3.init()
running = True
def speech_init():
engine.setProperty('rate', 175)
engine.setProperty('volume' , 2)
voices = engine.getPropertyvoices = engine.getProperty('v... | python |
"""
Provides utility functions for creating plots in exercise 8.
"""
from typing import Union
def organize_kwargs(
user_kwargs: Union[dict, None], default_kwargs: dict = None
) -> dict:
"""
Update default keyword argument configuration with user provided
configuration.
Parameters
----------
... | python |
import s3fs
import numpy as np
import pandas as pd
import xarray as xr
from pyproj import Proj
def isin_merra_cell(lat, lon, latm, lonm):
dlat, dlon = 0.5, 0.625
lat1, lat2 = latm - dlat/2, latm + dlat/2
lon1, lon2 = lonm - dlon/2, lonm + dlon/2
lon_slices = [(lon1, lon2)]
if lon2 > 180:
lo... | python |
"""Sets (expansions) information
"""
import datetime
from typing import Hashable
from . import utils
class Set(utils.i18nMixin, utils.NamedMixin):
"""A class representing a V:tES Set (expansion)."""
def __init__(self, **kwargs):
super().__init__()
self.id = 0
self.abbrev = kwargs.get... | python |
from SimPEG import *
import simpegEM as EM
from scipy.constants import mu_0
import matplotlib.pyplot as plt
plotIt = False
cs, ncx, ncz, npad = 5., 25, 15, 15
hx = [(cs,ncx), (cs,npad,1.3)]
hz = [(cs,npad,-1.3), (cs,ncz), (cs,npad,1.3)]
mesh = Mesh.CylMesh([hx,1,hz], '00C')
active = mesh.vectorCCz<0.
layer = (mesh.v... | python |
"""
Support for EnOcean sensors.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.enocean/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (CONF_NAME, CONF_ID)... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018, Yanis Guenane <yanis+ansible@guenane.org>
# Copyright (c) 2019, René Moser <mail@renemoser.net>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_functio... | python |
# Ensomniac 2022 Ryan Martin, ryan@ensomniac.com
# Andrew Stet, stetandrew@gmail.com
import os
import sys
class GlobalSpacing:
group: bool
ignore: str
source_code: list
iter_limit_range: range
starts_with_keyword: str
line_break_quantity: int
GetIndentSpaceCount: callable
... | python |
import cvxpy as cp
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.utils import check_X_y
from sklearn.metrics.pairwise import euclidean_distances
from wdwd.utils import pm1
from wdwd.linear_model import LinearClassifierMixin
class DWD(BaseEstimator, LinearClassifierMixin):
def __init__(... | python |
from psyrun import Param
pspace = Param()
python = 'true'
def execute():
return {}
| python |
import numpy as np
def PlotPlanetXZ(fig,R=1.0,Center=[0.0,0.0,0.0],zorder=10,NoBlack=False,NoonTop=True):
a = 2*np.pi*np.arange(361,dtype='float32')/360
x = R*np.sin(a) + Center[0]
z = R*np.cos(a) + Center[2]
if NoonTop:
fig.fill(z,x,color=[1.0,1.0,1.0],zorder=zorder)
fig.plot(z,x,color=[0,0,0],zorder=zo... | python |
def text(result):
output = [
f"active rolls: {result['active_rolls']}",
f"cycles: {result['cycles']}",
"",
]
for key in ["bakes", "endorsements", "total"]:
output.append(key)
col1 = "mean"
col2 = "max"
header = " " * 10 + f"{col1:>10} {col2:>10}"
... | python |
from app.runner.setup import setup
app = setup()
| python |
import os
from datetime import datetime, timezone
from typing import Dict
import click
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
class Config:
@property
def repository(self) -> str:
return os.getenv("GITHUB_REPOSITORY")
@property
def actor(self) -> str:
... | python |
import peewee
db = peewee.SqliteDatabase('./apidocs/api_doc.db')
class ApiDoc(peewee.Model):
title = peewee.CharField(default='')
url = peewee.CharField()
method = peewee.CharField()
description = peewee.CharField(default='')
class Meta:
database = db
| python |
# -*- coding:utf-8 -*-
import peewee
from torcms.core import tools
from torcms.model.core_tab import TabPost
from torcms.model.core_tab import TabRel
from torcms.model.core_tab import TabPost2Tag
from torcms.model.post2catalog_model import MPost2Catalog as MInfor2Catalog
from torcms.model.abc_model import Mabc
class... | python |
#!/usr/bin/env python3
import torch
from ..distributions import MultivariateNormal
from ..lazy import InterpolatedLazyTensor
from ..utils.broadcasting import _mul_broadcast_shape
from ..utils.interpolation import Interpolation, left_interp
from ..utils.memoize import cached
from ._variational_strategy import _Variati... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.