content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
"""
ipython -i --pdb scripts/train_model.py -- --model cropped_jan02 --data 128_20151029 --use_cropped --as_grey --overwrite --no_test
"""
import numpy as np
from lasagne.layers import dnn
import lasagne as nn
import theano.tensor as T
import theano
from utils.nolearn_net import NeuralNet
from nolearn.lasagne.handle... | nilq/baby-python | python |
from __future__ import annotations
import abc
import datetime
import decimal
import typing as t
import zoneinfo
# region: Bases
class SpecialValue(abc.ABC):
"""Represents a special value specific to an SQL Type."""
def __init__(self, python_value: t.Any, sql_value: str):
self._py_value = python_val... | nilq/baby-python | python |
"""
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
from obscmd import compat
def init():
global _global_dict
_global_dict = {}
def use_lock(key):
lock_key = key + '_lock'
if lock_key not in _global_dict:
_global_dict[lock_key] = compat.Lock()
return lock_key
def set_value(key, value):
_... | nilq/baby-python | python |
from hill import Hill
from numpy.linalg.linalg import norm
from jumper import Jumper
from jump_result import JumpResult
from physics_simulator import PhysicsSimulator
import numpy as np
import random
angles = [0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20,
22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44]
kw_pts = [... | nilq/baby-python | python |
"""
Implements a simple HTTP/1.0 Server
"""
import socket
# Define socket host and port
SERVER_HOST = '127.0.0.1'
SERVER_PORT = 7777
# Create socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((SERVER_HOST... | nilq/baby-python | python |
# coding=utf-8
#-----------------------------------------------------------
# IMPORTS
#-----------------------------------------------------------
import enigmus
import messages
import random
from entities import Entity, Player, Room
#-----------------------------------------------------------
# CLASSES
#----------... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-11-23 21:48
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('problems', '0040_auto_20161123_2106'),
]
operations... | nilq/baby-python | python |
# Ultroid - UserBot
# Copyright (C) 2021-2022 TeamUltroid
#
# This file is a part of < https://github.com/TeamUltroid/Ultroid/ >
# PLease read the GNU Affero General Public License in
# <https://www.github.com/TeamUltroid/Ultroid/blob/main/LICENSE/>.
#
# Ported by @AyiinXd
# FROM Ayiin-Userbot <https://github.com/Ayiin... | nilq/baby-python | python |
# encoding:utf-8
from flask import Flask,request
import json
import time
import sys
import sqlite3
import os
app=Flask(__name__)
####回复文本格式##########
re={}
result={}
result["type"]="text"
result["content"]=""
re["error_code"]=0
re["error_msg"]=""
re["result"]=result
dic={'温度':'temperature','湿度':'humid... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#1 - Normalize vector:
def normalize_v(V):
m = 0
for x in V: m += x**2 #Sum of the elements powered to the 2
m = sqrt(m) #Get vector's norm
return [x/m for x in V] #Divide each element of vector by its norm
#2 - Find D, euclidian distance
def euclid_dis(V... | nilq/baby-python | python |
from spaceone.inventory.manager.pricing_manager import PricingManager
| nilq/baby-python | python |
#!/usr/bin/env python
import sys
import dnfile
from hashlib import sha256
filename = sys.argv[1]
sha256hash = ''
with open(filename, 'rb') as fh_in:
sha256hash = sha256(fh_in.read()).hexdigest()
pe = dnfile.dnPE(filename)
#tbl = pe.net.mdtables.MemberRef
tbl = pe.net.mdtables.TypeRef
tbl_num_rows =\
pe.ge... | nilq/baby-python | python |
import pandas as pd
fname = "LBW_dataset.csv"
df = pd.read_csv(fname)
#cleaning data
df = df.drop(columns=['Education'])
df = df.interpolate()
df['Community'] = df['Community'].round()
df['Delivery phase'] = df['Delivery phase'].round()
df['IFA'] = df['IFA'].round()
#df = df.round()
mean_weight = df['... | 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
distri... | nilq/baby-python | python |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import logging
import numpy as np
from astropy.io import fits
from astropy.table import Table
from gammapy.data import GTI
from gammapy.maps import MapCoord, Map
from gammapy.estimators.core import FluxEstimate
from gammapy.estimators.flux_point import Flu... | nilq/baby-python | python |
from flask import Flask
from driver import get_final_kmeans
app = Flask(__name__)
@app.route("/")
def hello():
return get_final_kmeans() | nilq/baby-python | python |
from typing import Any, Dict, List, Optional, Union
from interactions.ext.paginator import Paginator
from thefuzz.fuzz import ratio
from interactions import Client, CommandContext, DictSerializerMixin, Embed, Extension
from .settings import AdvancedSettings, PaginatorSettings, TemplateEmbed, typer_dict
class RawHe... | nilq/baby-python | python |
import numpy as np
from sklearn.cluster import MeanShift# as ms
from sklearn.datasets.samples_generator import make_blobs
import matplotlib.pyplot as plt
centers = [[1,1], [5,5]]
X,y = make_blobs(n_samples = 10000, centers = centers, cluster_std = 1)
plt.scatter(X[:,0],X[:,1])
plt.show()
ms = MeanShi... | nilq/baby-python | python |
# Copyright 2020 Arthur Coqué, Valentine Aubard, Pôle OFB-INRAE ECLA, UR RECOVER
#
# 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 ... | nilq/baby-python | python |
from tkinter import *
root = Tk()
root.geometry('225x230')
root.resizable(False, False)
root.title('Learning English')
def showMenu():
menu1.pack()
menu2.pack()
def hideMenu():
menu1.pack_forget()
menu2.pack_forget()
menu1 = Button(text = 'Can you translate?\nENG --> RUS', width = 300, height = 7)
m... | nilq/baby-python | python |
import numpy as np
from time import time
import xorshift
rng = xorshift.Xoroshiro()
rng2 = xorshift.Xorshift128plus()
def output(name, start, end):
elapsed = (end - start) * 1000
per_iter = elapsed / iters
per_rv = per_iter / count * 1e6
print '%s took %.2f ms/iter, %.2f ns per float' % (name, per_ite... | nilq/baby-python | python |
from PySide2.QtCore import Qt
from PySide2.QtWidgets import QWidget, QHBoxLayout, QLabel, QSlider
from traitlets import HasTraits, Unicode, Int, observe
from regexport.views.utils import HasWidget
class LabelledSliderModel(HasTraits):
label = Unicode()
min = Int(default_value=0)
max = Int()
value = I... | nilq/baby-python | python |
'''
Configure web app settings. Updating or removing application settings will cause an app recycle.
'''
from .... pyaz_utils import _call_az
def list(name, resource_group, slot=None):
'''
Get the details of a web app's settings.
Required Parameters:
- name -- name of the web app. If left unspecified,... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Bandit Algorithms
This script follows Chapter 2 of Sutton and Barto (2nd) and simply reproduces
figures 2.2 to 2.5.
Author: Gertjan van den Burg
License: MIT
Copyright: (c) 2020, The Alan Turing Institute
"""
import abc
import math
import matplotlib.pyplot as plt
... | nilq/baby-python | python |
import unittest
import pandas as pd
from tests.test_utils import TestUtils
from enda.ml_backends.sklearn_estimator import EndaSklearnEstimator
try:
from sklearn.linear_model import LinearRegression, SGDRegressor
from sklearn.ensemble import AdaBoostRegressor, RandomForestRegressor
from sklearn.svm import S... | nilq/baby-python | python |
""" Generate new files from templates. """
import argparse
import sys
from typing import Optional
from contextlib import contextmanager
import os
import shlex
from itertools import chain
from cjrh_template import Template
import biodome
__version__ = '2017.10.3'
@contextmanager
def file_or_stdout(args, filename: Op... | nilq/baby-python | python |
import os
import paramiko
def get_private_key():
# or choose the location and the private key file on your client
private_key_file = os.path.expanduser("/home/ubuntu/.ssh/id_rsa")
return paramiko.RSAKey.from_private_key_file(private_key_file, password='')
def get_ssh(myusername, myhostname, myport):
... | nilq/baby-python | python |
import json
from unittest.mock import patch
from ddt import ddt
from django.test import tag
from django.urls import reverse
from requests.exceptions import HTTPError
from rest_framework import status
from .test_setup import TestSetUp
@tag('unit')
@ddt
class ViewTests(TestSetUp):
def test_get_catalogs(self):
... | nilq/baby-python | python |
import sys
stack = []
def recursion(stack, last):
if stack:
now = stack.pop()
else:
return -1
s = 0
while now != -last:
foo = recursion(stack, now)
if foo == -1:
return -1
s += foo
if stack:
now = stack.pop()
else:
... | nilq/baby-python | python |
from chaco.api import ArrayPlotData
from enable.component_editor import ComponentEditor
from traits.api import (
List, Instance, Either, Str, on_trait_change, Tuple, Any,
Property)
from traitsui.api import (
TabularEditor, View, UItem, VGroup, EnumEditor, HGroup, Item)
from traitsui.tabular_adapter import T... | nilq/baby-python | python |
from .device import (ORTDeviceInfo, get_available_devices_info,
get_cpu_device_info)
from .InferenceSession import InferenceSession_with_device
| nilq/baby-python | python |
#!/usr/bin/env python3
import sys
import numpy as np
with open(sys.argv[1]) as infile:
rows = [a.strip() for a in infile]
def do_round(cube):
x, y, z = cube.shape
new_cube = np.zeros(cube.shape, dtype=bool)
for i in range(x):
for j in range(y):
for k in range(z):
... | nilq/baby-python | python |
"""bsw URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-b... | nilq/baby-python | python |
from pandas import DataFrame
from typing import List, Tuple, Dict
from models.team_stats import TeamSkeletonStats
def get_opponents_in_given_fixture_list(team_id: int, fixtures: DataFrame) -> List[int]:
home_opponents = fixtures.loc[fixtures['team_a'] == team_id, 'team_h']
away_opps = fixtures.loc[fixtures['t... | nilq/baby-python | python |
#!/usr/bin/env python3
# coding:utf-8
from pickle import load
with open("banner.p", "rb") as f:
print(load(f))
| nilq/baby-python | python |
#!/usr/bin/env python
import re
from setuptools import setup
def get_version(filename):
f = open(filename).read()
return re.search("__version__ = ['\"]([^'\"]+)['\"]", f).group(1)
version = get_version('flake8_assertive.py')
description = open('README.rst').read() + "\n\n" + open('CHANGELOG.rst').read()
g... | nilq/baby-python | python |
import modules.weapon as weapon
basic_sword = weapon.Weapon("Sword", "A sword you found somewhere.", 10, 0.5, 10, "slash", 1 , "You took the sword.", "You dropped the sword.")
big_axe = weapon.Weapon("Axe", "A big axe you found somewhere.", 20, 0.5, 10, "slash", 1 , "You took the axe.", "You dropped the axe.") | nilq/baby-python | python |
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.shortcuts import get_object_or_404, redirect, render
from django.views.decorators.cache import cache_page
from .forms import CommentForm, PostForm
from .models import Follow, Group, Post, User
from .settin... | nilq/baby-python | python |
from numpy import random
from impl.distribution import distribution
class triangular(distribution):
def __init__(self, mini, mode, maxi):
self.mini = float(mini)
self.mode = float(mode)
self.maxi = float(maxi)
def generate(self):
return int(random.triangular(self.mini, self.m... | nilq/baby-python | python |
from .multiagent_particle_env import RLlibMultiAgentParticleEnv as MultiAgentParticleEnv
__all__ = [
"MultiAgentParticleEnv"
]
| nilq/baby-python | python |
from flask import abort, Flask, jsonify, request
import os
import asyncio
import pyjuicenet
import aiohttp
from prettytable import PrettyTable
from pytz import timezone
import datetime
import requests
import database_helper
import html_renderer
app = Flask(__name__)
@app.route("/")
def show_all_chargers():
datab... | nilq/baby-python | python |
import pytest
import networkx as nx
from ..pyfastg import add_node_to_digraph
def test_basic():
def check_asdf(g):
assert "asdf" in g.nodes
assert g.nodes["asdf"]["cov"] == 5.2
assert g.nodes["asdf"]["gc"] == 4 / 6.0
assert g.nodes["asdf"]["length"] == 6
def check_ghjasdf(g):
... | nilq/baby-python | python |
from rest_framework import serializers
from care.facility.api.serializers import TIMESTAMP_FIELDS
from care.facility.api.serializers.facility import FacilityBasicInfoSerializer
from care.facility.models import PatientConsultation, PatientRegistration, Facility
from care.facility.models.prescription_supplier import Pre... | nilq/baby-python | python |
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
from azure_devtools.perfstress_tests import PerfStressTest
from azure.identity import ClientSecretCredential, TokenCachePersistenceOptions
from azure.identity.aio impor... | nilq/baby-python | python |
import re, hashlib, random, json, csv, sys
from datetime import datetime, timedelta, tzinfo
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.cache import caches
from django.core.exceptions i... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-05-21 08:19
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('photos', '0005_photolikes'),
]
operations = [
migrations.RemoveField(
... | nilq/baby-python | python |
class Record:
vdict = dict()
count = 0
record = dict()
reclen = 0
fd = None
# The constructor opens the Record Defenition File and sets
# the record defenition
def __init__(self, recName, fileName, mode="r", encoding="Latin-1"):
defstr = self.recordDef(recName)
self.vdic... | nilq/baby-python | python |
import os
import posixpath
import sys
import docker
import json
from unittest import TestCase, skipUnless
from unittest.mock import Mock, call, patch, ANY
from pathlib import Path, WindowsPath
from parameterized import parameterized
from samcli.lib.build.build_graph import FunctionBuildDefinition, LayerBuildDefinit... | nilq/baby-python | python |
import requests
import json
coin_market_cap = requests.get(
"https://api.coingecko.com/api/v3/coins/markets?vs_currency=usd&order=market_cap_desc&per_page=100&page=1&sparkline=false",
headers = {"accept": "application/json"})
print("Enter the number of top cryptocurrencies by market capitalization: ")... | nilq/baby-python | python |
"""
"""
from __future__ import print_function
from abc import ABCMeta, abstractmethod
class BaseAgent:
"""
"""
__metaclass__ = ABCMeta
def __init__(self):
pass
@abstractmethod
def agent_init(self, agent_info= {}):
""" """
@abstractmethod
def agent_start(self, obser... | nilq/baby-python | python |
import torch
import gpytorch
from torch.nn.functional import softplus
from gpytorch.priors import NormalPrior, MultivariateNormalPrior
class LogRBFMean(gpytorch.means.Mean):
"""
Log of an RBF Kernel's spectral density
"""
def __init__(self, hypers = None):
super(LogRBFMean, self).__init__()
if hypers is not No... | nilq/baby-python | python |
# python
import lx, lxifc, lxu, modo
import tagger
from os.path import basename, splitext
CMD_NAME = tagger.CMD_SET_PTAG
def material_tags_list():
res = set(tagger.scene.all_tags_by_type(lx.symbol.i_POLYTAG_MATERIAL))
for type, tag in tagger.items.get_all_masked_tags():
if type == "material":
... | nilq/baby-python | python |
import turtle
'''this makes a circle by building many squares'''
def draw_square(tom):
for _ in range(4):
tom.forward(100)
tom.right(90)
def draw_flower():
window = turtle.Screen()
window.bgcolor("red")
brad = turtle.Turtle()
brad.speed(0)
brad.color("blue")
for i in rang... | nilq/baby-python | python |
class Solution:
def maxProfit(self, prices):
index = 0
flag = False
ans = 0
i = 1
n = len(prices)
while i < n:
if prices[i] > prices[i - 1]:
flag = True
else:
if flag:
ans += prices[i - 1] - p... | nilq/baby-python | python |
from bs4 import BeautifulSoup
from requests.exceptions import RequestException
from lxml import etree
import requests
import re
def get_links(who_sells=0):
# urls = []
list_view = 'http://bj.58.com/pbdn/{}/'.format(str(who_sells))
print(list_view)
wb_data = requests.get(list_view, headers=h... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import os
import json
from logging import getLogger
from six import string_types, text_type
from collections import OrderedDict
from ckan import logic
from ckan import model
import ckan.plugins as p
from ckan.lib.plugins import DefaultDatasetForm
try:
from ckan.lib.plugins import Default... | nilq/baby-python | python |
# coding=utf-8
# IP地址取自国内髙匿代理IP网站:http://www.xicidaili.com/nn/
# 仅仅爬取首页IP地址就足够一般使用
import telnetlib
from bs4 import BeautifulSoup
import requests
import random
URL = 'http://www.xicidaili.com/nn/'
HEADERS = {
'User-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.... | nilq/baby-python | python |
import struct
__all__ = ['AbstractEnumValue', 'IntValue', 'KnobModeEnum', 'PadModeEnum', 'SusModeEnum']
class AbstractEnumValue (object):
_VALUES = {}
def __init__(self, val):
if isinstance(val, int):
try:
self._value = next(k for k, v in self._VALUES.items() if v == val)... | nilq/baby-python | python |
s = input().strip()
n = int(input().strip())
a_count = s.count('a')
whole_str_reps = n // len(s)
partial_str_length = n % len(s)
partial_str = s[:partial_str_length]
partial_str_a_count = partial_str.count('a')
print(a_count * whole_str_reps + partial_str_a_count)
| nilq/baby-python | python |
import asyncio
import math
import networkx as nx
from ccxt import async_support as ccxt
import warnings
__all__ = [
'create_multi_exchange_graph',
'create_weighted_multi_exchange_digraph',
'multi_graph_to_log_graph',
]
def create_multi_exchange_graph(exchanges: list, digraph=False):
"""
Returns a ... | nilq/baby-python | python |
"""Methods for creating, manipulating, and storing Teradata row objects."""
import csv
from claims_to_quality.lib.qpp_logging import logging_config
from claims_to_quality.lib.teradata_methods import deidentification
import teradata
logger = logging_config.get_logger(__name__)
def csv_to_query_output(csv_path):
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2010 British Broadcasting Corporation and Kamaelia Contributors(1)
#
# (1) Kamaelia Contributors are listed in the AUTHORS file and at
# http://www.kamaelia.org/AUTHORS - please extend this file,
# not this notice.
#
# Licensed under the Apache License... | nilq/baby-python | python |
# Copyright 2021 AIPlan4EU project
#
# 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 wri... | nilq/baby-python | python |
preco = float(input('Qual o valor do produto ? R$ '))
porcentagem = float(input('Qual a porcentagem ? '))
calculo = preco - (preco * porcentagem / 100)
print(f'O produto que custava R${preco}, na promoção com desconto de {porcentagem}% vai custar {calculo:.2f}') | nilq/baby-python | python |
import json
import logging
from unittest import mock
from django.test import TestCase
from djenga.logging.formatters import JsonFormatter, JsonTaskFormatter
__all__ = [ 'JsonFormatterTest', ]
log = logging.getLogger(__name__)
class JsonFormatterTest(TestCase):
def test_json_formatter(self):
formatter = ... | nilq/baby-python | python |
#!/usr/bin/env python3
'''
booksdatasource.py
Jeff Ondich, 21 September 2021
For use in the "books" assignment at the beginning of Carleton's
CS 257 Software Design class, Fall 2021.
'''
#Revised by Thea Traw
import csv
class Author:
def __init__(self, surname='', given_name='', birth_year=None,... | nilq/baby-python | python |
/home/wai/anaconda3/lib/python3.6/copy.py | nilq/baby-python | python |
import pytest
from ergaster import add
data = (
(1, 2, 3),
(2, 2, 4),
(3, 2, 5),
)
@pytest.mark.parametrize("x, y, res", data)
def test_add(x, y, res):
assert add(x, y) == res
| nilq/baby-python | python |
def grafoSimples(matriz):
result = ""
l = 0
am = 0
for linha in range(len(matriz)):
for coluna in range(len(matriz[linha])):
if(linha == coluna and matriz[linha][coluna] == 2):
result+=("Há laço no vertice %s\n" %(linha+1))
l = 1
if (linha... | nilq/baby-python | python |
# coding=UTF-8
from django.db import models
from django.utils.translation import ugettext, ugettext_lazy as _
from django.utils.encoding import python_2_unicode_compatible
from product.models import TaxClass
from l10n.models import AdminArea, Country
#from satchmo_store.shop.models import Order
#from satchmo_store.sho... | nilq/baby-python | python |
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import colorcet as cc
import datashader as ds
import datashader.utils as utils
import datashader.transfer_functions as tf
sns.set(context="paper", style="white")
data_dir = os.path.abspath("./data")
data_fname = ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from .base_settings import *
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
ALLOWED_HOSTS = ['*']
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
FOP_EXECUTABLE = "C:/U... | nilq/baby-python | python |
import json
from dagster import ModeDefinition, execute_solid, solid
from dagster_slack import slack_resource
from mock import patch
@patch("slack.web.base_client.BaseClient._perform_urllib_http_request")
def test_slack_resource(mock_urllib_http_request):
@solid(required_resource_keys={"slack"})
def slack_so... | nilq/baby-python | python |
# Copyright (c) 2011-2020 Eric Froemling
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish,... | nilq/baby-python | python |
#!/usr/bin/env python
from avro.io import BinaryEncoder, BinaryDecoder
from avro.io import DatumWriter, DatumReader
import avro.schema
from io import BytesIO
import argo_ams_library
from argo_ams_library import ArgoMessagingService
import argparse
import base64
import logging
import logging.handlers
import sys
import ... | nilq/baby-python | python |
from datetime import datetime
from itertools import chain
from random import randint
from django.contrib.auth.decorators import login_required
from django.contrib.formtools.wizard.views import SessionWizardView
from django.http import HttpResponseRedirect, Http404, HttpResponse
from django.utils.decorators impo... | nilq/baby-python | python |
'''
visualize VIL-100 datasets in points form or curves form.
datasets name:vil-100
paper link: https://arxiv.org/abs/2108.08482
reference: https://github.com/yujun0-0/MMA-Net/tree/main/dataset
datasets structure:
VIL-100
|----Annotations
|----data
|----JPEGImages
|----Json
|----trai... | nilq/baby-python | python |
from __future__ import print_function
import os
import re
import sqlite3
import sys
import traceback
import simpy
from vcd import VCDWriter
from . import probe
from .util import partial_format
from .timescale import parse_time, scale_time
from .queue import Queue
from .pool import Pool
class Tracer(object):
na... | nilq/baby-python | python |
from pyhafas.profile import ProfileInterface
from pyhafas.profile.interfaces.helper.parse_lid import ParseLidHelperInterface
from pyhafas.types.fptf import Station
class BaseParseLidHelper(ParseLidHelperInterface):
def parse_lid(self: ProfileInterface, lid: str) -> dict:
"""
Converts the LID given... | nilq/baby-python | python |
from __future__ import print_function, absolute_import
import torch
from torch.optim.lr_scheduler import _LRScheduler
from bisect import bisect_right
AVAI_SCH = ['single_step', 'multi_step', 'cosine', 'multi_step_warmup']
def build_lr_scheduler(optimizer,
lr_scheduler='single_step',
... | nilq/baby-python | python |
"""
File: rocket.py
Name:Claire Lin
-----------------------
This program should implement a console program
that draws ASCII art - a rocket.
The size of rocket is determined by a constant
defined as SIZE at top of the file.
Output format should match what is shown in the sample
run in the Assignment 2 Handout.... | nilq/baby-python | python |
from enum import Enum
class RecipeStyle(Enum):
"""
Class for allrecipes.com style labels
"""
diabetic = 'diabetic'
dairy_free = 'dairy_free'
sugar_free = 'sugar-free'
gluten_free = 'gluten_free'
low_cholesterol = 'low_cholesterol'
mediterranean = 'mediterranean'
chinese = 'chin... | nilq/baby-python | python |
from typing import Union, List, Optional
from pyspark.sql.types import StructType, StructField, StringType, ArrayType, DataType
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Naming
class ImplementationGuide_PageSchema:
"""
A set of rules of how FHIR is used to ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.7 on 2017-11-15 01:52
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
... | nilq/baby-python | python |
from rallf.sdk.logger import Logger
from rallf.sdk.network import Network
from rallf.sdk.listener import Listener
class Task:
def __init__(self, manifest, robot, input, output):
self.manifest = manifest
self.robot = robot
self.finished = False
self.status = "stopped"
self.... | nilq/baby-python | python |
from django.urls import re_path
from . import views
urlpatterns = [
re_path(r'^$',
views.IndexView.as_view(),
name='index'),
re_path(r'^(?P<pk>[-\w]+)/$',
views.PageDetailView.as_view(),
name='page_detail'),
]
| nilq/baby-python | python |
import unittest
import time
from liquidtap.client import Client
class TestClient(unittest.TestCase):
def setUp(self) -> None:
self.client = Client()
self.client.pusher.connection.bind('pusher:connection_established', self._on_connect)
def _on_connect(self, data: str):
print('on_conne... | nilq/baby-python | python |
class NopBackpressureManager:
def __init__(self):
pass
def register_pressure(self):
pass
def unregister_pressure(self):
pass
def reached(self) -> bool:
return False
class BackpressureManager:
def __init__(self, max):
self.max = max
self.pressure... | nilq/baby-python | python |
import re
import croniter
from datetime import timedelta, datetime
from functools import partial
from airflow import DAG
from airflow.sensors.external_task import ExternalTaskSensor
from dagger import conf
from dagger.alerts.alert import airflow_task_fail_alerts
from dagger.dag_creator.airflow.operator_factory import... | nilq/baby-python | python |
from __future__ import absolute_import
from collections import defaultdict, Sequence, OrderedDict
import operator
from string import capwords
import numpy as np
from .elements import ELEMENTS
# records
MODEL = 'MODEL '
ATOM = 'ATOM '
HETATM = 'HETATM'
TER = 'TER '
MODEL_LINE = 'MODEL ' + ' ' * 4 + '{:>4d}\n'
END... | nilq/baby-python | python |
# Copyright 2017-2020 TensorHub, 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 writ... | nilq/baby-python | python |
"""Module for raceplan exceptions."""
class CompetitionFormatNotSupportedException(Exception):
"""Class representing custom exception for command."""
def __init__(self, message: str) -> None:
"""Initialize the error."""
# Call the base class constructor with the parameters it needs
su... | nilq/baby-python | python |
################ Running: F:\users\emiwar\edited_new\catAtt.py #################
COM1
Serial<id=0x52b47f0, open=True>(port='COM1', baudrate=115200, bytesize=8, parity='N', stopbits=1, timeout=2.5, xonxoff=False, rtscts=False, dsrdtr=False)
492
1 False [('b', 1.378630934454577)]
1 finished.
2 desert [('b', 1.37283... | nilq/baby-python | python |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: server_admin.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _... | nilq/baby-python | python |
import tensorflow as tf
from tensorflow.keras.applications import InceptionV3
__all__ = ["inception_score"]
def inception_score(images):
r"""
Args:
images: a numpy array/tensor of images. Shape: NxHxWxC
Return:
inception score
"""
img_shape = images.shape
if img_shape[1] !=... | nilq/baby-python | python |
from django.dispatch import receiver
from django.db.models.signals import post_save, post_delete
from django.core.mail import send_mail
from .models import Profile
from django.conf import settings
SUBJECT = 'WELCOME TO DEVCONNECT'
MESSAGE = """ Congratulation I have to say thank you for creating a new account
with our... | nilq/baby-python | python |
"""
Setup file for installation of the dataduct code
"""
from setuptools import find_packages
from setuptools import setup
from dataduct import __version__ as version
setup(
name='dataduct',
version=version,
author='Coursera Inc.',
packages=find_packages(
exclude=["*.tests", "*.tests.*", "test... | nilq/baby-python | python |
import re
f = open("regex.txt", "r")
content = f.readlines()
# s = 'A message from cs@uni.edu to is@uni.edu'
for i in range(len(content)):
if re.findall('[\w\.]+@[\w\.]+', content[i]):
print(content[i], end='') | nilq/baby-python | python |
"""
Command-line interface implementing synthetic MDS Provider data generation:
- custom geographic area, device inventory, time periods
- generates complete "days" of service
- saves data as JSON files to container volume
All fully customizable through extensive parameterization and configuration options.
"""
... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.