content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# -*- coding: utf-8 -*-
from .player import BagPlayer
from .reader import BagReader
from .recorder import BagRecorder
from .writer import BagWriter
| nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
import sys
import os
path = os.path.dirname(os.path.abspath(__file__))
sys.path.append(os.path.join(path, ".."))
sys.path.append(os.path.join(path, "../../../common/"))
sys.path.append(os.path.join(path, "../../../common/acllite"))
import numpy as np
import acl
import base64
imp... | nilq/baby-python | python |
"""Gordon Ramsay shouts. He shouts and swears. There may be something wrong with him.
Anyway, you will be given a string of four words. Your job is to turn them in to Gordon language.
Rules:
Obviously the words should be Caps, Every word should end with '!!!!',
Any letter 'a' or 'A' should become '@', Any other vow... | nilq/baby-python | python |
# Copyright 2022 The jax3d 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 in wr... | nilq/baby-python | python |
import numpy as np
from forge.blade.action import action
from forge.blade.systems import skill, droptable
class Entity():
def __init__(self, pos):
self.pos = pos
self.alive = True
self.skills = skill.Skills()
self.entityIndex=0
self.health = -1
self.lastAttacker = None
def a... | nilq/baby-python | python |
from django.db import models
class Student(models.Model):
firstname = models.CharField(max_length=64)
lastname = models.CharField(max_length=64)
olsclass = models.ForeignKey('OLSClass')
family = models.ForeignKey('Family')
def __unicode__(self):
return self.name()
def name(self, lastn... | nilq/baby-python | python |
from django.core.management.base import BaseCommand
from exampleapp.models import FieldUpdate
from exampleapp.tests import EXAMPLE, FIELDS
from time import time, sleep
from django.db import transaction, connection
def tester(f, n=10):
runs = []
for _ in range(n):
# some sleep to put db at rest
... | nilq/baby-python | python |
#List items are indexed and you can access them by referring to the index number:
#Example
#Print the second item of the list:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
| nilq/baby-python | python |
import keyboard, time
from map import *
from inventory import Inventory
class Player():
x = 0
y = 0
direction = "UP"
costume = "@"
def spawn(pos_x, pos_y):
Map.generate()
Player.x = pos_x
Player.y = pos_y
Map.replaceObject(Player.x, Player.y, Player.costume, True)
... | nilq/baby-python | python |
# -*- coding: UTF-8 -*-
import io
from distutils.core import setup
# http://stackoverflow.com/a/7071358/735926
import re
VERSIONFILE='freesms/__init__.py'
# In Python 2.x open() doesn't support the encoding keyword parameter.
verstrline = io.open(VERSIONFILE, encoding='utf-8').read()
VSRE = r'^__version__\s+=\s+[\'"]... | nilq/baby-python | python |
import torch.nn as nn
from torchvision.models.alexnet import AlexNet
import torch.utils.model_zoo as model_zoo
from torch.nn.parameter import Parameter
import math
def init_network(model):
print('==> Network initialization.')
if isinstance(model, AlexNet) and hasattr(model, 'classifier100'): # fine tune alex... | nilq/baby-python | python |
from django.conf import settings
def pusher(request):
return {
"PUSHER_KEY": getattr(settings, "PUSHER_KEY", ""),
}
| nilq/baby-python | python |
from enhancer import enhance
startingtable = []
with open("data.txt", "r") as fh:
lookup = fh.readline().strip()
for thing in [i.strip() for i in fh.readlines()]:
if len(thing):
startingtable.append(list(thing))
enhance(startingtable, lookup, 50) | nilq/baby-python | python |
import collections as abc_collection
from .. import abc
from .adjacency_graph import AdjacencyGraph
class Bounded(abc.Graph):
"""
Wrapper to make the values of :py:class:`~.abc.Graph` instances bounded
:param value_bound: bound for all values
The ``value_bound`` must be compatible with all values s... | nilq/baby-python | python |
class PaintIt:
"""
Simple utility to easily color a text printed in the console.
Usage: print(ColorMe("green")("Hello World!"))
"""
colors = {
'unchanged': "{0}",
'yellow': "\033[93m{0}\033[00m",
'sea': "\033[96m{0}\033[00m",
'red': "\033[91m{0}\033[00m",
'g... | nilq/baby-python | python |
# Copyright 2018 Open Source Robotics Foundation, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | nilq/baby-python | python |
from django.test import TestCase
from core.forms import RITSForm
from core.models import get_rits_choices
class RITSFormTestCase(TestCase):
def test_python_prohibited(self):
test_body = {
'name': 'Test RITS',
'transformation_type': 'python',
}
form = RITSForm(test_... | nilq/baby-python | python |
import distributions
import numpy as np
def gen_hmm(pi, A, obs_distr, T):
K = len(obs_distr)
seq = np.zeros(T, dtype=int)
X = np.zeros((T,obs_distr[0].dim))
seq[0] = np.argmax(np.random.multinomial(1, pi))
for t in range(T-1):
seq[t+1] = np.argmax(np.random.multinomial(1, A[seq[t]]))
... | nilq/baby-python | python |
import subprocess
import json
creds = subprocess.check_output(['pass', 'gcloud/ansible@dlang-ci.iam.gserviceaccount.com'])
GCE_PARAMS = ('ansible@dlang-ci.iam.gserviceaccount.com', json.loads(creds)['private_key'])
GCE_KEYWORD_PARAMS = {'project': 'dlang-ci', 'datacenter': 'us-east1'}
| nilq/baby-python | python |
# Copyright 2021 The TensorFlow Ranking 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 ag... | nilq/baby-python | python |
import pandas as pd
import numpy as np
abnb = pd.read_csv('Airbnb_U4.csv',
usecols=[1, 2, 3, 5, 6, 7, 8, 27, 28],
)
print(abnb.shape)
# abnb.info()
# print("\nNULL :\n", abnb.isnull().sum())
abnb['price'] = round(np.exp(abnb['log_price']),1)
print(abnb.dtypes)
... | nilq/baby-python | python |
from unet_ddpm import *
class EncResBlock(nn.Module):
def __init__(
self, in_channel, out_channel, dropout=0, group_norm=32,
):
super().__init__()
norm_affine = True
self.norm1 = nn.GroupNorm(group_norm, in_channel)
self.activation1 = Swish()
self.conv1 = c... | nilq/baby-python | python |
#!/usr/bin/env python
### generate prior file from h5py file directly ###
### generate_h2_pT generates two prior files from the results of LDSC and a fixed annotation file ###
### generate_h2_from_user generates one prior file from the user provided prior file ###
import h5py
import os
from collections import Counter
... | nilq/baby-python | python |
import logging
import os
def initLogger() -> object:
"""
Initialize the logger.
"""
logger_level = logging.INFO
if 'APP_ENV' in os.environ:
if os.environ['APP_ENV'] == 'dev':
logger_level = logging.DEBUG
logging.basicConfig(level=logger_level,
form... | nilq/baby-python | python |
import numpy as np
import torch
import torchvision
import torch.utils.data as data
import torchvision.transforms as transforms
import pandas as pd
import h5py
import os
import sys
import json
import time
from scaler import *
from opts import parse_opts
from loss_funcs import *
# lightweight GAN model
from lwgan.lig... | nilq/baby-python | python |
"""
NLP Sandbox Date Annotator API
# Overview The OpenAPI specification implemented by NLP Sandbox Annotators. # noqa: E501
The version of the OpenAPI document: 1.0.2
Contact: thomas.schaffter@sagebionetworks.org
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
impo... | nilq/baby-python | python |
# Enter your code here. Read input from STDIN. Print output to STDOUT
phonebook = dict()
n = int(input())
for i in range(n):
inp = input()
inp_command = inp.split()
#print(inp_command)
phonebook[inp_command[0]] = int(inp_command[1])
#print(phonebook)
while True:
try:
name = input()
... | nilq/baby-python | python |
from typing import Any, List, Optional
from antarest.study.storage.rawstudy.model.filesystem.factory import FileStudy
from antarest.study.storage.variantstudy.model.model import CommandDTO
from antarest.study.storage.variantstudy.model.command.common import (
CommandOutput,
CommandName,
)
from antarest.study.s... | nilq/baby-python | python |
#!/usr/bin/env python
# EQUAL PARTS VINEGAR AND WATER
#
# https://www.goodhousekeeping.com/home/cleaning/tips/a26565/cleaning-coffee-maker/
#
# Fill the reservoir with equal parts vinegar and water, and place a paper filter
# into the machine's empty basket. Position the pot in place, and "brew" the solution
# halfway... | nilq/baby-python | python |
"""
# Copyright 2022 Red Hat
#
# 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... | nilq/baby-python | python |
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
import factory
from datetime import date
from ggrc_workflows import models
fro... | nilq/baby-python | python |
import shutil
def terminal_width():
"""
Return the current width of the terminal screen.
"""
return shutil.get_terminal_size().columns
| nilq/baby-python | python |
# jsb/tick.py
#
#
""" provide system wide clock tick. """
## jsb imports
from jsb.lib.threadloop import TimedLoop
from jsb.lib.eventbase import EventBase
from jsb.lib.callbacks import callbacks
from jsb.lib.config import getmainconfig
## TickLoop class
class TickLoop(TimedLoop):
def start(self, bot=None):
... | nilq/baby-python | python |
# -*- coding: utf8 -*-
"""`dsklayout.cli.cmdext_`
"""
from . import cmdbase_
__all__ = ('CmdExt',)
class CmdExt(cmdbase_.CmdBase):
__slots__ = ('_parent',)
@property
def parent(self):
"""A parent command which contains this extension"""
return self._parent
@parent.setter
def p... | nilq/baby-python | python |
#!/usr/bin/env python
import os
import codecs
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
setup(
name='django-compose-settings',
version=codecs.open(os.path.join(here, 'VERSION'), encoding='utf-8').read().strip(),
description='Django composable settings loader.',
... | nilq/baby-python | python |
typeface = {
'font': 'Gotham',
"foundry": "Hoefler",
"designer": "tobias frere-jones",
"cassification": "geometric sans-serif",
"default-size": 12.0,
'weights': [
{'name': "bold", 'weight': 600},
{'name': "medium", 'weight': 500},
{'name': "light", 'weight': 350}
],
... | nilq/baby-python | python |
import numpy as np
import pyautogui
import time
import cv2
from game_frame_detector import GameFrameDetector
from scrollbar_detector import ScrollbarDetector
from kai_recognizer import KaiRecognizer
from rarity_recognizer import RarityRecognizer
from common import Point, Size, Rect
def takeScreenshot():
raw_captur... | nilq/baby-python | python |
from passlib.hash import pbkdf2_sha256
def encrypt_psw(psw):
return pbkdf2_sha256.hash(psw)
def compare_psw(current, saved):
return pbkdf2_sha256.verify(current, saved)
| nilq/baby-python | python |
from .task import Task
class TaskObserver:
def __init__(self):
self.__tasks = {}
def add_task(self, task: Task):
delivery_tag = task.delivery_tag
if delivery_tag in self.__tasks.keys():
raise ValueError(f"Delivery tag {delivery_tag} is already exists")
self.__tasks... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import os
import pytest
def test_env_absent():
# Even if the env var is not initially set, the environ
# variables should not be affected.
assert "PYGAME_HIDE_SUPPORT_PROMPT" not in os.environ
import pygamesilent
assert "PYGAME_HIDE_SUPPORT_PROMPT" not in os.environ
| nilq/baby-python | python |
#-*- codeing = utf-8 -*-
import bs4 #Web page parsing
import re #Text extraction, regular expressions
import urllib.request,urllib.error #Get web page data
import xlwt #Excel
import sqlite3 #Database operations
def main():
baseurl="https://movie.douban.com/top250?start="
datalist = getData(baseurl)
def getDa... | nilq/baby-python | python |
from django.utils.encoding import smart_str
from test_plus import TestCase
from touchtechnology.common.tests import factories
class SitemapNodeTests(TestCase):
def setUp(self):
self.object = factories.SitemapNodeFactory.create()
def test_string_representation(self):
self.assertEqual(self.obj... | nilq/baby-python | python |
from threading import Thread, Event
import time
# Code to execute in an independent thread
def countdown(n, started_evt):
print("countdown starting")
started_evt.set()
while n > 0:
print("T-minus", n)
n -= 1
time.sleep(5)
# Create the event object that will be used to signal start... | nilq/baby-python | python |
# A script to copy positions using Interactive Brokers because SierrChart does
# not support adaptive market orders
import asyncio
import json
import logging
import typing as t
import datetime as dt
from asyncio.tasks import ensure_future
from contextlib import suppress
import click
from ib_insync import ContFuture, ... | nilq/baby-python | python |
from typing import Optional, List, Dict, Any
from collections import OrderedDict
import timm
from timm.models.layers import SelectAdaptivePool2d
import torch
import torch.nn as nn
from theseus.utilities.loading import load_state_dict
from theseus.utilities.loggers.observer import LoggerObserver
LOGGER = LoggerObserve... | nilq/baby-python | python |
import mock
import pytest
from py_zipkin import Encoding
from py_zipkin import Kind
from py_zipkin import logging_helper
from py_zipkin.encoding._encoders import get_encoder
from py_zipkin.encoding._helpers import create_endpoint
from py_zipkin.encoding._helpers import Endpoint
from py_zipkin.encoding._helpers import ... | nilq/baby-python | python |
import nddata
import numpy as np
def ones(shape, dtype = None):
'''
'''
values = np.ones(shape, dtype = dtype)
coords = []
dims = []
for ix in range(len(shape)):
dims.append(str(ix))
coords.append(np.arange(shape[ix]))
return nddata.nddata_core(values, dims, coords)
def o... | nilq/baby-python | python |
# this deals with setting a custom prefix and writing it to a json file
# (not the best way, but works)
# Imports
from discord.ext import commands
import discord
import json
# config
from config import DEFAULT_PREFIX
# cog class
class Prefix(commands.Cog):
def __init__(self, bot):
self.bot = bot
@c... | nilq/baby-python | python |
__author__ = 'Aaron Yang'
__email__ = 'byang971@usc.edu'
__date__ = '12/21/2020 5:37 PM' | nilq/baby-python | python |
squares = []
for x in range(10):
squares.append(x**2)
print(squares)
squares = list(map(lambda x : x** 2, range(10)))
print('lambda:', squares)
squares = [x ** 2 for x in range(10)]
print('for: ', squares)
squares = [(x,y) for x in [1,2,3] for y in [3,1,4] if x != y ]
print(squares) | nilq/baby-python | python |
from django.dispatch import Signal
product_viewed_signal = Signal(providing_args=['instance', 'request']) | nilq/baby-python | python |
from apero.core.constants import param_functions
from apero.core.core import drs_recipe
from apero import lang
from apero.core.instruments.default import file_definitions as sf
# =============================================================================
# Define variables
# =========================================... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from subprocess import check_call, call, Popen, PIPE
from ansible.module_utils.basic import *
LAIN_VIP_PREFIX_KEY = "/lain/config/vips"
module = AnsibleModule(
argument_spec=dict(
ip=dict(required=True),
port=dict(required=True),
container_app=... | nilq/baby-python | python |
# Generated by Django 2.0 on 2018-08-17 09:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('humanist_app', '0004_incomingemail_log'),
]
operations = [
migrations.AlterField(
model_name='incomingemail',
name='lo... | nilq/baby-python | python |
from rest_framework import routers
from talentmap_api.language import views
router = routers.SimpleRouter()
router.register(r'', views.LanguageListView, base_name="language.Language")
urlpatterns = []
urlpatterns += router.urls
| nilq/baby-python | python |
"""
A prototype application of the distributed cross-entropy method to the wind optimization problem.
In this basic implementation, the number of turbines is fixed and the generative distribution is uncorrelated.
TODO:
+ Add boundary constraints / penalties
+ Add proximity constraints
+ Better order turbine locatio... | nilq/baby-python | python |
from __future__ import unicode_literals
def file_args_to_stdin(file_args):
return '\0'.join(list(file_args) + [''])
def run_hook(env, hook, file_args):
return env.run(
' '.join(['xargs', '-0', hook['entry']] + hook['args']),
stdin=file_args_to_stdin(file_args),
retcode=None,
)
... | nilq/baby-python | python |
import os
import subprocess
import time
from .exceptions import InterfaceNotFoundError
from .abstract_readers import TcIpQueueLimitsStatsReader
from .utils.available_interfaces import AvailableInterfaces
class QueueLimitsStatsReader(TcIpQueueLimitsStatsReader):
@staticmethod
def _interface_exists(interface_n... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('tags', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='tag',
options={'verbose... | nilq/baby-python | python |
import numpy as np
import cvxopt as cvx
import math
from Env.opter import CvxOpt
class Env:
REWARD_NEG = 0
STATE_ON = 1
STATE_OFF = 0
def __init__(self, name, configure):
self.name = name
if configure.random_seed >= 0:
np.random.seed(configure.random_seed)
self... | nilq/baby-python | python |
import warnings
from copy import deepcopy
import pygromos.files.blocks.pertubation_blocks
from pygromos.files._basics import _general_gromos_file, parser
from pygromos.files.blocks import pertubation_blocks as blocks
class Pertubation_topology(_general_gromos_file._general_gromos_file):
_block_order = ["TITLE"]... | nilq/baby-python | python |
from base import BaseTest
import requests
import json
class Test(BaseTest):
def test_root(self):
"""
Test / http endpoint
"""
self.render_config_template(
)
proc = self.start_beat(extra_args=["-E", "http.enabled=true"])
self.wait_until(lambda: self.log_co... | nilq/baby-python | python |
from uuid import UUID
from typing import Dict, Optional
from dataclasses import dataclass, field
from sqlmodel import select
from sqlmodel.ext.asyncio.session import AsyncSession
from source.domain.entities import Profile
from source.ports.repositories import ProfileRepository
from source.infrastructure.tables import... | nilq/baby-python | python |
## emotionProcessor-threaded.py
## This is a variation of the emotionProcessor class.
## The main difference between the two classes is that this
## class utilizes python's threading module to collect the
## audio metrics.
## Since this proved to offer little to no performance gains
## while still expending ex... | nilq/baby-python | python |
import json
ID1 = "3a569cbc-49a3-4772-bf3d-3d46c4a51d32"
TEST_JSON_1 = {
"name": "some_name",
"values": [
"value1", "value2"
]
}
SHARED_ID = "2d34bed8-c79a-4f90-b992-f7d3b5bc1308"
SHARED_JSON = {
"shared_value": "psx"
}
EXPANSION_JSON = {
"services": {
"starsky": {
... | nilq/baby-python | python |
import os
import subprocess
import sys
import re
from joblib import Parallel, delayed
from tqdm import tqdm
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from Bio.Align.Applications import PrankCommandline
from Bio.Align.Applications import MafftCommandline
from Bio.Align.Applicat... | nilq/baby-python | python |
from pyrevit.framework import List
from pyrevit import revit, DB
import clr
clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')
clr.AddReference("System")
from Autodesk.Revit.DB import FilteredElementCollector
from Autodesk.Revit.DB import BuiltInCategory, ElementId, XYZ, ExternalFileReference,FamilyInstance,E... | nilq/baby-python | python |
#!/usr/bin/python3
def max_integer(my_list=[]):
"""
finds the largest integer of a list
"""
if len(my_list) == 0:
return (None)
my_list.sort()
return (my_list[-1])
| nilq/baby-python | python |
'''OpenGL extension EXT.blend_minmax
This module customises the behaviour of the
OpenGL.raw.GL.EXT.blend_minmax to provide a more
Python-friendly API
Overview (from the spec)
Blending capability is extended by respecifying the entire blend
equation. While this document defines only two new equations, the
Blen... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2015 Baifendian Corporation
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... | nilq/baby-python | python |
import json
jf = open('test.json', 'r')
f = json.load(jf)
l = [ ]
for item in f:
try:
loc = item['location']
except:
l.append(item['Empresa'])
out = open('test_no_found.txt', 'w')
out.write(str(l))
| nilq/baby-python | python |
#!/usr/bin/python
from __future__ import division
import sys
import collections
import math
def percentile(N, percent):
k = (len(N)-1) * percent
f = math.floor(k)
c = math.ceil(k)
if f == c:
return N[int(k)]
d0 = N[int(f)] * (c-k)
d1 = N[int(c)] * (k-f)
return int(d0+d1)
outputResults = sys.argv[1]
outputfil... | nilq/baby-python | python |
from setuptools import setup
import elife_bus_sdk
setup(
name='elife_bus_sdk',
version=elife_bus_sdk.__version__,
description='This library provides a Python SDK for the eLife Sciences Bus',
packages=['elife_bus_sdk',
'elife_bus_sdk.publishers',
'elife_bus_sdk.queues'],
... | nilq/baby-python | python |
"""
The Swift-Hohenberg equation
.. codeauthor:: David Zwicker <david.zwicker@ds.mpg.de>
"""
from typing import Callable
import numpy as np
from ..fields import ScalarField
from ..grids.boundaries.axes import BoundariesData
from ..tools.docstrings import fill_in_docstring
from ..tools.numba import jit, nb
from .ba... | nilq/baby-python | python |
#!/usr/bin/env python
"""
BluetoothMotors.py: Use bluetooth controller to control rover motors.
"""
__author__ = "Murray Ireland"
__email__ = "murray@murrayire.land"
__date__ = "16/01/2017"
import BluetoothController, time
from rrb3 import *
import numpy as np
# Initialise bluetooth controller
joystick = Blue... | nilq/baby-python | python |
np.kron(np.eye(2), np.ones((2,2))) | nilq/baby-python | python |
_MIN_TWO_DIGIT_HEX: int = 0x00
_MAX_TWO_DIGIT_HEX: int = 0xFF
def calculate_hex_digit(num: int) -> str:
if num < _MIN_TWO_DIGIT_HEX or num > _MAX_TWO_DIGIT_HEX:
raise RuntimeError('num is invalid and can not convert hex')
return hex(num)[2:].upper()
def calculate_opacity(percent_float: float) -> str... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Implements decorators used to retrieve and validate users/projects/teams/organizations/etc.
"""
from __future__ import unicode_literals
from __future__ import print_function
import re
from functools import wraps
from flask import request, jsonify
from collections import Sequence
f... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This file is part of pvsim.
# https://github.com/scorphus/pvism
# Licensed under the MIT license:
# http://www.opensource.org/licenses/MIT-license
# Copyright (c) 2017, Pablo Santiago Blum de Aguiar <pablo.aguiar@gmail.com>
import logging
import pika
class Broker(obj... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from model.person import Person
import pytest
import random
import string
def test_add_contact(app):
contact = Person(firstname=app.session.get_random_string(), lastname=app.session.get_random_string(), company=app.session.get_random_string(),
ad... | nilq/baby-python | python |
import os
def read_file(path):
lines = []
with open(path, "r", encoding="utf-8") as f:
lines = f.readlines()
lines = [ln.strip(os.linesep) for ln in lines]
return lines
def write_file(path, rows, separator="\t"):
with open(path, "wb") as outfile:
for row in rows:
... | nilq/baby-python | python |
# Homework Header as usual
#
#
#
import sys
import doctest
def read_FASTA(fname):
""" (str) -> (list of tuples)
# function body with documentation
"""
return sequences # a list of (sequence_name , sequence) tuples
def identify_orfs(dnaStrand):
""" (str) -> (list of strings)
# function body with documentation... | nilq/baby-python | python |
import numpy as np
import KalmanFilter as kf
from estimateSpeed import estimate_speed
class ObjectDetected:
def __init__(self, object_id, frame_number, indexes, H, pixelToMeters):
self.object_id = object_id
self.indexes = indexes
self.current_frame = frame_number
self.frames = [sel... | nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
########################################################################
#
# Copyright (c) 2016 Baidu, Inc. 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... | nilq/baby-python | python |
import json
from typing import Optional
import dgeq
from channels.db import database_sync_to_async
from django.core.exceptions import PermissionDenied, ValidationError
from django.http import Http404, JsonResponse
from pl_core.async_db import has_perm_async
from pl_core.enums import ErrorCode
from pl_core.mixins impo... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import sys
import os
import json
import yaml
import string
import random
import shlex
import subprocess
from traceback import format_exc
from flask import Flask, request, jsonify
app = Flask(__name__)
app.url_map.strict_slashes = False
assert 'APP_ROOT' in os.environ, 'No APP_ROOT env variable... | nilq/baby-python | python |
# Generated by Django 3.0.11 on 2020-12-17 13:49
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | nilq/baby-python | python |
import numpy as np
def rle_to_mask(lre, shape=(1600, 256)):
'''
params: rle - run-length encoding string (pairs of start & length of encoding)
shape - (width,height) of numpy array to return
returns: numpy array with dimensions of shape parameter
'''
# the incoming string is ... | nilq/baby-python | python |
import pygame, random
#Initialize pygame
pygame.init()
#Set display surface
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
display_surface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption("Group Collide!")
#Set FPS and clock
FPS = 60
clock = pygame.time.Clock()
#Define Classes
class Game(... | nilq/baby-python | python |
# -*- coding:utf-8 -*-
from datetime import datetime, timedelta
def get_time(num=0, sf="%Y%m%d",unit="days"):
'''
得到时间字符串
:param num: 和unit配合使用计算时间
:param sf: %Y%m%d%H%M%S
:param unit: days = None, seconds = None, microseconds = None, milliseconds = None, minutes = None, hours = None, weeks = None... | nilq/baby-python | python |
from mutations.translator import TranslateSchema
| nilq/baby-python | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
_SNAKE_TO_CAMEL_CASE_TABLE = {
"availability_zones": "availabilityZones",
"backend_services": "backendServices",
"beanstalk... | nilq/baby-python | python |
import configparser
import logging
from os.path import isfile
from typing import Dict, Union
import humanfriendly # type: ignore
from . import path_config
logger = logging.getLogger(__name__)
class GeneralClass:
def __init__(self, config: str = path_config.config_path_file) -> None:
if isfile(config):... | nilq/baby-python | python |
"""
Tests for Office Model
"""
from unittest import TestCase
from app.api.v1.models.office import PoliticalOffice
class TestOfficeModel(TestCase):
"""
TestOfficeModel class
"""
def test_political_office_create(self):
"""
Test that PoliticalOffice Model Creates Political Offices
"""
political... | nilq/baby-python | python |
"""Functions for getting current server resource use."""
from typing import Optional, Union
import psutil
import pandas as pd
import logging
import asyncio
import datetime
import numpy as np
import platform
import socket
import subprocess
from pathlib import Path
async def sample_resource_usage(data_dir: Path, file... | nilq/baby-python | python |
# Extraindo dados de um arquivo CSV e exibindo com Matplotlib
import csv
from matplotlib import pyplot as plt
from exe1600_country_codes import get_country_code
# Obtém as datas e as temperaturas máximas e mínimas do arquivo
# filename = 'sitka_weather_07-2014.csv'
# filename = 'sitka_weather_2014.csv'
filename = 'd... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import numpy as np
import pytest
from renormalizer.mps import Mps, Mpo
from renormalizer.model import MolList2, ModelTranslator
from renormalizer.utils.basis import BasisSHO, BasisMultiElectronVac, BasisMultiElectron, BasisSimpleElectron, Op
from renormalizer.tests import parameter
@pytest.m... | nilq/baby-python | python |
# Generated by Django 3.2.6 on 2021-08-10 11:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AdressEntery',
fields=[
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
""" LSOF class, a parallelized class for processing lsof output into a dict
Copyright (C) 2017 copyright /at/ mzpqnxow.com under the MIT license
Please see COPYRIGHT for terms
"""
from __future__ import print_function
from collections import defaultdict
from proclib.worker import ProcToolWorker... | nilq/baby-python | python |
"""
This script creates plots to visualize the results of simulations of the differential growth model.
Later on, it will also be used to visualize other models that work with discrete systems.
This script starts by importing a csv file of the results, creates a plot, shows it, and then exports it as a png to the same... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.