content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
"""
The wntr.network package contains methods to define a water network model,
network controls, and graph representation of the network.
"""
from wntr.network.model import WaterNetworkModel, Node, Link, Junction, Reservoir, Tank, Pipe, Pump, Energy, Valve, Curve, LinkStatus, WaterNetworkOptions, LinkType, NodeType
fro... | nilq/baby-python | python |
import cv2
img = cv2.imread("dog.jpg")
cv2.imshow("dog", img)
cv2.waitKey()
cv2.destroyAllWindows()
| nilq/baby-python | python |
#-*- coding: utf-8 -*-
# https://github.com/Kodi-vStream/venom-xbmc-addons
#test film strem vk 1er page dark higlands & tous ces enfants m'appartiennent
from resources.hosters.hoster import iHoster
from resources.lib.handler.requestHandler import cRequestHandler
from resources.lib.parser import cParser
import re
UA = ... | nilq/baby-python | python |
__author__ = 'Richard Lincoln, r.w.lincoln@gmail.com'
""" This example demonstrates how to use the discrete Roth-Erev reinforcement
learning algorithms to learn the n-armed bandit task. """
import pylab
import scipy
from pybrain.rl.agents import LearningAgent
from pybrain.rl.explorers import BoltzmannExplorer #@Unus... | nilq/baby-python | python |
import abc
from enum import Enum as EnumCLS
from typing import Any, List, Optional, Tuple, Type
import pendulum
from starlette.requests import Request
from mongoengine import Document
from mongoengine import QuerySet
from fastapi_admin import constants
from fastapi_admin.widgets.inputs import Input
class Filter(Inp... | nilq/baby-python | python |
from itertools import chain
from functools import lru_cache
import abc
import collections
from schema import Schema
from experta.pattern import Bindable
from experta.utils import freeze, unfreeze
from experta.conditionalelement import OperableCE
from experta.conditionalelement import ConditionalElement
class BaseFi... | nilq/baby-python | python |
from tensorflow.keras.models import Sequential
import tensorflow.keras.layers as layers
import numpy as np
from os.path import join
import os
from invoke.context import Context
import unittest
import templates
import ennclave_inference as ennclave
import config as cfg
def common(backend: str):
target_dir = join(... | nilq/baby-python | python |
import numpy as np
import os
import time
from . import util
from tensorboardX import SummaryWriter
import torch
class TBVisualizer:
def __init__(self, opt):
self._opt = opt
self._save_path = os.path.join(opt.checkpoints_dir, opt.name)
self._log_path = os.path.join(self._save_path, 'loss_l... | nilq/baby-python | python |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import argparse
import pandas as pd
from funcs import shortpath
def print_inp(inp_file_name):
inp_file_full = pd.read_csv(inp_file_name, sep='\t', header=1, dtype=str)
for j in range(len(inp_file_full)):
inp_file = inp_file_full.loc[[j], :]
... | nilq/baby-python | python |
format = "%(asctime)s - %(levelname)s - %(name)s - %(message)s"
minimal_format = "%(message)s"
def _get_formatter_and_handler(use_minimal_format: bool = False):
logging_dict = {
"version": 1,
"disable_existing_loggers": True,
"formatters": {
"colored": {
"()": "... | nilq/baby-python | python |
import argparse
import json
import os
import shutil
import logging
from weed_annotator.semantic_segmentation import utils
from weed_annotator.semantic_segmentation.train import train
from weed_annotator.semantic_segmentation.inference import inference
from weed_annotator.post_processing.post_process_masks import post... | nilq/baby-python | python |
"""
This module contains helper functions.
The main purpose is to remove clutter in the main
file
"""
from __future__ import print_function
import argparse
import sys
import os
import logging
import copy
import subprocess
from operator import attrgetter
from string import Formatter
try:
# Python 3
import _str... | nilq/baby-python | python |
"""
Use to populate:
from crs.populate_crs_table import CrsFromApi
crs_api = CrsFromApi()
crs_api.populate()
"""
import re
import math
from bills.models import Bill
from crs.scrapers.everycrsreport_com import EveryCrsReport
# Bill's types {'sres', 'hjres', 'hconres', 's', 'hres', 'sjres', 'hr', 'sconres'}
BILL_NUMBER... | nilq/baby-python | python |
import os
import numpy as np
import pandas as pd
from trackml.dataset import load_event
from trackml.score import score_event
from sklearn.preprocessing import StandardScaler
from sklearn.cluster import DBSCAN
class Clusterer(object):
def __init__(self, eps):
self.eps = eps
def _preprocess(self, h... | nilq/baby-python | python |
"""
This module encapsulates QCoDeS database: its schema, structure, convenient
and relevant queries, wrapping around :mod:`sqlite3`, etc.
The dependency structure of the sub-modules is the following:
::
.connection .settings
/ | \ |
/ | \ |
/ |... | nilq/baby-python | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# vim: fenc=utf-8
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
#
"""
File name: constants.py
Author: dhilipsiva <dhilipsiva@gmail.com>
Date created: 2016-11-20
"""
class QuestionType(object):
UNKNOWN = -1
MULTIPLE_CHOICE = 0
CHOICE = 1
BOOLE... | nilq/baby-python | python |
"""
author:xing xiangrui
test os.system()
"""
import os
os.chdir("mAP/")
#os.system("cd mAP/")
os.system("python main.py -na") | nilq/baby-python | python |
'''
Author : ZHP
Date : 2022-04-12 16:00:40
LastEditors : ZHP
LastEditTime : 2022-04-12 17:01:01
FilePath : /models/PointFormer/similarity.py
Description :
Copyright 2022 ZHP, All Rights Reserved.
2022-04-12 16:00:40
'''
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys... | nilq/baby-python | python |
import re
import pytest
from perl.translator import translate_string
from perl.utils import re_match, reset_vars
@pytest.fixture
def _globals():
return {"re": re, "__perl__re_match": re_match, "__perl__reset_vars": reset_vars}
def test_match__value_present__returns_true(_globals):
ldict = {"var": "one foo... | nilq/baby-python | python |
# Authors: Stephane Gaiffas <stephane.gaiffas@gmail.com>
# License: BSD 3 clause
"""This modules introduces the Dataset class allowing to store a binned features matrix.
It uses internally a bitarray to save the values of the features in a memory efficient
fashion. It exploits the fact that any columns j of the featu... | nilq/baby-python | python |
import numpy as np
from sklearn.metrics.pairwise import pairwise_distances
try:
from bottleneck import argpartsort
except ImportError:
try:
# Added in version 1.8, which is pretty new.
# Sadly, it's still slower than bottleneck's version.
argpartsort = np.argpartition
except AttributeError:
argpa... | nilq/baby-python | python |
#!/usr/bin/env python3
#-----------------------------------------------------------------------------
# This file is part of the rogue_example software. It is subject to
# the license terms in the LICENSE.txt file found in the top-level directory
# of this distribution and at:
# https://confluence.slac.stanford.e... | nilq/baby-python | python |
# Generated by Django 2.2 on 2019-05-18 19:06
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = []
operations = [
migrations.CreateModel(
name="CIPRSRecord",
fields=[... | nilq/baby-python | python |
retrieve = [
{"scenario":"Patient Exists","patient":"9000000009", "response":{"address":[{"extension":[{"extension":[{"url":"type","valueCoding":{"code":"PAF","system":"https://fhir.nhs.uk/R4/CodeSystem/UKCore-AddressKeyType"}},{"url":"value","valueString":"12345678"}],"url":"https://fhir.nhs.uk/R4/StructureDefinit... | nilq/baby-python | python |
from django.contrib import admin
from . models import Ads
class AdsAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
admin.site.register(Ads, AdsAdmin)
| nilq/baby-python | python |
#write import statement for Die class
from src.homework.homework9.die import Die
'''
Create a Player class.
'''
class Player:
def __init__(self):
'''
Constructor method creates two Die attributes die1 and die2
'''
self.die1 = Die()
self.die2 = Die()
def roll_doubles... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This is needed as multiprocessing shouldn't include nsz
# as it won't be able to optain __main__.__file__ and so crash inside Keys.py
if __name__ == '__main__':
import sys
if sys.hexversion < 0x03060000:
raise ImportError("NSZ requires at least Python 3.6!\nCurrent ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI 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 ... | nilq/baby-python | python |
from datetime import datetime
from unittest import mock
import dateutil.relativedelta
from carbonserver.api.infra.repositories.repository_projects import SqlAlchemyRepository
from carbonserver.api.usecases.project.project_sum import ProjectSumsUsecase
PROJECT_ID = "e60afa92-17b7-4720-91a0-1ae91e409ba1"
END_DATE = da... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
'''
Created on 2017-6-22
@author: hshl.ltd
'''
from __future__ import absolute_import, unicode_literals
import warnings
from sqlalchemy import orm
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from django.conf import settings
fr... | nilq/baby-python | python |
import os
import requests
from dotenv import load_dotenv
dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
load_dotenv(dotenv_path)
# how to generate URL https://www.youtube.com/watch?v=lEQ68HhpO4g
INCOMING_WEBHOOKS_ACCESS_URL=os.getenv("INCOMING_WEBHOOKS_ACCESS_URL")
def send_message(post_data, api_u... | nilq/baby-python | python |
import os
import sys
import random
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn.functional as F
import torch.nn as nn
import torchvision
import torchvision.transforms as transforms
import torchvision.utils
import imgaug as ia
from torch.utils.data import DataLoader,Dataset
from torch.... | nilq/baby-python | python |
from django.http import Http404
from django.test.testcases import TestCase
from corehq.apps.app_manager.models import (
AdvancedModule,
Application,
BuildProfile,
GlobalAppConfig,
LatestEnabledBuildProfiles,
Module,
)
from corehq.apps.app_manager.views.utils import get_default_followup_form_xml... | nilq/baby-python | python |
# Gradient Norm Scaling/Clipping
from keras import optimizers
# configure sgd with gradient norm scaling
# i.e. changing the derivatives of the loss function to have a given vector norm when
# the L2 vector norm (sum of the squared values) of the gradient vector exceeds
# a threshold value.
opt = optimizers.SGD(lr=0.0... | nilq/baby-python | python |
class DEQue:
__slots__ = '_length', '_data'
def __init__(self):
self._length = 0
self._data = []
def __len__(self):
return self._length
def is_empty(self):
return len(self) == 0
def first(self):
if self.is_empty():
print('DEQue is em... | nilq/baby-python | python |
from tcprecord import TCPRecord, TCPRecordStream
from httprecord import HTTPRecordStream
from tcpsession import TCPSession, tcp_flags, SeqException
from httpsession import parse_http_streams, HTTPParsingError, HTTPResponse, HTTPRequest
from errors import *
import sys
import printing
from printing import print_tcp_sess... | nilq/baby-python | python |
from .fid import FIDScore
| nilq/baby-python | python |
# Copyright 2016 Ifwe 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, so... | nilq/baby-python | python |
"""
A file just to hold the version number, allows automated version increasing.
"""
SEMANTIC = '0.1.4-SNAPSHOT'
BUILD_TIME = 'UNKNOWN'
try:
with open('build-time.txt') as f:
CONTENTS = f.readline().rstrip()
if CONTENTS:
BUILD_TIME = CONTENTS
except IOError:
pass
| nilq/baby-python | python |
import unittest
from iterable_collections import collect
class TestMap(unittest.TestCase):
def test_list(self):
c = collect(list(range(10))).map(lambda x: x + 1)
self.assertEqual(c.list(), list(map(lambda x: x + 1, list(range(10)))))
def test_lists(self):
c = collect(list(range(10))... | nilq/baby-python | python |
# Copyright 2016 Joel Dunham
#
# 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 writi... | nilq/baby-python | python |
# Software License Agreement (BSD License)
#
# Copyright (c) 2018, Fraunhofer FKIE/CMS, Alexander Tiderko
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code mu... | nilq/baby-python | python |
# Generated by Django 3.0.2 on 2021-05-11 11:21
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('banks', '0002_bankcode_otp_enabled'),
('loans', '0021_loanrequests'),
]
operations = [
migrations.C... | nilq/baby-python | python |
#!/usr/bin/env python3
from argparse import ArgumentParser, FileType
from collections import OrderedDict
from datetime import datetime
import logging
from json import dumps
from sys import stdout
from time import sleep
from coloredlogs import install as coloredlogs_install
from ssnapshot.ssnapshot import (
creat... | nilq/baby-python | python |
import itk
import numpy as np
from segmantic.prepro import core
from segmantic.prepro.core import make_image
def test_extract_slices(labelfield: core.Image3) -> None:
slices_xy = core.extract_slices(labelfield, axis=2)
assert slices_xy[0].GetSpacing()[0] == labelfield.GetSpacing()[0]
assert slices_xy[0... | nilq/baby-python | python |
"""
Fetch dependencies and build a Windows wheel
============================================
This script depends on pycairo being installed to provide cairo.dll; cairo.dll
must have been built with FreeType support.
The cairo headers (and their dependencies) are fetched from the Arch Linux
repositories (the official... | nilq/baby-python | python |
#!/usr/bin/env python3
# encoding: utf-8
"""
This module contains unit tests for the arc.main module
"""
import os
import shutil
import unittest
from arc.common import ARC_PATH
from arc.exceptions import InputError
from arc.imports import settings
from arc.main import ARC, StatmechEnum, process_adaptive_levels
from ... | nilq/baby-python | python |
b = 1
for i in range(100000):
b += i * b
print(b)
| nilq/baby-python | python |
import sys, os, math, random, time, zlib, secrets, threading, time, asyncio
async def say_after(delay, what):
await asyncio.sleep(delay)
return what
async def main():
taskvec=[]
for i in range(10):
taskvec.append(asyncio.create_task(say_after(i,str(i))))
print(f"started at {time.strftim... | nilq/baby-python | python |
# Copyright 2021 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 django.urls import reverse
from rest_framework import status
from django.test import TestCase
from .models import CustomUser
from .serializers import UserDetailsSerializer
from rest_framework.test import APIClient
REGISTRATION_URL = reverse('rest_register')
LOGIN_URL = reverse('rest_login')
PASSWORD_CHANGE_URL = ... | nilq/baby-python | python |
print("Please give termination parameter as zero to proceed with number of iterations.")
x = list()
x1, d, e = map(float, input(
"Enter initial point, delta and termination parameter: ").split())
expr = input("Enter expression for x: ")
print("Please give no. of iterations as considerably a high number to check wit... | nilq/baby-python | python |
from bs4 import BeautifulSoup
from faker import Faker
import requests
class faceFarm():
def __init__(self) -> None:
super(faceFarm, self).__init__()
self.requests = requests.Session()
pass
def request(self, method, url, **kwargs):
try:
return self.requests.request(... | nilq/baby-python | python |
var1 = int(input('Digite um número: '))
print('Analizando o valor {}, seu antecessor é o {} e o seu sucessor é {}'.format(var1, var1-1, var1+1))
| nilq/baby-python | python |
import pathlib
import aiosql
queries = aiosql.from_path(pathlib.Path(__file__).parent / "sql", "asyncpg")
| nilq/baby-python | python |
dollars=eval(input("Enter in a value of Dollars:"))
def main():
euros=dollars*0.8007
euros=round(euros,2)
print("That is exactly",euros,"euros.")
main() | nilq/baby-python | python |
import logging
from functools import partial
from typing import TYPE_CHECKING, Optional
from magicgui.widgets import create_widget
from napari.qt.threading import thread_worker
from napari_plugin_engine import napari_hook_implementation
from qtpy.QtCore import QEvent, Qt
from qtpy.QtWidgets import (
QCheckBox,
... | nilq/baby-python | python |
"""Methods for projecting a feature space to lower dimensionality."""
from .factory import create_projector, IDENTIFIERS, DEFAULT_IDENTIFIER # noqa: F401
from .projector import Projector # noqa: F401
| nilq/baby-python | python |
import numpy as np
from sklearn.metrics import pairwise_distances
from sklearn.metrics.pairwise import cosine_similarity, euclidean_distances, haversine_distances, chi2_kernel, \
manhattan_distances
class Similarity(object):
"""
Simple kNN class
"""
def __init__(self, data, user_profile_matrix, ... | nilq/baby-python | python |
from enum import Enum
from typing import Optional, Sequence
from PyQt5 import QtCore, QtWidgets
from electroncash.address import Address, AddressError
from electroncash.consolidate import (
MAX_STANDARD_TX_SIZE,
MAX_TX_SIZE,
AddressConsolidator,
)
from electroncash.constants import PROJECT_NAME, XEC
from ... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# データセットの交差検証
import pandas as pd
import numpy as np
import dataclasses
from collections import defaultdict
from .utils.folder import folder_create
from tqdm import tqdm
@dataclasses.dataclass
class Stratified_group_k_fold:
"""
データをグループ層化K分割すると... | nilq/baby-python | python |
import numpy as np
from tqdm import tqdm
class PaddingInputExample(object):
"""Fake example so the num input examples is a multiple of the batch size.
When running eval/predict on the TPU, we need to pad the number of examples
to be a multiple of the batch size, because the TPU requires a fixed batch
size. T... | nilq/baby-python | python |
from typing import List
import metagrad.module as nn
from examples.feedforward import load_dataset
from metagrad.dataloader import DataLoader
from metagrad.dataset import TensorDataset
from metagrad.functions import sigmoid
from metagrad.loss import BCELoss
from metagrad.optim import SGD
from metagrad.paramater import... | nilq/baby-python | python |
from functools import wraps
from ..exceptions import BeeSQLError
def primary_keyword(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
if not self.table:
raise BeeSQLError('No table selected. Use Query.on to select a table first')
statement = func(self, *args, **kwargs)
... | nilq/baby-python | python |
"""
Relationship pseudo-model.
"""
class Relationship:
def __init__(self, start_id, end_id, type, properties):
"""
A relationship (edge) in a property graph view of data.
:param {str} start_id: unique id of the 'from' node in the graph this relationship is associated with
:param... | nilq/baby-python | python |
# Number of Islands
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if not any(grid): return 0
m, n = len(grid), len(grid[0])
count = 0
for i in range(m):
for j in range(n):
... | nilq/baby-python | python |
from parameterized import parameterized
from combinatrix.testintegration import load_parameter_sets
from doajtest.helpers import DoajTestCase
from doajtest.fixtures import JournalFixtureFactory, ArticleFixtureFactory
from doajtest.mocks.store import StoreMockFactory
from doajtest.mocks.model_Cache import ModelCacheMoc... | nilq/baby-python | python |
from flask import Flask, jsonify, request
app = Flask(__name__)
@app.route('/', methods=['GET'])
def hello_world():
#return 'Hello, World!'
response = ""
term = request.args['term']
if term:
items = [ "c++", "java", "php", "coldfusion", "javascript", "asp", "ruby", "perl", "ocaml", "haskell", "... | nilq/baby-python | python |
"""Flsqls module."""
from pineboolib.core import decorators
from pineboolib.core.utils import utils_base
from pineboolib.application.metadata import pntablemetadata
from pineboolib import logging
from pineboolib.fllegacy import flutil
from pineboolib.interfaces import isqldriver
from sqlalchemy.orm import sessionm... | nilq/baby-python | python |
"""
Copyright 2021 Gabriele Pisciotta - ga.pisciotta@gmail.com
Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted,
provided that the above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTH... | nilq/baby-python | python |
import re
from .models import Profile, Link
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.utils.module_loading import import_string
from django.contrib.sites.shortcuts import get_current_site
from django.contrib.auth.models import User
from django.contrib.auth impo... | nilq/baby-python | python |
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import os
from pathlib import Path
from subprocess import run
import nltk
def rebuild_custom_ops():
"""The objective of this script is to:
1.) Delete the existing custom ops if it exists
2.) Perform the make command
3.) Validate a custom_ops.s... | nilq/baby-python | python |
from tortoise import Tortoise
from tortoise.contrib import test
from tortoise.exceptions import OperationalError, ParamsError
from tortoise.tests.testmodels import Event, EventTwo, TeamTwo, Tournament
from tortoise.transactions import in_transaction, start_transaction
class TestTwoDatabases(test.SimpleTestCase):
... | nilq/baby-python | python |
from Instrucciones.Instruccion import Instruccion
from Instrucciones.Declaracion import Declaracion
from Expresion.Terminal import Terminal
from Tipo import Tipo
class Procedure(Instruccion):
def __init__(self,nombre,params,instrucciones):
self.nombre=nombre
self.params=params
self.instruc... | nilq/baby-python | python |
"""
This example shows how to upload a model with customized csv schedules
Put all the relevant schedules under one folder
and then add the folder directory to the add_files parameter.
"""
import BuildSimHubAPI as bshapi
import BuildSimHubAPI.postprocess as pp
bsh = bshapi.BuildSimHubAPIClient()
project_api_key = 'f... | nilq/baby-python | python |
# Generated by Django 3.2.11 on 2022-01-12 08:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('index', '0004_auto_20201221_1213'),
]
operations = [
migrations.AlterField(
model_name='broadcast',
name='id',
... | nilq/baby-python | python |
from pyrosm.data_manager import get_osm_data
from pyrosm.frames import prepare_geodataframe
import warnings
def get_network_data(node_coordinates, way_records, tags_as_columns,
network_filter, bounding_box):
# Tags to keep as separate columns
tags_as_columns += ["id", "nodes", "timestamp"... | nilq/baby-python | python |
class UnionFind(object):
def __init__(self, n):
self.u = list(range(n))
def union(self, a, b):
ra, rb = self.find(a), self.find(b)
if ra != rb:
self.u[ra] = rb
def find(self, a):
while self.u[a] != a:
a = self.u[a]
return a
class Solution(ob... | nilq/baby-python | python |
for _ in range(int(input())):
n = int(input())
s = input()
alpha = set(s)
ans = n
countImpossible = 0
for i in alpha:
curr = 0
lb, ub = 0, n - 1
while lb < ub:
if s[lb] == s[ub]:
lb += 1
ub -= 1
continue
... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright (c) 2020, Xiaotian Derrick Yang
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
"""Package build and install script."""
from setuptools import find_packages, setup
def get_re... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Description
"""
import torch
from scipy import stats
from ptranking.metric.adhoc_metric import torch_ap_at_ks, torch_nDCG_at_ks, torch_kendall_tau, torch_nerr_at_ks
def test_ap():
''' todo-as-note: the denominator should be carefully checked when using AP@k '... | nilq/baby-python | python |
import logging
from kubernetes import client
from kubernetes.client import V1beta1CustomResourceDefinition, V1ObjectMeta, V1beta1CustomResourceDefinitionSpec, \
V1Deployment, V1DeploymentSpec, V1LabelSelector, V1PodTemplateSpec, V1PodSpec, V1Service, V1ServiceSpec, \
V1ServicePort, V1DeleteOptions, V1Persisten... | nilq/baby-python | python |
# Generated by Django 2.1.5 on 2019-01-28 03:31
from django.db import migrations
import jsonfield.fields
class Migration(migrations.Migration):
dependencies = [
('configurations', '0017_d3mconfiguration_description'),
]
operations = [
migrations.AddField(
model_name='d3mconf... | nilq/baby-python | python |
from agrirouter.auth.enums import BaseEnum
class CertificateTypes(BaseEnum):
PEM = "PEM"
P12 = "P12"
class GateWays(BaseEnum):
MQTT = "2"
REST = "3"
| nilq/baby-python | python |
"""yaml templates for DataFrame plotting."""
from os.path import (join, dirname)
import yaml
_filename = join(dirname(__file__), 'palette.yaml')
with open(_filename, 'r') as f:
lineplot_dict = yaml.load(f, Loader=yaml.SafeLoader)
style_overide = lineplot_dict.pop('style_overide', {})
__all__ = ['lineplot_dic... | nilq/baby-python | python |
#!/usr/bin/env python3
# Importation des librairies TM1637 et time
from tm1637 import TM1637
from time import sleep
# Stockage de la duree dans des variables
print("- Duree du minuteur -")
minutes = int(input("Minutes : "))
secondes = int(input("Secondes : "))
print("- Demarage du minuteur : " + str(minutes... | nilq/baby-python | python |
from unittest import TestCase
from daily_solutions.year_2020.day_5 import parse_seat_id
class Day5TestCase(TestCase):
def test_parse_row_column(self) -> None:
self.assertEqual(567, parse_seat_id("BFFFBBFRRR"))
| nilq/baby-python | python |
from flask_wtf import FlaskForm
from wtforms import (
widgets,
HiddenField,
BooleanField,
TextField,
PasswordField,
SubmitField,
SelectField,
SelectMultipleField,
DateTimeField,
)
from wtforms.validators import Email, Length, Required, EqualTo, Optional
day_map = {
"0": "Mon",
... | nilq/baby-python | python |
# File: __init__.py
# Aim: Package initial
# Package version: 1.0
# %%
from .defines import Config
CONFIG = Config()
# CONFIG.reload_logger(name='develop')
# %%
| nilq/baby-python | python |
from dataclasses import dataclass
from enum import Enum
class TokenEnum(Enum):
LPAREN = 0
RPAREN = 1
NUMBER = 2
PLUS = 3
MINUS = 4
MULTIPLY = 5
DIVIDE = 6
INTEGRAL_DIVIDE = 7
EXPONENTIAL = 8
@dataclass
class Token:
type: TokenEnum
val: any = None
def __repr__(self):
... | nilq/baby-python | python |
#-------------------------------------------------------------------------------
import collections
import copy
import warnings
import inspect
import logging
import math
#-------------------------------------------------------------------------------
class MintError(Exception): pass
class MintIndexError(MintError): pa... | nilq/baby-python | python |
"""Remote"""
from os import path
import uuid
import time
import json
import tornado.ioloop
import tornado.websocket
import tornado.web
from models.led_strip import LedStrip
from models.color import Color
strip = LedStrip(14)
def start():
"""animation"""
strip.stop_animation()
print("start_animation")
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from unittest import TestCase
class DataTest(TestCase):
"""Obey the testing goat."""
def test_something(self):
"""
A testing template -- make to update tests.yml if you change the
testing name.
"""
matches = True
expected_matches = Tru... | nilq/baby-python | python |
from selenium.webdriver.common.by import By
from seleniumpm.webpage import Webpage
from seleniumpm.webelements.textfield import TextField
from seleniumpm.locator import Locator
class GooglePage(Webpage):
"""
This is an Google page that extends SeleniumPM WebPage. This class acts as a container for the differe... | nilq/baby-python | python |
import unittest
from ArrayQueue import ArrayQueue, Empty
class TestArrayQueue(unittest.TestCase):
def setUp(self):
self.q = ArrayQueue()
self.q.enqueue(1)
self.q.enqueue(2)
self.q.enqueue(3)
def test_instantiation(self):
print('Can create an instance')
self.as... | nilq/baby-python | python |
"""Unit tests for memory-based file-like objects.
StringIO -- for unicode strings
BytesIO -- for bytes
"""
import unittest
from test import support
import io
import _pyio as pyio
import pickle
class MemorySeekTestMixin:
def testInit(self):
buf = self.buftype("1234567890")
bytesIo = self.ioclass(... | nilq/baby-python | python |
# Generated by Django 3.1.3 on 2022-01-18 13:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('onlinecourse', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='choice',
name='question_id',
... | nilq/baby-python | python |
"""Tools to turn atmospheric profiles into their record representation.
MonoRTM takes gas amounts either as column density in molecules/cm² or
as molecular/volume mixing ratios in molecules/molecules. Internally the
two are separated by checking if the given value is smaller or larger than
one (monortm.f90, lines 421-... | nilq/baby-python | python |
import numpy as np
import argparse
import cv2
from cnn.neural_network import CNN
from keras.utils import np_utils
from keras.optimizers import SGD
from sklearn.datasets import fetch_mldata
from sklearn.model_selection import train_test_split
# Parse the Arguments
ap = argparse.ArgumentParser()
ap.add_argu... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.