content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from pymtl import *
from lizard.util.rtl.interface import UseInterface
from lizard.util.rtl.method import MethodSpec
from lizard.core.rtl.messages import ExecuteMsg, WritebackMsg, PipelineMsgStatus
from lizard.util.rtl.pipeline_stage import gen_stage, StageInterface, DropControllerInterface
from lizard.core.rtl.kill_un... | nilq/baby-python | python |
# Copyright 2021 NVIDIA 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 or agreed to in wr... | nilq/baby-python | python |
import numpy as np
import hmm
x = np.random.randint(0, 500, 1000)
m = 3
l = np.array([10, 250, 450])
g = np.array([[.8, .1, .1], [.1, .8, .1], [.1, .1, .8]])
d = np.array([.3, .3, .3])
(success, lambda_, gamma_, delta_, aic, bic, nll, niter) = hmm.hmm_poisson_fit_em(x, m, l, g, d, 1000, 1e-6)
print(success, aic, bic... | nilq/baby-python | python |
import torch
from torch import nn
from buglab.models.layers.multihead_attention import MultiheadAttention
class RelationalMultiheadAttention(MultiheadAttention):
"""
A relational multihead implementation supporting two variations of using additional
relationship information between tokens:
* If no e... | nilq/baby-python | python |
from django.shortcuts import render
from datetime import datetime
from notifications.models import Notification
from users.models import Profile
from django.core.urlresolvers import reverse
from django.shortcuts import render
from django.contrib.auth.decorators import login_required, permission_required
from django.con... | nilq/baby-python | python |
from aoc import AOC
aoc = AOC(year=2015, day=18)
data = aoc.load()
## Part 1
# Initialize the array of lights to all off
lights = [x[:] for x in [[0] * len(data.lines())] * len(data.lines())]
# For every line in the input
in_y = 0
for line in data.lines():
line = line.strip()
in_x = 0
for c in line:
... | nilq/baby-python | python |
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.tree import DecisionTree
from pyspark.mllib.linalg import SparseVector
from pyspark import SparkContext
from operator import add
import time
import numpy
from pyspark.mllib.linalg import Vectors
import pyspark.mllib.clustering as cl
import os... | nilq/baby-python | python |
#!/usr/bin/env python3
from aws_cdk import core
from lab08.lab08_stack import Lab08Stack
app = core.App()
Lab08Stack(app, "lab08",env={"region":"us-east-1","account":"111111111111"})
app.synth()
| nilq/baby-python | python |
import h5py
import numpy as np
import glob
from mne import create_info
from mne.io import RawArray
def extract_blackrock_info(mat_file, blackrock_type):
""" Extracts basic recording info from a blacrock extracted mat file.
Extracts the data, sampling rate, channel names, and digital to
analog conversion ... | nilq/baby-python | python |
import tensorflow as tf
from tf_stft import Spectrogram, Logmel
from tensorflow_utils import do_mixup
class ConvBlock(tf.keras.Model):
"""
Convolutional Block Class.
"""
def __init__(self, out_channels):
"""
Parameters
----------
out_channels : int
Number of ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
def count_days(y, m, d):
return (365 * y + (y // 4) - (y // 100) + (y // 400) + ((306 * (m + 1)) // 10) + d - 429)
def main():
y = int(input())
m = int(input())
d = int(input())
if m == 1 or m == 2:
m += 12
y -= 1
print(count_days(201... | nilq/baby-python | python |
import pytest
from azure.ml import MLClient
@pytest.fixture
def environment_id() -> str:
return "/subscriptions/5f08d643-1910-4a38-a7c7-84a39d4f42e0/resourceGroups/sdk_vnext_cli/providers/Microsoft.MachineLearningServices/Environments/AzureML-Minimal"
@pytest.fixture
def compute_id() -> str:
return "testCom... | nilq/baby-python | python |
#!/usr/bin/env python3
# Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | nilq/baby-python | python |
from rdflib.graph import ConjunctiveGraph
from typing import ClassVar
from rdflib import Namespace
from test.testutils import MockHTTPResponse, ServedSimpleHTTPMock
import unittest
EG = Namespace("http://example.org/")
class TestSPARQLConnector(unittest.TestCase):
query_path: ClassVar[str]
query_endpoint: Cl... | nilq/baby-python | python |
# Copyright 2021 TUNiB Inc.
import torch
import torch.distributed as dist
from transformers import GPT2Tokenizer
from oslo.models.gpt_neo.modeling_gpt_neo import (
GPTNeoForCausalLM,
GPTNeoForSequenceClassification,
GPTNeoModel,
)
class TestPPInference:
def __init__(self, num_gpus):
self.num... | nilq/baby-python | python |
"""(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017"""
import ldap3
from epflldap.utils import get_optional_env, EpflLdapException
def _get_LDAP_connection():
"""
Return a LDAP connection
"""
server = ldap3.Server('ldap://' + get_optional_env('EPFL_LDAP_SERVE... | nilq/baby-python | python |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2020 Kyoto University (Hirofumi Inaguma)
# Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0)
"""Conduct forced alignment with the pre-trained CTC model."""
import codecs
import logging
import os
import shutil
import sys
from tqdm import tqdm
from n... | nilq/baby-python | python |
def my_reduce(value):
number = 0
for v in value:
number+=v
return number
| nilq/baby-python | python |
from playground.network.packet import PacketType, FIELD_NOT_SET
from playground.network.packet.fieldtypes import UINT8, UINT16, UINT32, UINT64, \
STRING, BUFFER, \
ComplexFieldType, PacketFields
from playground.network... | nilq/baby-python | python |
"""Base class for patching time and I/O modules."""
import sys
import inspect
class BasePatcher(object):
"""Base class for patching time and I/O modules."""
# These modules will not be patched by default, unless explicitly specified
# in `modules_to_patch`.
# This is done to prevent time-travel from... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Pox-based OpenFlow manager
"""
import pox.openflow.libopenflow_01 as of
from pox.core import core
from pox.lib.recoco import *
from pox.lib.revent import *
from pox.lib.addresses import IPAddr, EthAddr
from pox.lib.util import dpid_to_str
from pox.lib.util import str_to_dpid
from debussy.uti... | nilq/baby-python | python |
import cv2 as cv # noqa
import numpy as np # noqa
| nilq/baby-python | python |
r"""
Module of trace monoids (free partially commutative monoids).
EXAMPLES:
We first create a trace monoid::
sage: from sage.monoids.trace_monoid import TraceMonoid
sage: M.<a,b,c> = TraceMonoid(I=(('a','c'), ('c','a'))); M
Trace monoid on 3 generators ([a], [b], [c]) with independence relation {{a, c}}... | nilq/baby-python | python |
from .handler import get_db_handle
__all__ = ["get_db_handle"]
| nilq/baby-python | python |
#!/usr/bin/env python3
import os
# Third Party
from flask import Blueprint
from flask import request, jsonify
from flask import render_template
# main
from . import routes
main = Blueprint('main', __name__)
# Routes
main.add_url_rule("/", 'root', view_func=routes.root)
main.add_url_rule("/api/", 'api', view_func=r... | nilq/baby-python | python |
"""scrapli.driver.core.cisco_iosxr"""
from scrapli.driver.core.cisco_iosxr.driver import IOSXRDriver
__all__ = ("IOSXRDriver",)
| nilq/baby-python | python |
import pandas as pd
import os
import json
from settings import *
from src.utils.sampu import interp_multi, sel_pos_frame, normalize
import seaborn as sns
sns.set(style="darkgrid")
"""Given some keyframe numbers (normalized kf), encodes them and interpolates their latent datapoints.
Saves the z interpolants and t... | nilq/baby-python | python |
#!/usr/bin/env python3
#
# Copyright (c) 2019 Roberto Riggio
#
# 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 applicabl... | nilq/baby-python | python |
import pytest
from aiosnow.exceptions import SchemaError
from aiosnow.models import ModelSchema, Pluck, fields
from aiosnow.query.fields import IntegerQueryable, StringQueryable
def test_model_schema_field_registration():
class TestSchema(ModelSchema):
test1 = fields.String()
test2 = fields.Integ... | nilq/baby-python | python |
#!/usr/bin/env python2
# XXX: Refactor to a comand line tool and remove pylint disable
"""Merge columns of multiple experiments by gene id."""
from __future__ import absolute_import
import argparse
import csv
import os
import sys
from itertools import chain
import utils
parser = argparse.ArgumentParser(
descript... | nilq/baby-python | python |
from torchvision import models
from PIL import Image
import matplotlib.pyplot as plt
import torch
import numpy as np
import cv2
import torchvision.transforms as T
def decode_segmap(image, source, nc=21):
label_colors = np.array([(0, 0, 0),
# 1=aeroplane, 2=bicycle, 3=bird, 4=boat, 5=bottle
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from django.db.models.query import QuerySet
class PublisherQuerySet(QuerySet):
"""Added publisher specific filters to queryset.
"""
def drafts(self):
return self.filter(publisher_is_draft=True)
def public(self):
return self.filter(publisher_is_draft=False)
| nilq/baby-python | python |
#
# Copyright (c) 2019 Jonathan Weyn <jweyn@uw.edu>
#
# See the file LICENSE for your rights.
#
"""
Upload settings to a theta-e website loaded dynamically from the theta-e.conf.
"""
import os
import string
template_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'template.txt')
def main(config, s... | nilq/baby-python | python |
# Generated by Django 3.2.5 on 2021-09-01 16:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0008_alter_workspacerole_role'),
]
operations = [
migrations.AlterModelOptions(
name='upload',
options={},
),... | nilq/baby-python | python |
# Copyright 2015-2017 ARM 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 agreed to in w... | nilq/baby-python | python |
import os
f = open("test.txt" "w")
list1 = ["Shoes", "Socks", "Gloves"]
quantity = [10, 5, 32]
f.write("{:<10} {:10} {:10}\n".format("S/N", "Items", "Quantity"))
for item in list1:
f.write("{:<10} {:10} {:10}\n".format("S/N", "Items", "Quantity") + "\n")
f.close() | nilq/baby-python | python |
import os
import subprocess
import sys
try:
import pty
except ImportError:
PTY = False
else:
PTY = True
from mklibpy.common.string import AnyString
from mklibpy.terminal.colored_text import get_text, remove_switch
from mklibpy.util.path import CD
__author__ = 'Michael'
TIMEOUT = 0.5
print("""`mklsgit` ... | nilq/baby-python | python |
#coding: utf-8
'''
# * By :
# *
# * ██████╗ ██████╗ ██████╗ ██╗████████╗ ████████╗██╗ ██╗██████╗ ███╗ ██╗███████╗██████╗
# * ██╔═══██╗██╔══██╗██╔══██╗██║╚══██╔══╝ ╚══██╔══╝██║ ██║██╔══██╗████╗ ██║██╔════╝██╔══██╗
# * ██║ ██║██████╔╝██████╔╝██║ ██║ ██║ ██║ ██║██████╔╝██╔█... | nilq/baby-python | python |
from mySecrets import connectStr
import json
import pyodbc
DATABASE_USERACCOUNTS = "[dbo].[UserAccounts]"
DATABASE_PROBLEMS = "[dbo].[Problems]"
DATABASE_SUBMISSIONS = "[dbo].[Submissions]"
def executeCommandCommit(cmd: str) -> None:
cnxn = pyodbc.connect(connectStr)
cursor = cnxn.cursor()
cursor.execute... | nilq/baby-python | python |
import csv
import os
import sqlite3
import pytest
import shutil
from tempfile import gettempdir
from openpyxl import Workbook
TMP_DIR = gettempdir()
ws_summary_B5_rand = [
'Cookfield, Rebuild',
'Smithson Glenn Park Editing',
'Brinkles Bypass Havensmere',
'Folicles On Fire Ltd Extradition',
'Pudd... | nilq/baby-python | python |
from . import *
class TestDefaults(BrokerTestCase):
def test_basic_submit(self):
f = self.queue.submit_ex(name=self.id() + '.0', pattern=None)
self.assertTrue(f.id)
self.assertEqual(self.broker.fetch(f.id)['status'], 'pending')
self.assertEqual(self.broker.fetch(f.id)['priority'],... | nilq/baby-python | python |
from django.db import models
class Job(models.Model):
"""Class describing a computational job"""
# currently, available types of job are:
TYPES = (
("fibonacci", "fibonacci"),
("power", "power")
)
STATUSES = (
("pending", "pending"),
("started", "started"),
("finished", "finished"),
... | nilq/baby-python | python |
from pathlib import Path
from math import inf
def get_image_layers(raw_data, width, height):
digits = map(int, raw_data.strip())
layers = list()
curr_layer = list()
layer_size = width * height
for digit in digits:
curr_layer.append(digit)
if len(curr_layer) == layer_size:
... | nilq/baby-python | python |
import matplotlib.pyplot as plt
VIEW_BORDER = 0.1
plt.ion()
class plotter():
def __init__(self, pos_bounds, plot_vor, plot_traj, plot_graph):
self.p_bounds = pos_bounds
self.plot_vor_bool = plot_vor
self.plot_traj_bool = plot_traj
self.plot_graph_bool = plot_graph
if self.plot_vor_bool:
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import json
with open('data.txt', 'w') as outfile:
data = {"total": 10}
json.dump(data, outfile)
if __name__ == "__main__":
print("ok")
| nilq/baby-python | python |
from util import traceguard
from gui.toolbox import GetTextFromUser
from common import profile, pref
import wx
def change_password(protocol, cb):
val = GetTextFromUser(_('Enter a new password for {username}:'.format(username=protocol.username)),
_('Change Password'),
... | nilq/baby-python | python |
"""Module for dilation based pixel consensus votin
For now hardcode 3x3 voting kernel and see
"""
from abc import ABCMeta, abstractmethod, abstractproperty
import numpy as np
from scipy.ndimage.measurements import center_of_mass
from ..box_and_mask import get_xywh_bbox_from_binary_mask
from .. import cfg
class PCV_ba... | nilq/baby-python | python |
# coding: utf-8
"""
Command Line Interface
"""
import sys
import click
from chipheures_sos import __version__
from chipheures_sos.app import App
@click.group()
@click.version_option(__version__)
@click.option("--debug/--no-debug", default=False)
@click.pass_context
def cli(ctx, debug):
"""
Tool for database... | nilq/baby-python | python |
from unittest import TestCase
from osbot_k8s.utils.Docker_Desktop_Cluster import DEFAULT_DOCKER_DESKTOP_NAME
from osbot_utils.utils.Misc import list_set
from osbot_utils.utils.Dev import pprint
from osbot_k8s.kubectl.Kubectl import Kubectl
class test_Kubectl(TestCase):
def setUp(self) -> None:
self.kube... | nilq/baby-python | python |
import queue
from pynput.keyboard import Events, Key, Controller, Listener
from random import choice
from json import load
thread_comms = queue.Queue()
kb = Controller()
class KeyboardEvents(Events):
_Listener = Listener
class Press(Events.Event): # key press event
def __init__(self, ke... | nilq/baby-python | python |
import scipy
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
class DataLoader():
def __init__(self, dataset_name, img_res=(101, 101), norm=False):
self.dataset_name = dataset_name
self.img_res = img_res
self.data = np.loadtxt("network/networkFrame.csv", delim... | nilq/baby-python | python |
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Profile
from .models import StudentUser
from rest_framework.authtoken.models import Token
@receiver(post_save, sender=StudentUser)
def post_save_create_profile(sender,instance,created,**kwargs):
if created:
... | nilq/baby-python | python |
import json
class Operators():
@staticmethod
def initFactory():
import planout.ops.core as core
import planout.ops.random as random
Operators.operators = {
"literal": core.Literal,
"get": core.Get,
"seq": core.Seq,
"set": core.Set,
"index": core.Index,
"array": core.... | nilq/baby-python | python |
import nltk
from models import *
import torch
from tokenization import *
import time
from torchtext.data.metrics import bleu_score
from nltk.translate.bleu_score import sentence_bleu
from nltk.translate.bleu_score import corpus_bleu
from nltk.translate.meteor_score import meteor_score
import sys
device = torch.device(... | nilq/baby-python | python |
from django.conf import settings
from ngw.core.models import Config, Contact
def banner(request):
"""
This context processor just add a "banner" key that's allways available
"""
if hasattr(request, 'user') and request.user.is_authenticated:
return {'banner': Config.objects.get(pk='banner').te... | nilq/baby-python | python |
import sys
import os
import logging
import click
import wfepy
import wfepy.utils
@click.command()
@click.option('-d', '--debug', is_flag=True)
@click.argument('example_name')
def run_wf(debug, example_name):
logging.basicConfig(level=logging.DEBUG if debug else logging.INFO)
example_module = __import__(exa... | nilq/baby-python | python |
from abc import ABCMeta, abstractmethod, abstractproperty
from pathlib import Path
from PIL import Image, ImageFont, ImageDraw, ImageEnhance, ImageFilter
import string
import cv2
import numpy as np
from numpy.random import uniform, choice
from random import randint, choice as rand_choice
import arabic_reshaper
from b... | nilq/baby-python | python |
# Copyright 2019 Atalaya Tech, 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 or agreed to in writing, ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
string normalizer exceptions module.
"""
from pyrin.core.exceptions import CoreException
class StringNormalizerManagerException(CoreException):
"""
string normalizer manager exception.
"""
pass
class InvalidStringNormalizerTypeError(StringNormalizerManagerException):
... | nilq/baby-python | python |
# https://www.blog.pythonlibrary.org/2010/03/08/a-simple-step-by-step-reportlab-tutorial/
# from reportlab.pdfgen import canvas
#
# c = canvas.Canvas("hello.pdf")
# c.drawString(100,750,"Welcome to Reportlab!")
# c.save()
import time
from reportlab.lib.enums import TA_JUSTIFY
from reportlab.lib.pagesizes import lette... | nilq/baby-python | python |
import logging
import time
import config
logging.basicConfig(level=logging.DEBUG,
stream=open(config.LOGGING.format(int(time.time())), "w", encoding="utf-8"),
format='[%(asctime)s-%(filename)s] [%(levelname)s] %(message)s',
datefmt='%Y %H:%M:%S',
... | nilq/baby-python | python |
from hlt import *
from networking import *
def getValueMap(valueMap, gameMap):
for y in range(gameMap.height):
for x in range(gameMap.width):
valueMap[y][x] = gameMap.getSite(Location(x,y)).production
return valueMap
myID, gameMap = getInit()
valueMap = [ [0 for x in range(gameMap.width)]... | nilq/baby-python | python |
#!/usr/bin/env python3
import hmac
import json
import flask
import flask_compress
import flask_httpauth
class Config:
pass
config = Config()
with open("config.json") as f:
config_data = json.load(f)
if config_data["cloud_service"]["type"] != "azure storage datalake":
raise NotImplementedError(... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, Caleb Bell <Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal... | nilq/baby-python | python |
# Copyright 2009-2013 Nokia Siemens Networks Oyj
#
# 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 |
from connection import Connection
import viewer.page
def general_information(url: str) -> dict:
con = Connection()
soup = con.get(url).soup
return {
'Imslp Link': url,
'Genre Categories': viewer.page.genre_categories(soup),
'Work Title': viewer.page.work_title(soup),
'Name ... | nilq/baby-python | python |
import fileinput
import re
lists = [['fileListGetter.py', 'fileListGetter', ['directory', '_nsns'], [], 'def fileListGetter(directory, _nsns): """ Function to get list of files and language types Inputs: directory: Stirng containing path to search for files in. Outputs: List of Lists. Lists are of form... | nilq/baby-python | python |
# Generated by Django 3.1.7 on 2021-07-07 17:50
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('messenger', '0023_auto_20210615_0956'),
]
operations = [
migrations.AlterModelOptions(
name='message',
options={'ord... | nilq/baby-python | python |
import sys
import numpy as np
import cv2 as cv2
import time
import yolov2tiny
def open_video_with_opencv(in_video_path, out_video_path):
#
# This function takes input and output video path and open them.
#
# Your code from here. You may clear the comments.
#
#raise NotImplementedError('open_v... | nilq/baby-python | python |
"""
Server receiver of the message
"""
import socket
from ..constants import *
class UDPMessageReceiver:
def __init__(self, port=PORT):
self.__port = port
def receive_message(self):
# Create the server socket
# UDP socket
s = socket.socket(family=socket.AF_INET, type=socket.S... | nilq/baby-python | python |
#!/usr/bin/env python
# 参考 https://github.com/schedutron/CPAP/blob/master/Chap2/sleep_serv.py
from socket import *
HOST = ''
PORT = 1145
BUFSIZ = 1024
ADDR = (HOST, PORT)
with socket(AF_INET, SOCK_STREAM) as s:
s.bind(ADDR)
s.listen(5)
clnt, addr = s.accept()
print(f'连接到 {addr}。')
with clnt:
... | nilq/baby-python | python |
from .CDx import *
__version__ = '0.0.30'
| nilq/baby-python | python |
$ make -C doc/sphinx html
| nilq/baby-python | python |
# Create by Packetsss
# Personal use is allowed
# Commercial use is prohibited
from player import Player
from genotype import Genotype
class Population:
def __init__(self, size):
self.players = [Player(box2d[i]) for i in range(size)]
self.generation = 1
self.fitness_sum = 0
self.b... | nilq/baby-python | python |
import torch
from torch import nn
import clinicaldg.eicu.Constants as Constants
class FlattenedDense(nn.Module):
def __init__(self, ts_cat_levels, static_cat_levels, emb_dim, num_layers, num_hidden_units,
t_max = 48, dropout_p = 0.2):
super().__init__()
self.ts_... | nilq/baby-python | python |
'''
Copyright University of Minnesota 2020
Authors: Mohana Krishna, Bryan C. Runck
'''
import math
# Formulas specified here can be found in the following document:
# https://www.mesonet.org/images/site/ASCE_Evapotranspiration_Formula.pdf
# Page number of each formula is supplied with each function.
def get_delta(t... | nilq/baby-python | python |
from pathlib import Path
from cosmology import Cosmology
from instruments import Instrument
class Simulation:
def __init__(self, data_path, save_path, field, sim_type='src_inj',
cosmo='Planck18'):
self.data_path = Path(data_path)
self.save_path = Path(save_path)
self.field... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
class Solution:
def countPrimes(self, n):
if n == 0 or n == 1:
return 0
result = [1] * n
result[0] = result[1] = 0
for i, el in enumerate(result):
if el:
for j in range(i * i, n, i):
result[j] = 0... | nilq/baby-python | python |
import logging
import os
from nose.plugins import Plugin
log = logging.getLogger('nose.plugins.helloworld')
class HelloWorld(Plugin):
name = 'helloworld'
def options(self, parser, env=os.environ):
super(HelloWorld, self).options(parser, env=env)
def configure(self, options, conf):
super... | nilq/baby-python | python |
from __future__ import absolute_import
from pyramid.view import view_config
from sqlalchemy import func, and_, or_
from . import timestep_from_request
import tangos
from tangos import core
def add_urls(halos, request, sim, ts):
for h in halos:
h.url = request.route_url('halo_view', simid=sim.escaped_basen... | nilq/baby-python | python |
#!/usr/bin/python3
#
# Copyright © 2017 jared <jared@jared-devstation>
#
# Generates data based on source material
import analyze
markov_data = analyze.data_gen()
| nilq/baby-python | python |
#!/usr/bin/env python3
# coding = utf8
import datetime
import pytz
import time
import copy
import sys
def get_utc_datetime():
"""
获取utc时间
"""
utc_datetime_str = datetime.datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%SZ')
return utc_datetime_str
def get_utc_timestamp():
"""
获取utc时间的时间戳
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Configurations
--------------
Specifies the set of configurations for a marksim package
"""
import os
class Configs:
"""
Configurations
"""
# TODO This might be not the best design decision to pack all variables under one class.
# tpm configs
MARKOV_ORDER = 1
... | nilq/baby-python | python |
def test_dbinit(db):
pass
| nilq/baby-python | python |
# https://leetcode.com/problems/random-pick-with-weight
import random
import bisect
class Solution:
def __init__(self, ws: List[int]):
s = sum(ws)
v = 0
self.cumsum = [v := v + w / s for w in ws]
def pickIndex(self) -> int:
return bisect.bisect_left(self.cumsum, random.unifor... | nilq/baby-python | python |
from django.apps import AppConfig
default_app_config = 'mozillians.groups.GroupConfig'
class GroupConfig(AppConfig):
name = 'mozillians.groups'
def ready(self):
import mozillians.groups.signals # noqa
| nilq/baby-python | python |
'''
Created on Jan 19, 2016
@author: elefebvre
'''
| nilq/baby-python | python |
from django.apps import AppConfig
class GqlConfig(AppConfig):
name = 'gql'
| nilq/baby-python | python |
from django.db.models import Q
from django.db.models.manager import Manager
class WorkManager(Manager):
def match(self, data):
"""
Try to match existing Work instance in the best way possible by the data.
If iswc is in data, try to find the match using the following tries:
1. Matc... | nilq/baby-python | python |
from .bmk_semihost import *
| nilq/baby-python | python |
"""
The borg package contains modules that assimilate large quantities of data into
pymatgen objects for analysis.
"""
| nilq/baby-python | python |
from django.utils import timezone
from django.contrib import admin
from django.urls import path
from .models import Post, Category, Tag, Comment, Commenter
from . import views
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'author','status', 'last_edition_date']
readonly_fie... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import numpy as np
import random as rd
dim = 100
def reward(i, j):
string = dim/2
bp = complex(dim/2, dim/2)
bp = (bp.real, bp.imag)
cp = complex(i, j)
cp = (cp.real, cp.imag)
xdiff = cp[0]-bp[0]
if bp[1] < cp[1]:
s = 1/(1 + 10*abs(bp[0]-cp[0])/stri... | nilq/baby-python | python |
import gi
import enum
import g13gui.model.bindings as bindings
from g13gui.observer.gtkobserver import GtkObserver
from g13gui.model.bindingprofile import BindingProfile
from g13gui.model.bindings import StickMode
from g13gui.model.bindings import ALL_STICK_MODES
gi.require_version('Gtk', '3.0')
gi.require_version('G... | nilq/baby-python | python |
import numpy as np
from Matrices import *
print("Determinant of diagonal matrix:")
print(np.linalg.det(diag_A))
diag_A_rev = np.linalg.inv(diag_A)
print("Condition number of diagonal matrix:")
print(np.linalg.norm(diag_A_rev) * np.linalg.norm(diag_A))
print("Determinant of random matrix:")
print(np.linalg.det(random... | nilq/baby-python | python |
import sys
import time
import threading
import queue
from hashlib import sha256
from secrets import token_bytes
import grpc
from lnd_grpc.protos import invoices_pb2 as invoices_pb2, rpc_pb2
from loop_rpc.protos import loop_client_pb2
from test_utils.fixtures import *
from test_utils.lnd import LndNode
impls = [LndNo... | nilq/baby-python | python |
#!c:/Python26/ArcGIS10.0/python.exe
# -*- coding: utf-8 -*-
#COPYRIGHT 2016 igsnrr
#
#MORE INFO ...
#email:
"""The tool is designed to convert Arcgis Grid file to Series."""
# ######!/usr/bin/python
import sys,os
import numpy as np
import arcpy
from arcpy.sa import *
from arcpy import env
import shutil
import time
fr... | nilq/baby-python | python |
# Generated by Django 2.0.7 on 2018-09-03 02:40
from django.db import migrations
import django.db.models.deletion
import mptt.fields
class Migration(migrations.Migration):
dependencies = [
('zinnia-threaded-comments', '0002_migrate_comments'),
]
operations = [
migrations.AlterField(
... | nilq/baby-python | python |
# coding: utf-8
"""
LUSID API
FINBOURNE Technology # noqa: E501
The version of the OpenAPI document: 0.11.2321
Contact: info@finbourne.com
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
class QuoteSeriesId(object):
"""NOTE: This class is... | nilq/baby-python | python |
import unittest
from messages.message import Message
from messages.option import Option
from messages import Options
import defines
class Tests(unittest.TestCase):
# def setUp(self):
# self.server_address = ("127.0.0.1", 5683)
# self.current_mid = random.randint(1, 1000)
# self.server_mid... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.