content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from datetime import date
def run_example():
march_2020_15 = date(year=2020, month=3, day=15)
print("march_2020_15.toordinal():", march_2020_15.toordinal())
print("march_2020_15.isocalendar():", march_2020_15.isocalendar())
if __name__ == "__main__":
run_example()
| nilq/baby-python | python |
class Solution:
def XXX(self, nums: List[int]) -> int:
length = len(nums)
if length <= 1:
return nums[0]
for i in range(1, length):
sum_ = nums[i-1] + nums[i]
if sum_ > nums[i]:
nums[i] = sum_
return max(nums)
undefined
for (i = 0... | nilq/baby-python | python |
import itertools
# Have the function ArrayAdditionI(arr) take the array of numbers stored in arr and return the string true if any combination of numbers in the array
# (excluding the largest number) can be added up to equal the largest number in the array, otherwise return the string false.
# For example: if ar... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from aliyun.api.rest import *
from aliyun.api.base import FileItem
| nilq/baby-python | python |
total_pf = {{packing_fraction}}
poly_coeff = {{polynomial_triso}}
| nilq/baby-python | python |
# Declare Variables
name = input() # Seller's name
salary = float(input()) # Seller's salary
sales = float(input()) # Sale's total made by the seller in the month
# Calculate salary with bonus
total = salary + (sales * .15)
# Show result
print("Total = R$ {:.2f}".format(total))
| nilq/baby-python | python |
from contextlib import contextmanager
import sys
@contextmanager
def stdout_translator(stream):
old_stdout = sys.stdout
sys.stdout = stream
try:
yield
finally:
sys.stdout = old_stdout
def read_translation(stream):
out = stream.getvalue()
outs = out.split('\n')
for item in o... | nilq/baby-python | python |
#!/usr/bin/env python3
import os
import redis
import json
from flask import Flask, render_template, redirect, request, url_for, make_response
#r = redis.Redis(host='123.12.148.95', port='15379', password='ABCDEFG1231LQ4L')
if 'VCAP_SERVICES' in os.environ:
VCAP_SERVICES = json.loads(os.environ['VCAP_SERVICES'])
... | nilq/baby-python | python |
import battlecode as bc
import sys
import traceback
import time
import pathFinding
#TODO: remove random and use intelligent pathing
import random
totalTime = 0
start = time.time()
#build my environment
gc = bc.GameController()
directions = list(bc.Direction)
#get the starting map
myMap = gc.starting_map(gc.planet())... | nilq/baby-python | python |
#!/usr/bin/env python
import numpy as np # For efficient utilization of array
import cv2 # Computer vision library
import os # Here this package is used writing CLI commands
import vlc_ctrl
import time
import pandas as pd
import os # package used for controlling vlc media player
import subproc... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import logging
from dku_model_accessor.constants import DkuModelAccessorConstants
from dku_model_accessor.preprocessing import Preprocessor
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
logger = logging.getLogger(__name__)
class SurrogateModel(object):
"""
... | nilq/baby-python | python |
import yaml
try:
# use faster C loader if available
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
# follows similar logic to cwrap, ignores !inc, and just looks for [[]]
def parse(filename):
with open(filename, 'r') as file:
declaration_lines = []
decl... | nilq/baby-python | python |
import re
class Graph:
def __init__(self, nodes, numWorkers=5):
self.graph = {}
for asciiCode in range(65, 91):
self.graph[chr(asciiCode)] = []
# populate link nodes
for node in nodes:
if node.pre in self.graph:
self.graph[no... | nilq/baby-python | python |
# sql/expression.py
# Copyright (C) 2005-2022 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: https://www.opensource.org/licenses/mit-license.php
"""Defines the public namespace for SQL expression constructs.
"""
from ._dml... | nilq/baby-python | python |
import argparse
from pathlib import Path
import torch
import torch.backends.cudnn as cudnn
import torch.nn as nn
import torch.utils.data as data
from PIL import Image, ImageFile
from torchvision import transforms
from tqdm import tqdm
from template import imagenet_templates
import fast_stylenet
from sampler import Inf... | nilq/baby-python | python |
# import os
# import json
#
# target_dirs = [ 'home_1', 'home_2', 'home_3', 'real_v0', 'real_v1', 'real_v2', 'real_v3', 'human_label_kobeF2', 'victor_1']
# target_file = './data/'
# for target_dir in target_dirs:
# target_file += target_dir + '_'
# target_file += 'output.json'
#
# output_images = {}
# output_annota... | nilq/baby-python | python |
# ==================================================================================================
# Copyright 2013 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use thi... | nilq/baby-python | python |
__author__ = 'Kalyan'
from placeholders import *
# For most of these tests use the interpreter to fill up the blanks.
# type(object) -> returns the object's type.
def test_numbers_types():
assert "int" == type(7).__name__
assert "float" == type(7.5).__name__
assert "long" == type(10L).__name__
... | nilq/baby-python | python |
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,... | nilq/baby-python | python |
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, s... | nilq/baby-python | python |
# File to explore the difference between the error function relying on Hoeffding's bound and the one relying on the
# bound of Maurer and Pontil.
import os
import sys
import configparser
import numpy as np
directory = os.path.dirname(os.path.dirname(os.path.expanduser(__file__)))
sys.path.append(directory)
path_conf... | nilq/baby-python | python |
import keras
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Conv2D, MaxPooling2D, ConvLSTM2D
from keras.layers import Activation, Dropout, Flatten, Dense, LeakyReLU
from keras.layers import LSTM, TimeDistributed, Lambda, BatchNormalization
from kera... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from nseta.analytics.model import *
from nseta.common.history import historicaldata
from nseta.common.log import tracelog, default_logger
from nseta.plots.plots import *
from nseta.cli.inputs import *
from nseta.archives.archiver import *
import click
from datetime import datetime
__all__ = ['... | nilq/baby-python | python |
import socket
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind(('127.0.0.1', 50007))
s.listen(1)
while True:
conn, addr = s.accept()
with conn:
while True:
data = conn.recv(1024)
if not data:
break
... | nilq/baby-python | python |
#!/usr/bin/python3
# -*- coding:utf-8 -*-
# ganben: MontyLemmatiser port of montylingua 2.1`
import re
# think about import
class MontyLemmatiser:
#
# original implt read `.mdf` file as db
# u obviously need a bigger db file
xtag_morph_zhcn_corpus = '' # add a real source
exceptions_source = '' ... | nilq/baby-python | python |
import logging
from typing import List, Tuple, Dict
import psycopg2
from src.tools.utils import read_config
class Postgres:
def __init__(self, config: Dict = None):
self.connection = None
self.cursor = None
self.connect(config)
def connect(self, config: Dict = None) -> None:
... | nilq/baby-python | python |
import os
from typing import Any, Dict, Literal
import wandb
from wicker.core.config import get_config
from wicker.core.definitions import DatasetID
from wicker.core.storage import S3PathFactory
def version_dataset(
dataset_name: str,
dataset_version: str,
entity: str,
metadata: Dict[str, Any],
... | nilq/baby-python | python |
from .munger import * # noqa
from .munger_link_only import * # noqa | nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
"""
Test _extend_kb_with_fixed_labels from core
"""
import pyqms
import sys
import unittest
TESTS = [
# {
# 'in' : {
# 'params' : {
# 'molecules' : ['KLEINERTEST'],
# 'charges' : [2, ],
# 'fixed_labels' : ... | nilq/baby-python | python |
'''
EXERCÍCIO 015: Aluguel de Carros
Escreva um programa que pergunte a quantidade de km percorridos por um carro alugado e a quantidade de dias pelos quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro custa R$ 60 por dia e R$ 0,15 por km rodado.
Escreva um programa que pergunte a quantidade de km pe... | nilq/baby-python | python |
#!/usr/bin/env python3
# coding: utf8
"""
Day 5: Alchemical Reduction part 2
https://adventofcode.com/2018/day/5
"""
from string import ascii_lowercase
def reactPolymer(polymer):
pats = []
pats += [c + c.upper() for c in ascii_lowercase]
pats += [c.upper() + c for c in ascii_lowercase]
reactedPolym... | nilq/baby-python | python |
from pathlib import Path
import os
import random
import json
import itertools
import copy
import torch
from torch.utils.data import Dataset, DataLoader, BatchSampler, RandomSampler, \
SequentialSampler
from torchvision import transforms
import numpy as np
import cv2
import PIL
import scipy.io
import glob
from . ... | nilq/baby-python | python |
from matplotlib import mlab
def SY_PeriodVital(x):
f1 = 1
f2 = 6
z = np.diff(x)
[F, t, p] = signal.spectrogram(z,fs = 60)
f = np.logical_and(F >= f1,F <= f2)
p = p[f]
F = F[f]
Pmean = np.mean(p)
Pmax = np.max(p)
ff = np.argmax(p)
if ff >= len(F):
Pf = np.nan
... | nilq/baby-python | python |
# Copyright (c) 2022 PaddlePaddle 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 appli... | nilq/baby-python | python |
import random
from collections import deque
from mesh.generic.nodeConfig import NodeConfig
from mesh.generic.formationClock import FormationClock
from mesh.generic.nodeState import NodeState, LinkStatus
from mesh.generic.cmdDict import CmdDict
class NodeParams():
def __init__(self, configFile=[], config=[]):
... | nilq/baby-python | python |
"""
Reference :
https://github.com/mattalcock/blog/blob/master/2012/12/5/python-spell-checker.rst
"""
import re
import collections
class SpellCorrect:
def __init__(self,
text=None,
files=[],
initialize=True):
self.NWORDS = collections.defaultdict(lambda... | nilq/baby-python | python |
ERROR_CODES = {
0: "EFW_SUCCESS",# = 0,
1: "EFW_ERROR_INVALID_INDEX",#,
3: "EFW_ERROR_INVALID_ID",#,
4: "EFW_ERROR_INVALID_VALUE",#,
5: "EFW_ERROR_REMOVED",#, //failed to find the filter wheel, maybe the filter wheel has been removed
6: "EFW_ERROR_MOVING",#,//filter wheel is moving
7: "EFW_E... | nilq/baby-python | python |
from django.http import Http404
from django.shortcuts import render_to_response
from django.template import RequestContext
from seaserv import get_repo, is_passwd_set
from winguhub.utils import check_and_get_org_by_repo, check_and_get_org_by_group
def sys_staff_required(func):
"""
Decorator for views that che... | nilq/baby-python | python |
from dataclasses import dataclass
@dataclass
class CheckpointCallback:
_target_: str = "pytorch_lightning.callbacks.ModelCheckpoint"
monitor: str = "loss/Validation"
save_top_k: int = 1
save_last: bool = True
mode: str = "min"
verbose: bool = False
dirpath: str = "./logs/checkpoints/" # u... | nilq/baby-python | python |
import redis
from twisted.python import log
def open_redis(config):
global redis_pool, redis_info
host = config.get("redis", "host")
port = int(config.get("redis", "port"))
socket = config.get("redis", "socket")
redis_info = ( host, port, socket )
if socket != "":
redis_pool = redis.Co... | nilq/baby-python | python |
#!/usr/bin/python
#
# Copyright 2010 Google 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 ag... | 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 the... | nilq/baby-python | python |
def content_length_check(content, allow_short=False):
maxlen = 40000
if len(content)>maxlen:
raise Exception('content too long {}/{}'.format(len(content), maxlen))
if (len(content)<2 and allow_short==False) or len(content)==0:
raise Exception('content too short')
def title_length_check(titl... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 14 17:36:13 2019
@author: Mangifera
"""
import seaborn as sns
import pandas as pd
from scipy import stats
def is_it_random(filename):
with open(filename, "r") as text_file:
demon = text_file.read()
demon = [int(x) for x in demon.split('\n')]
... | nilq/baby-python | python |
import warnings
warnings.filterwarnings('ignore')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, inspect
from sqlalchemy import func, desc
from matplotlib.t... | nilq/baby-python | python |
import sys
import socket
import threading
class Server:
def __init__(self, hostname='localhost', port=8080):
self.host = hostname
self.port = port
self.clients = []
# crea un socket TCP
self.socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
... | nilq/baby-python | python |
from Server.models.business.ListenThread import ListenThread
listenThread = ListenThread()
listenThread.main_execution()
| nilq/baby-python | python |
'''
Description on how to produce metadata file.
'''
input_filter = None
treename = 'deepntuplizer/tree'
reweight_events = -1
reweight_bins = [list(range(200, 2051, 50)), [-10000, 10000]]
metadata_events = 1000000
selection = '''jet_tightId \
&& ( !label_H_cc )'''
# && ( (sample_isQCD && fj_isQCD) || (!sample_isQCD &&... | nilq/baby-python | python |
from argparse import ArgumentTypeError
import numpy as np
from PIL import Image
from convolution_functions import apply_filter, filters
debug_mode = False
"""
Seznam pouzitelnych funkci pro tento program na upravu obrazku.
Pro pridani fuknce ji napiste zde, a pridejte do action_dict (seznam pouzitelnych fci)
a pot... | nilq/baby-python | python |
"""Tests for the auth providers."""
| nilq/baby-python | python |
# Generated by Django 2.2.1 on 2020-05-07 07:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('PropelRapp', '0009_auto_20200506_0627'),
]
operations = [
migrations.AddField(
model_name='menu',
name='is_deleted',... | nilq/baby-python | python |
''' Text Media Matching interface '''
from summarization.text_media_matching.text_media_matching_helper import \
TextMediaMatchingHelper
from summarization.text_media_matching.text_media_matching_preprocessor import \
TextMediaMatchingPreprocessor # noqa
class TextMediaMatcher:
'''Class to integrate the... | nilq/baby-python | python |
"""
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# 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, mod... | nilq/baby-python | python |
from module import foo, bar
from module import foo, \
bar, \
baz
from module import (foo, bar)
from module import (foo,
bar,
baz)
| nilq/baby-python | python |
from jsonrpcserver.sentinels import Sentinel
def test_Sentinel():
assert repr(Sentinel("foo")) == "<foo>"
| nilq/baby-python | python |
# Copyright (c) 2019, CRS4
#
# 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, distribu... | nilq/baby-python | python |
from numpy import zeros
from sklearn.tree import _tree
def _interpret_tree(tree, X, n_labels):
# Tree preprocessing allowing down-top search
parents = [-1 for _ in range(tree.node_count)]
to_pursue = [0]
while len(to_pursue):
node_i = to_pursue.pop()
child_l = tree.... | nilq/baby-python | python |
from behavioral.interpreter.logic.tokens.token_type import TokenType
class Token:
def __init__(self, token_type: TokenType, text: str) -> None:
self.type = token_type
self.text = text
def __repr__(self) -> str:
return f"Token '{self.type.name}' with value '{self.text}'"
| nilq/baby-python | python |
import pytest
from .fixtures import *
@pytest.mark.parametrize(["num_partitions", "rows"], [(7, 30), (3, 125), (27, 36)])
def test_update_table(num_partitions, rows, store):
fixtures = UpdateFixtures(rows)
original_df = fixtures.make_df()
update_df = fixtures.generate_update_values()
partition_size =... | nilq/baby-python | python |
"""Ghana specific form helpers."""
from django.forms.fields import Select
from .gh_regions import REGIONS
class GHRegionSelect(Select):
"""
A Select widget with option to select a region from
list of all regions of Ghana.
"""
def __init__(self, attrs=None):
super().__init__(attrs, choic... | nilq/baby-python | python |
from django.conf import settings
def pytest_configure():
settings.configure(INSTALLED_APPS=["geoipdb_loader"])
| nilq/baby-python | python |
import datetime
from typing import Any, Optional
from googleapiclient.discovery import build
from jarvis.plugins.auth.google_auth import GoogleAuth
from .config import GoogleCalendar
class GoogleCalendar:
def __init__(self, calendar_id: Optional[str] = None) -> None:
self.calendars: dict = GoogleCalendar.... | nilq/baby-python | python |
import sys
import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output, State
# TODO: fix it
sys.path.append("./")
from calculus_of_variations import MultidimensionalSolver
from web_interface.utils import (
dash_multidimensional_answer,
dash_m... | nilq/baby-python | python |
from datetime import date
from nose.tools import eq_
from nose.plugins.attrib import attr
from allmychanges.crawler import (
_filter_changelog_files,
_extract_version, _parse_item,
_extract_date)
from allmychanges.utils import get_markup_type, get_change_type
from allmychanges.downloaders.utils import norm... | nilq/baby-python | python |
# coding=utf-8
__author__ = 'cheng.hu'
import logging
# 第一步,创建一个logger
logger = logging.getLogger()
logger.setLevel(logging.INFO) # Log等级总开关
# 第二步,创建一个handler,用于写入日志文件
logfile = '/Users/CalvinHu/Documents/python/hurnado/src/test/log.txt'
fh = logging.FileHandler(logfile, mode='w')
fh.setLevel(logging.INFO) # 输出到... | nilq/baby-python | python |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse, HttpResponseBadRequest, JsonResponse
from django.shortcuts import render
# Create your views here.
from django.template.loader import render_to_string
from django.ur... | nilq/baby-python | python |
# Copyright 2017 University of Maryland.
#
# This file is part of Sesame. It is subject to the license terms in the file
# LICENSE.rst found in the top-level directory of this distribution.
import numpy as np
from .observables import *
from .defects import defectsF
def getF(sys, v, efn, efp, veq):
###############... | nilq/baby-python | python |
import tornado.web
import mallory
class HeartbeatHandler(tornado.web.RequestHandler):
def initialize(self, circuit_breaker):
self.circuit_breaker = circuit_breaker
@tornado.web.asynchronous
@tornado.gen.engine
def get(self):
if self.circuit_breaker.is_tripped():
self.set_st... | nilq/baby-python | python |
from petroleum.conditional_task import ConditionalTask
from petroleum.exceptions import PetroleumException
from petroleum.task import Task
class ExclusiveChoice(Task):
def __init__(self, name=None, *args, **kwargs):
self._conditional_tasks = []
super().__init__(name=None, *args, **kwargs)
def... | nilq/baby-python | python |
"""
AmberTools utilities.
"""
__author__ = "Steven Kearnes"
__copyright__ = "Copyright 2014, Stanford University"
__license__ = "BSD 3-clause"
from collections import OrderedDict
from cStringIO import StringIO
import numpy as np
import os
import shutil
import subprocess
import tempfile
from rdkit import Chem
from v... | nilq/baby-python | python |
from matplotlib import pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
from scipy.interpolate import griddata
import copy
def visualize_source(
points,
values,
ax=None,
enlarge_factor=1.1,
npixels=100,
cmap='jet',
):
"""
Points is defined as a... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
__author__ = 'S.I. Mimilakis'
__copyright__ = 'MacSeNet'
import torch
import torch.nn as nn
from torch.autograd import Variable
class SkipFiltering(nn.Module):
def __init__(self, N, l_dim):
"""
Constructing blocks of the skip filtering connections.
Reference: - ht... | nilq/baby-python | python |
# __init__.py
import logging
import os
from task_manager.views import (
HomeView,
ErrorView,
InfoView,
LoginView,
LogoutView,
ProfileView,
RegistrationView,
TaskListView,
TaskView
)
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.options impo... | nilq/baby-python | python |
from dnaweaver import (
CommercialDnaOffer,
DnaAssemblyStation,
GibsonAssemblyMethod,
OligoAssemblyMethod,
TmSegmentSelector,
FixedSizeSegmentSelector,
PerBasepairPricing,
SequenceLengthConstraint,
)
# OLIGO COMPANY
oligo_com = CommercialDnaOffer(
name="Oligo vendor",
sequence_... | nilq/baby-python | python |
import sys
import os
import json
# date and time
from datetime import datetime, timedelta
from email.utils import parsedate_tz
from dateutil import tz
import time
from api_extractor_config import DATETIME_FORMAT
def load_credentials(access):
credentials = {}
if access == 'AgProCanada_TableauD... | nilq/baby-python | python |
import json
BATCH_SIZE = 128
RNN_SIZE = 128
EMBED_SIZE = 128
LEARNING_RATE = 0.001
KEEP_PROB = 0.75
EPOCHS = 500
DISPLAY_STEP = 30
MODEL_DIR = 'Saved_Model_Weights'
SAVE_PATH = 'model_saver'
MIN_LEARNING_RATE = 0.01
LEARNING_RATE_DECAY = 0.9
| nilq/baby-python | python |
#!/usr/bin/env python
from __future__ import print_function
import cProfile
import matplotlib.pyplot as plt
import multiprocessing as mp
import numpy as np
import swn
def stats():
grouperLabels = ['Random',
'Min Dist Stars',
'Max Dist Stars',
'1/4 M... | nilq/baby-python | python |
from .abstract_conjunction import AbstractConjunction
from .condition_type import ConditionType
class OrConjunction(AbstractConjunction):
def __init__(self, conditions):
super().__init__(type_=ConditionType.OR.value, conditions=conditions)
| nilq/baby-python | python |
import socket
from enum import IntEnum
import json
import argparse
# Enum of available commands
class Command(IntEnum):
Undefined = 1
SafeModeEnable = 2
SafeModeDisable = 3
ShowNumCommands = 4
ShowNumSafeModes = 5
ShowUpTime = 6
ResetCommandCounter = 7
Shutdown = 8
MAX_COMMAND_NUM = 9
... | nilq/baby-python | python |
# coding: utf-8
# Copyright (c) 2016, 2022, 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 |
from django.test import TestCase
from dfirtrack_config.filter_forms import AssignmentFilterForm
class AssignmentFilterFormTestCase(TestCase):
"""assignment filter form tests"""
def test_case_form_label(self):
"""test form label"""
# get object
form = AssignmentFilterForm()
#... | nilq/baby-python | python |
from guy import Guy,http
@http(r"/item/(\d+)")
def getItem(web,number):
web.write( "item %s"%number )
def test_hook_with_classic_fetch(runner):
class T(Guy):
__doc__="""Hello
<script>
async function testHook() {
var r=await window.fetch("/item/42")
return await ... | nilq/baby-python | python |
'''Google Sheets Tools'''
import os
from pathlib import Path
import subprocess
import pandas as pd
def save_csv(url: str, save_path: Path, sheet_name: str, show_summary=False):
'''Download a data sheet from Google Sheets and save to csv file'''
sheet_url = f'{url}&sheet={sheet_name}'
subprocess.run(('wge... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# flake8: noqa
from __future__ import absolute_import
from __future__ import print_function
import io
from os import path
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
import sys
import setuptools
from setuptools.command.dev... | nilq/baby-python | python |
# Copyright (c) 2021 Alethea Katherine Flowers.
# Published under the standard MIT License.
# Full text available at: https://opensource.org/licenses/MIT
"""Helps create releases for Winterbloom stuff"""
import atexit
import collections
import datetime
import importlib.util
import mimetypes
import os
import os.path
i... | nilq/baby-python | python |
# Generated by Django 3.1.12 on 2021-08-06 12:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("aidants_connect_web", "0064_merge_20210804_1156"),
]
operations = [
migrations.AlterField(
model_name="habilitationrequest",
... | nilq/baby-python | python |
from django.shortcuts import render
from sch.models import search1
from sch.models import subs
# Create your views here.
def list(request):
select1=request.POST.get('select1')
select2=request.POST.get('select2')
ls = search1.objects.filter(City=select2)
print(select2)
print(select1)
return re... | nilq/baby-python | python |
from gooey import options
from gooey_video import ffmpeg
def add_parser(parent):
parser = parent.add_parser('trim_crop', prog="Trim, Crop & Scale Video", help='Where does this show??')
input_group = parser.add_argument_group('Input', gooey_options=options.ArgumentGroup(
show_border=True
))
# ... | nilq/baby-python | python |
import pytest
from gpiozero import Device
from gpiozero.pins.mock import MockFactory, MockPWMPin
from pytenki import PyTenki
@pytest.yield_fixture
def mock_factory(request):
save_factory = Device.pin_factory
Device.pin_factory = MockFactory()
yield Device.pin_factory
if Device.pin_factory is not Non... | nilq/baby-python | python |
a=list(map(int,input().split()))
n=len(a)
l=[]
m=0
j=n-1
for i in range(n-2,0,-1):
if(a[i]>a[i-1] and a[i]>a[0]):
m=max(m,a[i]-a[0])
#print(m)
elif(a[i]<a[i-1]):
j=i
m=0
l.append(m)
print(m)
m=0
while(j<n-1):
m=max(m,a[n-1]-a[j])
j+=1
l.appen... | nilq/baby-python | python |
""" Pacakge for various utilities """
| nilq/baby-python | python |
# type:ignore
from django.conf.urls import include, url
from . import views
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index, name='index'),
path('newproject', views.create_project, name = "create_project"),
... | nilq/baby-python | python |
"""
Arrangement of panes.
Don't confuse with the prompt_toolkit VSplit/HSplit classes. This is a higher
level abstraction of the Pymux window layout.
An arrangement consists of a list of windows. And a window has a list of panes,
arranged by ordering them in HSplit/VSplit instances.
"""
from __future__ import unicode... | nilq/baby-python | python |
from microsetta_public_api.utils._utils import (
jsonify,
DataTable,
create_data_entry,
)
__all__ = [
'testing',
'jsonify',
'DataTable',
'create_data_entry',
]
| nilq/baby-python | python |
from __future__ import annotations
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "1"
import numpy as np
import pandas as pd
import datetime
import tensorflow as tf
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.pipeline import Pipeline
from s... | nilq/baby-python | python |
#It is necessary to import the datetime module when handling date and time
import datetime
currentTime = datetime.datetime.now()
currentDate = datetime.date.today()
#This will print the date
#print(currentDate)
#This the year
#print(currentDate.year)
#This the month
#print(currentDate.month)
#And this the d... | nilq/baby-python | python |
RAD_FILE_FOLDER = ""
path_stack = [] #wrt RAD_FILE_FOLDER
JSON_FILE_FOLDER = "" | nilq/baby-python | python |
# Copyright 2019 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... | nilq/baby-python | python |
import os
ps_user = "sample"
ps_password = "sample"
| nilq/baby-python | python |
# encoding: UTF-8
'''
vn.lts的gateway接入
'''
import os
import json
from vnltsmd import MdApi
from vnltstd import TdApi
from vnltsqry import QryApi
from ltsDataType import *
from vtGateway import *
# 以下为一些VT类型和LTS类型的映射字典
# 价格类型映射
priceTypeMap= {}
priceTypeMap[PRICETYPE_LIMITPRICE] = defineDict["SECURITY_FTDC_OPT_Limi... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.