content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import json
import logging
import unittest
from dataclasses import asdict, dataclass
from datetime import datetime, timedelta
from typing import Any, Dict, Mapping, Optional
from uuid import UUID, uuid4
import bson
from bson import ObjectId
from falcon.testing import Result
from eduid_userdb.testing import normalised... | nilq/baby-python | python |
# flake8: noqa
from .serializers import ViewSetSerializer
from .views import (
ViewSetCreateView, ViewSetDeleteView, ViewSetDetailView, ViewSetIndexView,
ViewSetListView, ViewSetUpdateView
)
from .viewsets import ModelViewSet, ViewSet
__version__ = '0.1.6'
default_app_config = 'viewsets.apps.ViewsetsConfig'
| nilq/baby-python | python |
import uuid
import boto3
from botocore.exceptions import ClientError
from busy_beaver.config import (
DIGITALOCEAN_SPACES_BASE_URL,
DIGITALOCEAN_SPACES_BUCKET_NAME,
DIGITALOCEAN_SPACES_ENDPOINT_URL,
DIGITALOCEAN_SPACES_REGION_NAME,
LOGOS_FOLDER,
)
class S3Client:
def __init__(self, client_ke... | nilq/baby-python | python |
import scrapy
import json
from bs4 import BeautifulSoup
import re
import datetime
import logging
logging.basicConfig(filename='Error.log', level=logging.CRITICAL, format='%(asctime)s:%(levelname)s:%(name)s:%(message)s', datefmt='%d/%m/%Y %I:%M:%S %p')
from PHASE_1.API_SourceCode.keyterms.key_terms import g... | nilq/baby-python | python |
from __future__ import print_function
import json
import os
import yagmail
import phonenumbers
class MailToSMS:
"""MailToSMS
This module implements a basic api for sending text messages via email using yagmail.
Arguments:
number {string|int}: The destination phone number (ex. 5551234567)
... | nilq/baby-python | python |
from google.cloud import storage
bucket_name = "ml_model_store"
storage_client = storage.Client()
storage_client.create_bucket(bucket_name)
for bucket in storage_client.list_buckets():
print(bucket.name)
| nilq/baby-python | python |
from Domo.Modules import *
from Domo.API import ApiManager, ApiResponse, ApiCodes
from System.Collections.Generic import Dictionary
from System.Drawing import Point, Color, Size, Brush, SolidBrush
from System.Threading import Thread, ThreadStart
from System.Windows.Forms import (
Application,
Form,
DialogResult... | nilq/baby-python | python |
# Stimulation server extended from VisionEgg.PyroApps.EPhysServer
from distutils.version import LooseVersion as V
import os
import ast
import Pyro
import pickle
import logging
import pygame
import VisionEgg
import VisionEgg.PyroApps.EPhysServer as server
from StimControl.LightStim.Core import DefaultScreen
from StimCo... | nilq/baby-python | python |
import torch
from torch.autograd import Function, Variable
from torch.nn import Module
from torch.nn.parameter import Parameter
import operator
def jacobian(f, x, eps):
if x.ndimension() == 2:
assert x.size(0) == 1
x = x.squeeze()
e = Variable(torch.eye(len(x)).type_as(get_data_maybe(x)))
... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (C) 2021 Antmicro
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either ... | nilq/baby-python | python |
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
class Permissions:
"""This is the base class for all custom permissions. To create a new permission set, subclass
this class."""
def __init__(self, model_name, app_label):
self.model_name =... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui_send_payout_dlg.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_SendPayoutDlg(object):
def setupUi(self, SendPayoutDlg):
... | nilq/baby-python | python |
"""
==========================================================================
TorusRouterFL.py
==========================================================================
FL route unit that implements dimension order routing.
Author : Yanghui Ou
Date : June 30, 2019
"""
from pymtl3 import *
from .directions import ... | nilq/baby-python | python |
import json
from common.methods import set_progress
from resourcehandlers.aws.models import AWSHandler
from botocore.client import ClientError
RESOURCE_IDENTIFIER = 'db_identifier'
def boto_instance_to_dict(boto_instance):
"""
Create a pared-down representation of an RDS instance from the full boto
dicti... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# @Author: Brian Cherinka, José Sánchez-Gallego, and Brett Andrews
# @Date: 2018-07-20
# @Filename: test_quantities.py
# @License: BSD 3-clause (http://www.opensource.org/licenses/BSD-3-Clause)
#
# @Last modified by: andrews
# @Last modified time: 2018-10-19 14:10:15
... | nilq/baby-python | python |
from .orientationDictionary import OrientationDictionary
from copy import deepcopy
class RiverDecorator:
def updateCells(
self, matrix, WATER_SPRITE_INDEX, waterSpot, GROUND_SPRITE_INDEX, waterSprites
):
orientationDictionary = OrientationDictionary(waterSprites)
spriteDict = orientat... | nilq/baby-python | python |
from telethon import TelegramClient, events, Button
import requests
import os
from pynpm import NPMPackage
from nodejs.bindings import node_run
import requests
import cryptg
import asyncio
import shutil
import subprocess
d = os.environ.get("d")
APP_ID = int(os.environ.get("APP_ID", 0))
API_HASH = os.environ.get("API_H... | nilq/baby-python | python |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def swapPairs(head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(-1)
prev, current = dummy, head;
dummy.next = h... | nilq/baby-python | python |
import pandas as pd
import numpy as np
import tensorflow as tf
import torch
from torch.nn import BCEWithLogitsLoss, BCELoss
from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler
from keras.preprocessing.sequence import pad_sequences
from sklearn.model_selection import train_test_split... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Class for dependency error exception
.. module:: lib.exceptions.dependencyerror
:platform: Unix
:synopsis: Class for dependency error exception
.. moduleauthor:: Petr Czaderna <pc@hydratk.org>
"""
class DependencyError(Exception):
"""Class DependencyError
"""
def __init... | nilq/baby-python | python |
#
# PySNMP MIB module Zhone (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Zhone
# Produced by pysmi-0.3.4 at Mon Apr 29 18:11:18 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:15)
#
... | nilq/baby-python | python |
from sqlalchemy import create_engine, Table, MetaData
from sqlalchemy.sql import select, delete, update, and_
import collections
from config import *
import datetime
class Dao():
con = None
def get_db_engine(self):
engine = create_engine(
'postgresql+psycopg2://%s:%s@%s:%s/%s' % (
... | nilq/baby-python | python |
from nonebot import on_command
from nonebot.adapters.cqhttp import Event
import requests
from nonebot.adapters.cqhttp import Bot
from nonebot.rule import to_me
weather = on_command("星座运势",rule=to_me(), priority=5)
@weather.handle()
async def handle_first_receive(bot: Bot, event: Event, state: dict):
arg... | nilq/baby-python | python |
# Here we use the last column of Table 4 of "Planck 2015 Results: XIII. Cosmological Parameters"
_cosmo_params = \
{
'omega_m_0': 0.3089,
'omega_b_0': round(0.0223/0.6774**2, 5),
'omega_l_0': 1. - 0.3089,
'hubble_0': 0.6774,
'helium_by_number': 0.0813,
'helium_by_mass': 0.2453,
'cmb_temp_0': 2.7255,
'sigma_8': 0.8159,
... | nilq/baby-python | python |
import pandas as pd
from pandas.io.formats.format import CategoricalFormatter
from config import ROOT_PATH_ABS, SSourceConfig as SSC
from config import RESULT_FOLDER_ABS
class Encoder(object):
def __init__(self, df:pd.DataFrame) -> None:
super().__init__()
self.df = df
self.sta... | nilq/baby-python | python |
import subprocess, logging
logger = logging.getLogger(__name__)
def turn_on_light(device):
if device.enabled:
if not device.status:
cmd = '/usr/local/bin/wemo switch "' + device.name + '" on'
proc = subprocess.Popen([cmd], stdout=(subprocess.PIPE), shell=True)
out, err... | nilq/baby-python | python |
from django_assets import env
def layout_workers(request):
workers = []
for name, bundle in env.get_env()._named_bundles.iteritems():
if name.startswith('worker_'):
name = name.split('_', 1)[1].rsplit('_', 1)[0]
workers.append((name, bundle.urls()[0]))
return {
'lay... | nilq/baby-python | 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 under th... | nilq/baby-python | python |
# ------------------------------------------------------------------------------
# CodeHawk Binary Analyzer
# Author: Henny Sipma
# ------------------------------------------------------------------------------
# The MIT License (MIT)
#
# Copyright (c) 2016-2020 Kestrel Technology LLC
# Copyright (c) 2020 Henny Si... | nilq/baby-python | python |
# Generated by Django 4.0 on 2022-01-02 13:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('leads', '0005_auto_20220102_1420'),
]
operations = [
migrations.AlterField(
model_name='agent',
... | nilq/baby-python | python |
#!/usr/bin/env python
import sys
import netsnmp
if __name__ == '__main__':
ip = '127.0.0.1'
snmp = netsnmp.SNMPSession(ip, 'RJKJ')
if snmp.is_alive():
snmp.close()
print 'test import netsnmp ok' | nilq/baby-python | python |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project
# root for license information.
from redact.types.file_bundle import FileBundle
from redact.types.file_bundle import FileType
class TestFileBundle:
def test_from_names(self) -> None:
... | nilq/baby-python | python |
"""
Copyright (C) 2017-2018 University of Massachusetts Amherst.
This file is part of "learned-string-alignments"
http://github.com/iesl/learned-string-alignments
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... | nilq/baby-python | python |
#!/usr/bin/env python3.9
# Modules
import os
import sprint
import colorama
import platform
from os.path import isfile, expanduser
# Credit message
colorama.init() # Fix windows colors
print(sprint.colored(f"Sprint v{sprint.__version__} by iiPython", "yellow"))
print(sprint.colored(f"Python version {platform.pytho... | nilq/baby-python | python |
"""Test categoricalCNNPolicy in PyTorch."""
import cloudpickle
import pytest
import torch
from garage.envs import GymEnv
from garage.torch import TransposeImage
from garage.torch.policies import CategoricalCNNPolicy
from tests.fixtures.envs.dummy import DummyDictEnv, DummyDiscretePixelEnv
class TestCategoricalCNNPo... | nilq/baby-python | python |
# coding=utf-8
import numpy as np
import torch.nn.functional as F
from datautil.util import random_pairs_of_minibatches
from alg.algs.ERM import ERM
class Mixup(ERM):
def __init__(self, args):
super(Mixup, self).__init__(args)
self.args = args
def update(self, minibatches, opt, sch):
... | nilq/baby-python | python |
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
MainWindow.resize(800, 600)
MainWindow.setUnifiedTitleAndToolBarOnMac(False)
self.centralwidget = QtWidgets.QWidget(MainWindow)
self.c... | nilq/baby-python | python |
from __future__ import absolute_import
import argparse
from detect_secrets.core.usage import ParserBuilder
import detect_secrets_server
from .add import AddOptions
from .install import InstallOptions
from .list import ListOptions
from .scan import ScanOptions
class ServerParserBuilder(ParserBuilder):
"""Argume... | nilq/baby-python | python |
from espnet_model_zoo.downloader import ModelDownloader
import sys
model_name = sys.argv[1]
d = ModelDownloader()
model_path = d.download(sys.argv[1])
print(model_path)
| nilq/baby-python | python |
larg = float(input('Qual a largura da parede?'))
alt = float(input('Qual a altura da parede?'))
print('Você vai precisar de {:.0f} litros de tinta'.format((larg*alt)/2)) | nilq/baby-python | python |
# Difficulty Level: Beginner
# Question: Calculate the sum of the values of keys a and b .
# d = {"a": 1, "b": 2, "c": 3}
# Expected output:
# 3
# Program
d = {"a": 1, "b": 2, "c": 3}
print(d["a"] + d["b"])
# Output
# shubhamvaishnav:python-bootcamp$ python3 17_dictionary_items_sum_up.py
# 3
| 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! ***
import pulumi
import pulumi.runtime
class Association(pulumi.CustomResource):
"""
Associates an SSM Document to an instance or... | nilq/baby-python | python |
from django.db.models.query import Q
from django.utils import timezone
from rest_framework import serializers
from ..accounts.serializers import UserSerializer
from .models import Amenity, Booking
class AmenityRelatedField(serializers.RelatedField):
def to_native(self, value):
return {
'id... | nilq/baby-python | python |
import os
from unittest import TestCase
from checkov.cloudformation.cfn_utils import create_definitions
from checkov.cloudformation.graph_builder.graph_components.block_types import BlockType
from checkov.cloudformation.graph_builder.graph_to_definitions import convert_graph_vertices_to_definitions
from checkov.cloudf... | nilq/baby-python | python |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... | nilq/baby-python | python |
from ..classes import ml_util
def test_objective_function():
new_objective = ml_util.ObjectiveFunction()
new_objective.load_data(path="Use Cases/VPS Popcorn Production/Docker/src/data/vpsFeatures.csv")
new_objective.fit_model()
prediction = new_objective.get_objective(4000)
assert prediction == 0.... | nilq/baby-python | python |
AddressType = int
SelectorType = int
| nilq/baby-python | python |
from manimlib.imports import *
from my_manim_projects.my_utils.my_3D_mobject import *
from my_manim_projects.my_utils.my_text import *
class Sum_of_cubes(ThreeDScene):
CONFIG = {
'camera_init': {
'phi': 52.5 * DEGREES,
'gamma': 0,
'theta': -45 * DEGREES,
},
... | nilq/baby-python | python |
# import unittest
# from unittest.mock import patch
# import http.client
| nilq/baby-python | python |
from app import app
import dataquery
import json
@app.route("/ajaxreq/get_capital_account_info<any:args>",methods=['GET'])
def ajaxrep_get_capital_account_info(args):
#cai=dataquery.get_capital_account_info();
return "abc";
#return json.dumps(cai); | nilq/baby-python | python |
import socket
import sys
import hlt
PORT_ = 2000
class Game(hlt.Game):
def __init__(self, *args, **kwargs):
self._buf = []
self._connection = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self._connection.connect(("localhost", PORT_))
super().__init__(*args, **kwargs)
def... | nilq/baby-python | python |
from typing import Iterable, List
import sparql_queries
from movie import Movie
from joblib import Parallel, delayed
from env import env
class Recommandation():
def __init__(self, uri, func, id, text) -> None:
self.data = getattr(sparql_queries, func)(uri)
self.data = [Movie(dataReco=mov) for mov ... | nilq/baby-python | python |
import unittest
from blazeweb.globals import settings
from blazeweb.config import QuickSettings, EnabledSettings
from blazeweb.hierarchy import listapps
from nose.tools import eq_
from minimal2.application import make_wsgi as make_wsgi_min2
from blazewebtestapp.applications import make_wsgi
class Base(QuickSettings)... | nilq/baby-python | python |
#!/usr/bin/env python
"""
DESCRIPTION:
This is an extremely simple Python application that demonstrates how to use Elbrys SDN Developer Lab (dev.elbrys.com) to
control endpoint user sessions access to the network.
This application will connect to one of the switches that you have connected in the SDN Devel... | nilq/baby-python | python |
"""Unit tests for flux calibration/zeropoints
Authors
-------
- Bryan Hilbert
Use
---
Ensure you have pytest installed. Then, simply run pytest in any
parent directory of mirage/tests/:
>>> pytest
"""
from astropy.table import Table
import numpy as np
import os
import pkg_resources
from mirage.utils ... | nilq/baby-python | python |
def clean_string(s):
if len(s) == 0:
return s
q = []
for idx in range(len(s)):
if s[idx] != "#":
q.append(s[idx])
elif len(q) != 0:
q.pop()
return "".join(q)
| nilq/baby-python | python |
import os
high_scores = {
"small_1" : "0",
"small_2" : "0",
"small_3" : "0",
"medium_1" : "0",
"medium_2" : "0",
"medium_3" : "0",
... | nilq/baby-python | python |
from typing import List
import torch
from torch.utils.data.dataset import Dataset
def noise(outlier_classes: List[int], generated_noise: torch.Tensor, norm: torch.Tensor,
nom_class: int, train_set: Dataset, gt: bool = False) -> Dataset:
"""
Creates a dataset based on the nominal classes of a given ... | nilq/baby-python | python |
import logging
import logging.handlers
import os
def create_logger(name):
"""Create generic logger for all nodes"""
# Create logger and let it capture all messages
logger = logging.getLogger(name)
logger.setLevel(logging.DEBUG)
# Output formatting
formatter = logging.Formatter("[ %(asctime)s... | nilq/baby-python | python |
from __future__ import absolute_import, division, print_function
import os
import numpy as np
import pytest
from ciso import zslice
data_path = os.path.join(os.path.dirname(__file__), "data")
@pytest.fixture
def data():
p = np.linspace(-100, 0, 30)[:, None, None] * np.ones((50, 70))
x, y = np.mgrid[0:20:5... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import pytest
from olympia.users.models import UserProfile
from olympia.users.templatetags.jinja_helpers import user_link, users_list
pytestmark = pytest.mark.django_db
def test_user_link():
u = UserProfile(username='jconnor', display_name='John Connor', pk=1)
assert user_link(u) ==... | nilq/baby-python | python |
from __future__ import division
import os
import pickle
import numpy as np
import blt_net.cascademv2.utils.benchmark_utils as benchmark_utils
import ntpath
import cv2
from blt_net.cascademv2.utils.general_utils import create_logger
import sys
import tensorflow as tf
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.en... | nilq/baby-python | python |
'''
Extra operators used by MetaFunctions
'''
from operator import add, sub, truediv, mul
def concat(*args):
"concat(1, 2, 3) -> (1, 2, 3)"
return args
| nilq/baby-python | python |
# Generated by Django 2.2.2 on 2019-09-27 00:54
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("dcodex", "0003_auto_20190920_1333"),
]
operations = [
migrations.AlterModelOptions(
name="manuscript",
options={"ordering": ... | nilq/baby-python | python |
import pytest
# stdlib
import json
import os
import unittest
from stackstate_checks.base.errors import CheckException
from stackstate_checks.splunk.client import TokenExpiredException
from stackstate_checks.splunk_health.splunk_health import SplunkHealth, Instance
from stackstate_checks.base.stubs import health, aggr... | nilq/baby-python | python |
import yaml
import os
import json
import logging
import time
def read_yaml(path_to_yaml: str) -> dict:
with open(path_to_yaml) as yaml_file:
content = yaml.safe_load(yaml_file)
logging.info(f"yaml file: {path_to_yaml} loaded successfully")
return content
| nilq/baby-python | python |
from math import sqrt
import numpy as np
# tools used in production
# ---------------------------------------------------------------------------------------------
def combine_mean_std(l_n, l_mean, l_std):
"""
Ref: https://www.statstodo.com/index.php and
Altman DG, Machin D, Bryant TN and Gardner MJ. (2... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from helper import IcebergUnitTestCase
class ClientAddresses(IcebergUnitTestCase):
def test_create(self):
"""
Create an address for the user
"""
self.login()
self.create_user_address()
def test_read(self):
"""
Try to fetch the a... | nilq/baby-python | python |
"""Create organisation table
Revision ID: ba9997532100
Revises:
Create Date: 2021-11-08 14:36:59.635469
"""
import sqlalchemy as sa
# revision identifiers, used by Alembic.
from app.db.utils import UtcNow
from alembic import op
revision = "ba9997532100"
down_revision = None
branch_labels = None
depends_on = None
... | nilq/baby-python | python |
# trivial example = 30/50 = 3/5
# non-trivial example = 49/98 = 4/8
# There are 4 non-trivial types of these fractions < 1 and both numerator and
# denominator contain two digits find the the product of the four in its
# lowest common terms, what is the denominator?
import timeit
import itertools
from functool... | nilq/baby-python | python |
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('assignments/', views.AssignmentListView.as_view(), name='assignments'),
path('assignment/<int:pk>', views.AssignmentDetailView.as_view(), name='assignment-detail'),
path('units/', views.UnitListView.as_view(), ... | nilq/baby-python | python |
from stormed.method.codegen.tx import *
| nilq/baby-python | python |
from litex.build.generic_platform import *
from litex.build.xilinx import XilinxPlatform, XC3SProg
_io = [
#OSC
("clk_50", 0, Pins("T7"), IOStandard("LVCMOS33")),
# RESET
("resetn", 0, Pins("C3"), IOStandard("LVCMOS33"), Misc("PULLDOWN")), #UNUSED PIN
# EVERLOOP CONTROL
("everloop_ctl", 0,... | nilq/baby-python | python |
"""Infer properties of TensorFlow nodes.
"""
from lucid.misc.graph_analysis.overlay_graph import OverlayNode, OverlayGraph
import tensorflow as tf
def as_tensor(t):
if isinstance(t, OverlayNode):
return t.tf_node
elif isinstance(t, tf.Operation):
return t.outputs[0]
elif isinstance(t, tf.Tensor):
re... | nilq/baby-python | python |
"""
ABOTS: A Bunch Of Tiny Scripts
==============================
The name of this project explains what it is, a bunch of tiny scripts.
I find myself thinking of many different projects that all require some core
functionality that many other projects can share.
However, it must be laid down first before adding th... | nilq/baby-python | python |
from ..mapper import PropertyMapper, ApiInterfaceBase
from ..mapper.types import Timestamp, AnyType
__all__ = ['DismissCard', 'DismissCardInterface']
class DismissCardInterface(ApiInterfaceBase):
card_id: int
image_url: str
title: AnyType
message: AnyType
button_text: AnyType
camera_target: A... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 15:52:30 2020
@author: liu
"""
NAME = 'FCS'
DESCR = """
This example uses **Pulse Streamer** to emulate signals for fluorescence correlation spectroscopy (FSC).
The example demonstrates autocorrelation measurement with logarithmic binning.
* Channel 1 - fluorescence... | nilq/baby-python | python |
# ___ _ ___ ___ _ |
# / _ \ __| |_ ___| _ \/ __| | | Create 8-bit-like games!
# | (_) / _| _/ _ \ _/ (_ |_| | Author: Death_Miner
# \___/\__|\__\___/_| \___(_) | Version: 0.4.0
# |
#
# @ octopg/data.py => Handles multiple data files
# We use the JSON format ... | nilq/baby-python | python |
__all__ = [
"same"
, "same_attrs"
# Can be used to implement interface of `same`.
# __same__ = same_{implementation}
, "same_vectors"
, "same_sets"
, "same_mappings"
]
from types import (
GeneratorType
)
from six.moves import (
zip_longest
)
from collections import (
Mapping
)
class End(objec... | nilq/baby-python | python |
from pathlib import Path
from jinja2 import Environment
from jinja2.loaders import BaseLoader
from pathlib import Path
import requests
import json
req = requests.get(r"https://raw.githubusercontent.com/thautwarm/DianaScript-JIT/master/sigs-for-builtin-modules.json")
if req.status_code != 200:
raise IOError("cannot re... | nilq/baby-python | python |
import torch
from torch.utils.data import Dataset
import numpy as np
class MNISTGraphDataset(Dataset):
def __init__(self, dataset_path, num_thresholded, train=True, intensities=True, num=-1):
if(train):
dataset_tr = np.loadtxt(dataset_path + 'mnist_train.csv', delimiter=',', dtype=np.float32)
... | nilq/baby-python | python |
# Copyright 2022 Huawei Technologies Co., Ltd
#
# 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... | nilq/baby-python | python |
from collections import Mapping, Iterable
import copy as copy_
import numpy as np
import datetime as dt
from . import misc
def select_var(d, name, sel):
var_dims = list(d['.'][name]['.dims'])
d['.'][name]['.dims'] = var_dims
for key, value in sel.items():
if isinstance(value, Mapping):
if len(sel) > 1: raise V... | nilq/baby-python | python |
import json
import os
from typing import Callable
import imageio
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pathlib
import torch
from torchvision import datasets, transforms
from torchvision.datasets.mnist import read_label_file, read_image_file
from args impor... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .models import Blogs
from .forms import Create
def add_blog(request):
if request.method == "POST":
addBlog = Create(request.POST, request.FILES)
if... | nilq/baby-python | python |
###############################################################################
# Copyright (c) 2007-2018, National Research Foundation (Square Kilometre Array)
#
# Licensed under the BSD 3-Clause License (the "License"); you may not use
# this file except in compliance with the License. You may obtain a copy
# of the ... | nilq/baby-python | python |
from typing import Sequence
from deeppavlov.models.tokenizers.utils import detokenize
from core.state_schema import Dialog
from annotators.person.person_normalizer import PersonNormalizer
class DefaultPostprocessor:
def __init__(self) -> None:
self.person_normalizer = PersonNormalizer(per_tag='PER')
... | nilq/baby-python | python |
# SPDX-FileCopyrightText: 2020 Jeff Epler for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_bitmap_font.pcf`
====================================================
Loads PCF format fonts.
* Author(s): Jeff Epler
Implementation Notes
--------------------
**Hardware:**
**Software and Dependencies... | nilq/baby-python | python |
from instapy import InstaPy
import random
from time import sleep
import subprocess
######################################
insta_username = 'your login'
insta_password = 'your password'
number_of_likes = 1200
number_of_follows = 0
number_of_comments = 250
tags = ['student', 'nature', 'river', 'forest', 'tree', 'lake',... | nilq/baby-python | python |
import argparse
import timeit
from statistics import fmean, variance
from pyformlang.cfg import Terminal
from src.cfg_algorithms import cyk
from src.cnf import WeakCNF
from src.label_graph import LabelGraph
from src.rpq import rpq, rpq_with_linear_tc
if __name__ == '__main__':
parser = argparse.ArgumentParser(
... | nilq/baby-python | python |
#!/usr/bin/env python3
#Convert EPUB files to either single HTML or text files.
#They can then be read on refreshable Braille displays, such as the Brailliant series from HumanWare or the Braille Edge by Hims.
#Also works with the Victor Reader Trek/Stream by Humanware.
#Requires pypandoc (shoutouts to @TheQuinbox on ... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
from solar_parallel import solar
from simulator import simul
##########################################
# define the class 'the simulation_plot' #
##########################################
'''
this class is used for plotting the result of the demon... | nilq/baby-python | python |
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
datasets_path = ["datasets/training", "datasets/testing", "datasets/validation"]
categories = ["RAW", "FRET", "FORCE"]
def get_main_bbox(image, threshold=100):
_, image_th = cv2.threshold(image, threshold, 65535, cv2.TH... | nilq/baby-python | python |
"""
Manage generation of maps from HEALpix tables
$Header: /nfs/slac/g/glast/ground/cvs/pointlike/python/uw/pipeline/pub/display_map.py,v 1.3 2011/06/24 04:53:06 burnett Exp $
"""
import os,sys, types, pickle
import numpy as np
import pylab as plt
from uw.utilities import image
from skymaps import Band, SkyDir, PySkyFu... | nilq/baby-python | python |
# Copyright 2019 Hewlett Packard Enterprise Development LP
# 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... | nilq/baby-python | python |
"""
Tests for PyBryt annotations
"""
import time
import numpy as np
from collections.abc import Iterable
from functools import lru_cache
from pybryt import Value
from pybryt.utils import pickle_and_hash
START_TIMESTAMP = 1614904732.51892
@lru_cache(1)
def generate_memory_footprint():
"""
"""
np.rando... | nilq/baby-python | python |
""" Exteneral Device Specifications Sub-package """
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government r... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""The Software is provided to you by the Licensor under the License, as
defined below, subject to the following condition.
Without limiting other conditions in the License, the grant of rights under
the License will not include, and the License does not grant to you, the
right to Sell the Soft... | nilq/baby-python | python |
import os
import json
pathToFolder = "c:/Users/dilGoe/Desktop/Praktikum/django"
pathToFile = "c:/Users/dilGoe/Desktop/Praktikum/django/LICENSE"
def getCorpusFolder(pathToFolder=pathToFolder):
resultDictJSON = {}
for (dirpath, dirname, filename) in os.walk(pathToFolder):
for file in filename:
... | nilq/baby-python | python |
"""Approval race condition mitigation."""
from web3.contract import Contract
def test_increase_approval(released_token: Contract, customer: str, empty_address: str, allowed_party):
"""Increase approval."""
token = released_token
amount = 5000
change = 1000
assert token.call().allowance(customer, ... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.