content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Copyright (c) 2021 Scott Weaver
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 u... | nilq/baby-python | python |
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='irobot',
... | nilq/baby-python | python |
from helperfunctions_plot import *
from plane_relative import *
from denavit_hartenberg140 import *
import itertools as it
def work_it(M, func=n.diff, axis=1):
return np.apply_along_axis(func, axis, arr=M)
def get_closest_solutions_pair(s0, s1):
## diff_list = []
## index_list0 = []
## index... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Author:by 王林清 on 2021/10/31 18:44
FileName:lunyu.py in shiyizhonghua_resource
Tools:PyCharm python3.8.4
"""
from util import get_time_str, save_split_json, get_json
if __name__ == '__main__':
author = {
'name': '孔子',
'time': '春秋',
'desc': '孔子(公元前551年9月28日~公元前479... | nilq/baby-python | python |
import cv2 as cv
import os
import numpy as np
class Cartonifier:
def __init__(self, n_downsampling_steps=2, n_filtering_steps=7):
self.num_down = n_downsampling_steps
self.num_bilateral = n_filtering_steps
# def process_folder(self, input_folder, output_folder):
# if not os.path.exis... | nilq/baby-python | python |
"""
AR : conditional covariance based Granger Causality
===================================================
This example reproduces the results of Ding et al. 2006 :cite:`ding2006granger`
where in Fig3 there's an indirect transfer of information from Y->X that is
mediated by Z. The problem is that if the Granger Causa... | nilq/baby-python | python |
#! bin/bash/python3
# Solution to Mega Contest 1 Problem: Sell Candies
for testcase in range(int(input())):
net_revenue = 0
n = int(input())
vals = list(map(int, input().split()))
vals.sort(reverse=True)
cost_reduction = 0
for val in vals:
net_revenue += max(val-cost_reduction, 0)
... | nilq/baby-python | python |
# ------------------------------------------------------------------------
# DT-MIL
# Copyright (c) 2021 Tencent. All Rights Reserved.
# ------------------------------------------------------------------------
def build_dataset(image_set, args):
from .wsi_feat_dataset import build as build_wsi_feat_dataset
r... | nilq/baby-python | python |
from .misc import (
camel_to_underscore,
convert_date,
convert_datetime,
dict_from_dataframe,
dir_list,
download_if_new,
get_ulmo_dir,
mkdir_if_doesnt_exist,
module_with_dependency_errors,
module_with_deprecation_warnings,
open_file... | nilq/baby-python | python |
from flask import Flask
from flask import make_response
app = Flask(__name__)
@app.route('/')
def index():
response = make_response('<h1>This document carries a cookie!</h1>')
response.set_cookie('answer', '42')
return response
if __name__ == '__main__':
app.run()
| nilq/baby-python | python |
#!/usr/bin/env /usr/bin/python3
# -*- coding: utf-8 -*-
from pymisp import PyMISP
from key import *
import json
import time
import os
from urllib.parse import urljoin
import sys
import traceback
from shutil import copyfile
import logging.handlers
from urllib.parse import quote
import argparse
logger = logging.getLog... | nilq/baby-python | python |
# (C) Datadog, Inc. 2019-present
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
import os
import platform
import stat
import subprocess
import click
import requests
from ....fs import ensure_parent_dir_exists
from ...constants import get_root
from ...testing import get_test_envs
fro... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Partitioned Least Square class
Developer:
Omar Billotti
Description:
Partitioned Least Square class
"""
from numpy import shape, zeros, hstack, ones, vstack, sum as sum_elements, array, inf, where
from numpy.random import rand
from numpy.linalg import lstsq
from scipy.optimize import nnls
fr... | nilq/baby-python | python |
import logging
from source.bridgeLogger import configureLogging
from nose2.tools.such import helper as assert_helper
def test_case01():
with assert_helper.assertRaises(TypeError):
configureLogging()
def test_case02():
with assert_helper.assertRaises(TypeError):
configureLogging('/tmp')
def... | nilq/baby-python | python |
import unittest
from imdb_app_data.moviemodel import MovieModel
from imdb_app_logic.movie_scraper import MovieScraper
from imdb_app_logic.ratingcalculator import RatingCalculator
class Test(unittest.TestCase):
def test_scraper(self):
scraper = MovieScraper()
scraper.get_movie_list()
#... | nilq/baby-python | python |
from docker import DockerClient
from pytest import fixture
from yellowbox.clients import open_docker_client
@fixture(scope="session")
def docker_client() -> DockerClient:
with open_docker_client() as client:
yield client
| nilq/baby-python | python |
def flow_control(k):
if (k == 0):
s = "Variable k = %d equals 0." % k
elif (k == 1):
s = "Variable k = %d equals 1." % k
else:
s = "Variable k = %d does not equal 0 or 1." % k
print(s)
def main():
i = 0
flow_control(i)
i = 1
flow_control(i)
i = 2
flow_control(i)
if __name__ == "__main__":
... | nilq/baby-python | python |
# Copyright 2012 Philip Chimento
"""Sound the system bell, Qt implementation."""
from pyface.qt import QtGui
def beep():
"""Sound the system bell."""
QtGui.QApplication.beep()
| nilq/baby-python | python |
"""
agenda:
1. speedup visualize_result
2. grouping labels
speed bottlenecks:
1. colorEncoding
results:
1. with visualize_result optimize: 0.045s --> 0.002s
2. with grouping labels: 0.002s --> 0.002-0.003s
"""
import os
import sys
import time
PATH = os.path.join(os.getcwd(), '..')
sys.path.append(PATH... | nilq/baby-python | python |
#!/usr/bin/env python
#--------------------------------------------------------
# The classes will generates bunches for pyORBIT J-PARC linac
# at the entrance of LI_MEBT1 accelerator line (by default)
# It is parallel, but it is not efficient.
#--------------------------------------------------------
import math
im... | nilq/baby-python | python |
import excursion
import excursion.testcases.fast as scandetails
import excursion.optimize
import numpy as np
import logging
def test_2d():
scandetails.truth_functions = [
scandetails.truth,
]
N_INIT = 5
N_UPDATES = 1
N_BATCH = 5
N_DIM = 2
X,y_list, gps = excursion.optimiz... | nilq/baby-python | python |
#!/usr/bin/env python3
import time
import sys
import zmq
import numpy as np
import pyglet
from ctypes import byref, POINTER
from pyglet.gl import *
from pyglet.window import key
window = pyglet.window.Window(640, 640, style=pyglet.window.Window.WINDOW_STYLE_DIALOG)
def recv_array(socket):
"""
Receive a numpy... | nilq/baby-python | python |
from django.urls import path
from . import views
urlpatterns = [
path('', views.mainpage_sec, name='index'),
path('authorize_ingress_sec', views.authorize_ingress_sec, name='authorize_ingress'),
path('revoke_ingress_sec', views.revoke_ingress_sec, name='authorize_ingress')
] | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... | nilq/baby-python | python |
import json
import os
import shutil
from os import listdir
from os import path
from os.path import isfile, join
from zipfile import ZipFile
from shutil import copyfile
from glob import glob
import ntpath
import threading
import re
def find_all(name, path):
result = []
for root, dirs, files in os.walk(path):
... | nilq/baby-python | python |
__author__ = 'Sergei'
from model.contact import Contact
from random import randrange
def test_del_contact(app):
if app.contact.count() == 0:
app.contact.create_c(Contact(first_n= "first",mid_n= "middle",last_n= "last",nick_n= "kuk",company= "adda",address= "575 oiweojdckjgsd,russia",home_ph= "12134519827"... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""General purpose nginx test configuration generator."""
import getpass
from typing import Optional
import pkg_resources
def construct_nginx_config(nginx_root: str, nginx_webroot: str, http_port: int, https_port: int,
other_port: int, default_server: bool, key_path... | nilq/baby-python | python |
from tkinter import *
from tkinter import font
from tkinter import ttk
from importlib import reload
game_loadonce = False
def play():
global game
global menuApp, game_loadonce
menuApp.save_scores("leaderboard.txt")
menuApp.root.destroy()
if game_loadonce == False:
import game
gam... | nilq/baby-python | python |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import getopt
import os
import sys
import re
from .debug import Debug
from .debug import BColors
from subprocess import Popen, PIPE
from .debug import Debug
class InputParams(object):
def __init__(self, cfg, argv):
self.PROG_OPT_RE = re.compile(r'^([A-Z\d]+)... | nilq/baby-python | python |
"""Test."""
import unittest
class TestX(unittest.TestCase):
"""Tests."""
def test_f(self):
"""Test."""
self.assertTrue(True)
if __name__ == '__main__':
unittest.main()
| nilq/baby-python | python |
import discord
from redbot.core import Config, commands, checks
class Automod(commands.Cog):
"""Automoderation commands"""
def __init__(self):
self.config = Config.get_conf(self, identifier=1234567890)
watching = list()
self.config.init_custom("ChannelsWatched", 1)
self.config... | nilq/baby-python | python |
#! /user/bin/env python3
import argparse
import xlrd
from datetime import datetime
import pandas as pd
import os
import shutil
import configparser
config = configparser.ConfigParser()
config.read("config.ini")
unixFilesPath = os.getcwd() + config["FilePaths"]["unixFilesPath"]
unixConvertedPath = os.getcwd() + config... | nilq/baby-python | python |
#-*- coding:utf-8 -*-
#
# 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, softwar... | nilq/baby-python | python |
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 Alex Holkner
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are ... | nilq/baby-python | python |
"""Replace block with 'lock'
Revision ID: 8192b68b7bd0
Revises: 3176777cd2bb
Create Date: 2021-01-20 20:48:40.867104
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = "8192b68b7bd0"
down_revision = "3176777cd2bb"
branch_labels... | nilq/baby-python | python |
#TODO check whether dummy classifier also does this
def count_true_positive(two_column_data_set):
positive_count = 0
for data in two_column_data_set["class"]:
##Hate Speech is labelled 0 in this project
if data == 0:
positive_count += 1
return positive_count
def compute_preci... | nilq/baby-python | python |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from src.data_schema.feature_names import FeatureNames
from src.data_preparation.input_data_schema import LasVegasGovtDataSchema
def plot_feature_stat(df, feature_xaxis, feature_yaxis, output_file):
##### construct list of mean, standard devia... | nilq/baby-python | python |
from .sqlalchemy_conftest import * # noqa
@pytest.fixture(scope="session", autouse=True)
def set_up_gcs_mock_tempdir(tmp_path_factory):
from .okta_mock import _Auth
from alchemy.shared import auth_backends
auth_backends.auth, auth_backends.__auth = _Auth(), auth_backends.auth
auth_backends.init_app, ... | nilq/baby-python | python |
import argparse
from snakemake.shell import shell
from .slurm_job import SlurmJob
from exceRNApipeline.includes.utils import logger
def pre_process(input_fq, adapter, log_file, prefix):
cmd = f"""
hts_Stats -L {log_file} -U {input_fq} | \\
hts_AdapterTrimmer -A -L {log_file} -a {adapter} | \\
hts_QWin... | nilq/baby-python | python |
import pandas as pd
import csv
original_csv = pd.read_csv('./Fuzzy_dataset.csv')
normal_csv = open('./fuzzy_normal_dataset.csv', 'w', newline='', encoding='utf-8')
normal_csv_file = csv.writer(normal_csv)
abnormal_csv = open('./fuzzy_abnormal_dataset.csv', 'w', newline='', encoding='utf-8')
abnormal_csv_file = csv.w... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 18 15:34:32 2018
@author: wangyu
"""
import socket
import sys
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) #与服务端相同
try:
sock.connect(('127.0.0.1',1052))
except socket.error as e:
print(e)
sys.exit(-1)
data_send = 'test'
sock.send(data_send.encode... | nilq/baby-python | python |
from .settings import *
from .user_groups import *
| nilq/baby-python | python |
import unittest
from unittest.mock import Mock, patch
from nuplan.common.actor_state.scene_object import SceneObject, SceneObjectMetadata
class TestSceneObject(unittest.TestCase):
"""Tests SceneObject class"""
@patch("nuplan.common.actor_state.tracked_objects_types.TrackedObjectType")
@patch("nuplan.com... | nilq/baby-python | python |
# @Title: 数组中重复的数字 (数组中重复的数字 LCOF)
# @Author: 18015528893
# @Date: 2021-02-28 16:44:53
# @Runtime: 52 ms
# @Memory: 23.4 MB
class Solution:
def findRepeatNumber(self, nums: List[int]) -> int:
for i in range(len(nums)):
while nums[i] != i:
if nums[nums[i]] == nums[i]:
... | nilq/baby-python | python |
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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.
# A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file acc... | nilq/baby-python | python |
"""
Helper module allowing src modules to be imported into tests
"""
# pylint: disable=wrong-import-position
# pylint: disable=unused-import
import os
import sys
from blockutils.common import ensure_data_directories_exist
from blockutils.stac import STACQuery
# NOTE: this must be before the modis and gibs imports - ... | nilq/baby-python | python |
from .context import get_puzzle, get_solution_script
index = 7
INPUT = """
16,1,2,0,4,2,7,1,2,14
"""[1:-1].split("\n")
def test_d7p1():
script = get_solution_script(index)
assert script is not None, "script is none"
d7p1 = script("d7p1")
assert d7p1 is not None, "d7p1 is none"
result = d7p1(INPU... | nilq/baby-python | python |
from collections import deque
def getIsWall(data):
favoriteNumber = int(data)
def isWall(x, y):
if y < 0 or x < 0:
return True
n = favoriteNumber + x * x + 3 * x + 2 * x * y + y + y * y
wall = 0
while n:
wall ^= n & 1
n >>= 1
return ... | nilq/baby-python | python |
# coding: utf-8
import cv2, os, sys
from PIL import Image
import numpy as np
import os
from tensorflow import keras
from tensorflow.keras.layers import Input
from .Models import GoogLeNetModel
from .Models import VGG16Model
from .Models import InceptionV3Model
from .Models import MobileNetModel
from .Mod... | nilq/baby-python | python |
#!/usr/bin/env python
from argparse import ArgumentParser
import sys
parser = ArgumentParser(description="Run the test suite.")
parser.add_argument(
"--failfast",
action="store_true",
default=False,
dest="failfast",
help="Stop the test suite after the first failed test.",
)
parser.add_argument(
... | nilq/baby-python | python |
import torch
def accuracy(pred, target):
pred = pred.float()
correct = 0
for i in range(target.size()[0]):
if (pred[i] == pred[i].max()).nonzero() == target[i]:
correct += 1
return correct / target.size()[0] | nilq/baby-python | python |
# Function to sort an unsorted list (due to globbing) using a number
# occuring in the path.
# Author: Lukas Snoek [lukassnoek.github.io]
# Contact: lukassnoek@gmail.com
# License: 3 clause BSD
from __future__ import division, print_function, absolute_import
import os.path as op
def sort_numbered_list(stat_list):
... | nilq/baby-python | python |
##############################
# support query serve for front web system
# filename:query.py
# author: liwei
# StuID: 1711350
# date: 2019.12.1
##############################
#查询构建
from whoosh import highlight
from whoosh import qparser
from whoosh import index
from flask import Flask
from flask import request... | nilq/baby-python | python |
# Copyright 2016 Google Inc. 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 agree... | nilq/baby-python | python |
#!/usr/bin/env python3
import curses
from random import randrange, choice # generate and place new tile
from collections import defaultdict
letter_codes = [ord(ch) for ch in 'WASDRQwasdrq']
actions = ['Up', 'Left', 'Down', 'Right', 'Restart', 'Exit']
actions_dict = dict(zip(letter_codes, actions * 2))
def get_user... | nilq/baby-python | python |
# https://qiita.com/taigamikami/items/6c69fc813940f838e96c
import numpy as np
import tensorflow as tf
import tensorflow_lattice as tfl
import matplotlib.pyplot as plt
import input_data
# ====================================
# 訓練用のデータ
# ====================================
#x_train = np.arange(-5, 5, 0.2)
#noise = np.... | nilq/baby-python | python |
config = {
"--acoustic-scale":[0.1,float],
"--allow-partial":["false",str],
"--beam":[13,int],
"--beam-delta":[0.5,float],
"--delta":[0.000976562,float],
"--determinize-lattice":["true",str],
"--hash-ratio":[2,int],
"--latti... | nilq/baby-python | python |
"""
Odoo client using Openerp proxy
"""
# https://pypi.org/project/openerp_proxy/
from openerp_proxy import Client as erpClient
class Client():
"""
Odoo client
"""
def __init__(self, username:str, password:str = '', database:str = '', host:str = '', port:int = 443, protocol:str = 'json-rpcs'):
... | nilq/baby-python | python |
import ROOT
import numpy as np
# fast index lookup
from melp.libs.misc import index_finder
def save_histo(filename: str, dt_dict: dict):
histo_file = ROOT.TFile.Open(filename, "RECREATE")
for keys in dt_dict.keys():
name_z = str(keys) + "z"
name_phi = str(keys) + "phi"
histo_file.Wri... | nilq/baby-python | python |
import logging
from collections import namedtuple
import magic
from io import BytesIO
from django.views.generic import DetailView
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
import matplotlib
import matplotlib.pyplot
import aplpy
import astropy
from scheduler.models im... | nilq/baby-python | python |
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from .models import Favorite, Subscription
User = get_user_model()
class FavoriteAdmin(admin.ModelAdmin):
model = Favorite
list_display = ('user', 'recipe')
class SubscriptionAdm... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 7 18:40:45 2019
@author: ryder
"""
#%%
import os
import pandas as pd
from pynabapi import YnabClient
import pygsheets
import datetime
import time
import re
#%%
# should create google_ledger object
with open('keys/google_expenses_sheet_key.txt', 'r') as g_sheet_id_key... | nilq/baby-python | python |
name = 'omnifig'
long_name = 'omni-fig'
version = '0.6.3'
url = 'https://github.com/felixludos/omni-fig'
description = 'Universal configuration system for common execution environments'
author = 'Felix Leeb'
author_email = 'felixludos.info@gmail.com'
license = 'MIT'
readme = 'README.rst'
packages = ['omnifig'... | nilq/baby-python | python |
import sys
import dataset
from datetime import datetime
from dateutil.rrule import rrule, MONTHLY
from dateutil.relativedelta import relativedelta
def process(username, metric, stream_limit):
# gets all artists and their respective daily play counts
db = dataset.connect('sqlite:///last-fm.db')
total = db[username].... | nilq/baby-python | python |
import requests
from datetime import datetime
aq = []
def scrap():
url = "http://vc8006.pythonanywhere.com/api/"
response = requests.request("GET", url)
r = response.json()
for i in range(1,31):
aq.append(r[-i]['AQI'])
# print(r[-i])
# print(response.text)
print(aq)
s... | nilq/baby-python | python |
import gym
from griddly import GymWrapperFactory
from griddly.RenderTools import RenderToFile
if __name__ == '__main__':
# A nice tool to save png images
file_renderer = RenderToFile()
# This is what to use if you want to use OpenAI gym environments
wrapper = GymWrapperFactory()
# There are two ... | nilq/baby-python | python |
# Generated by Django 2.2.15 on 2020-08-04 19:14
import aldryn_apphooks_config.fields
import app_data.fields
import cms.models.fields
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import djangocms_blog.models
import djangocms_text_ckeditor.fields
import file... | nilq/baby-python | python |
import pandas as pd
import numpy as np
import ml_metrics as metrics
from sklearn.ensemble import RandomForestClassifier
from sklearn.calibration import CalibratedClassifierCV
from sklearn.cross_validation import StratifiedKFold
from sklearn.metrics import log_loss
path = '../Data/'
print("read training data")... | nilq/baby-python | python |
import pytest
from mutalyzer_spdi_parser.convert import to_hgvs_internal_model, to_spdi_model
TESTS_SET = [
(
"NG_012337.3:10:C:T",
{
"seq_id": "NG_012337.3",
"position": 10,
"deleted_sequence": "C",
"inserted_sequence": "T",
},
{
... | nilq/baby-python | python |
"""
Licensed Materials - Property of IBM
Restricted Materials of IBM
20190891
© Copyright IBM Corp. 2021 All Rights Reserved.
"""
"""
Module to where fusion algorithms are implemented.
"""
import logging
import numpy as np
from ibmfl.aggregator.fusion.iter_avg_fusion_handler import \
IterAvgFusionHandler
logger ... | nilq/baby-python | python |
from lark import Tree
from copy import deepcopy
from .values import Value, ValueType
from .symbols import Symbol, Symbols
from .debug import DebugOutput
from .converters import get_symbol_name_from_key_item, get_array_index_exp_token_from_key_item
from . import blocks
from . import expressions
class Key():
def __... | nilq/baby-python | python |
numero=int(input('Coloque o seu numero: '))
x=0
while x <= numero:
if x % 2 == 0:
print (x)
x = x + 1 | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Package to support metabarcoding read trimmming, merging, and quantitation."""
import os
__version__ = "0.1.0-alpha"
_ROOT = os.path.abspath(os.path.dirname(__file__))
ADAPTER_PATH = os.path.join(_ROOT, "data", "TruSeq3-PE.fa")
| nilq/baby-python | python |
import numpy as np
import pylab as pl
from astropy.io import fits
from astropy.table import Table
from linetools.spectra.io import readspec
from linetools.spectra.xspectrum1d import XSpectrum1D
from linetools.spectra.utils import collate
import numpy as np
from pypeit.core import coadd as arco
from astropy import units... | nilq/baby-python | python |
import findspark
findspark.init('/opt/spark')
import schedule
import pyspark
from pyspark.sql import SparkSession
from pyspark.sql.functions import col, udf, lit
import random
import smtplib, ssl
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
import schedule
import time
from random ... | nilq/baby-python | python |
class Test(object):
__slots__ = 'name', 'word_set', 'target', 'longest_subsequence',\
'verbose', 'actual'
def __init__(self, json_object):
self.name = json_object['name']
self.word_set = json_object['word_set']
self.target = json_object['target']
self.longest_subsequence = j... | nilq/baby-python | python |
numbers = [int(el) for el in input().split(", ")]
positive = [str(x) for x in numbers if x >= 0]
negative = [str(x) for x in numbers if x < 0]
even = [str(x) for x in numbers if x % 2 == 0]
odd = [str(x) for x in numbers if not x % 2 == 0]
print("Positive:", ', '.join(positive))
print("Negative:", ', '.join(negative)... | nilq/baby-python | python |
# ------ your setttings ------
TrainModule = 'OutputOshaberi' # your sensation folder name
device = 'cuda' # debugging device
# ------ end of settings -----
if __name__ == '__main__':
from importlib import import_module
from multiprocessing import Value
module = import_module(TrainModule)
func = module... | nilq/baby-python | python |
year = int(input())
if year%4==0:
cond=True
if year%100==0 and cond==True:
cond=False
if year%400==0 and cond==False:
print(f"{year} is a Leap Year!!")
else:
print(f"{year} is not a Leap Year") | nilq/baby-python | python |
from flask import Flask,request
import os
import base64
from lib.logger import Logger
from termcolor import colored
import sys
def main(mongoclient,server_logger,port):
app = Flask('app')
## Get the cookie/victim ID from a request
def get_cookie(request):
d = request.cookies
if d:
return base64.b64decode(... | nilq/baby-python | python |
'''
PyTorch Dataset Handling. The dataset folder should comprise of two subfolders namely "train" and "test" where both folders has subfolders that named
according to their class names.
'''
import os
import glob
import cv2
import torch
from torch.utils import data
from torch.utils.data import Dataset, dataset
class ... | nilq/baby-python | python |
import numpy as np
from perturbative_solver import solve_oscillon
from matplotlib import pyplot as plt
from progress.bar import Bar
############################################################################
# Edit these parameters:
############################################################################
# the v... | nilq/baby-python | python |
from PIL import Image
from csv import reader
inputFilename: str = "./dist/flag.csv"
outputFilename: str = "./writeup/flag.png"
with open(inputFilename, "r") as csv_file:
csv_reader = reader(csv_file)
list_of_rows = list(csv_reader)
size = [len(list_of_rows[0]), len(list_of_rows)]
outputImage: Image = Image.n... | nilq/baby-python | python |
import unittest
import ttrw
from unittest.mock import patch
test_dictionary = {
"en": {
"adverbs": ["test"],
"adjectives": ["test"],
"nouns": ["test"]
},
"pl": {
"adverbs": ["bardzo"],
"adjectives": ["maly"],
"nouns": ["ksiazka"]
}
}
class TestTTRW(unit... | 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
# distribu... | nilq/baby-python | python |
import graphene
from graphql_auth.bases import MutationMixin, DynamicArgsMixin
from users.mixins import PasswordSetAdminMixin
class PasswordSetAdmin(MutationMixin, DynamicArgsMixin, PasswordSetAdminMixin, graphene.Mutation):
_required_args = ["new_password1", "new_password2"]
class Arguments:
id = gr... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import os
import unittest
import sqlite3
import tempfile
import bottle
from bottle.ext import sqlite
''' python3 moves unicode to str '''
try:
unicode
except NameError:
unicode = str
class SQLiteTest(unittest.TestCase):
def setUp(self):
self.app = bottle.Bottle(catchall=... | nilq/baby-python | python |
# This code is designed to compare the absolute difference between one
# reference burn_cell test and multiple other burn_cell tests.
# burn_cell_testing.py must be run before running this.
# Around line 195, you choose which elements you will compare the xn and ydot of
# To change what you investigate, you must chan... | nilq/baby-python | python |
#!/usr/bin/python
import socket,os
import platform
""" NETLINK related stuff
Astrit Zhushi 2011, a.zhushi@cs.ucl.ac.uk
"""
NETLINK_CONNECTOR=11
NETLINK_ADD_MEMBERSHIP=1
def get_cn_idx_iwlagn():
uname = platform.uname()[2]
infile = open("/usr/src/linux-headers-%s/include/linux/connector.h"
%(uname), "r")
flag ... | nilq/baby-python | python |
"""
Employee service.
"""
from department_app import db
from department_app.models.department import Department
from department_app.models.employee import Employee
def add_employee_service(forename, surname, birthdate, department_id, salary):
"""
Adds employee to db.
:param forename: employee first name
... | nilq/baby-python | python |
### tensorflow==2.3.1
import tensorflow as tf
import tensorflow_datasets as tfds
import numpy as np
def representative_dataset_gen_480x640():
for data in raw_test_data.take(10):
image = data['image'].numpy()
image = tf.image.resize(image, (480, 640))
image = image[np.newaxis,:,:,:]
... | nilq/baby-python | python |
import bayesiancoresets as bc
import numpy as np
import warnings
warnings.filterwarnings('ignore', category=UserWarning) #tests will generate warnings (due to pathological data design for testing), just ignore them
np.seterr(all='raise')
np.set_printoptions(linewidth=500)
np.random.seed(100)
tol = 1e-9
def test_empty... | nilq/baby-python | python |
# MIT License
#
# Copyright (c) 2018 Silvia Amabilino
#
# 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, me... | nilq/baby-python | python |
# ro_prefixes.py
"""
Central list of prefixes commonly used with ROs
extended to support ro model updates and extensions for earth science (01/2017) by Raul Palma
"""
__authors__ = "Graham Klyne (GK@ACM.ORG), Raul Palma"
__copyright__ = "Copyright 2011-2013, University of Oxford"
__license__ = "MIT (http:/... | nilq/baby-python | python |
import random
from lxml import etree
from typing import List
from PIL import ImageDraw
from nonebot.log import logger
try:
import ujson as json
except ModuleNotFoundError:
import json
from .base_handle import BaseHandle, BaseData
from ..config import draw_config
from ..util import remove_prohibit... | nilq/baby-python | python |
"""Queries to answer following questions"""
# How many total Characters are there?
QUERY_1 = '''SELECT COUNT(*)
FROM charactercreator_character;'''
# How many of each specific subclass?
QUERY_2 = '''SELECT (
SELECT COUNT(*)
FROM charactercreator_thief
) AS thief_class,
(
SELECT COUNT(*)
FROM c... | nilq/baby-python | python |
from astutils import ast
def test_terminal():
value = 'a'
t = ast.Terminal(value)
r = repr(t)
assert r == "Terminal('a', 'terminal')", r
r = str(t)
assert r == 'a', r
r = len(t)
assert r == 1, r
r = t.flatten()
assert r == value, r
def test_hash():
# different AST node in... | nilq/baby-python | python |
num1 = 111
num2 = 222
num3 = 3333333333
num3 = 333
num4 = 44444
| nilq/baby-python | python |
# =============================================================================== #
# #
# This file has been generated automatically!! Do not change this manually! #
# ... | nilq/baby-python | python |
import os
import sys
import zipfile
import asc_parse
import wget
import multiprocessing
import urllib.request as request
from contextlib import closing
import argparse
import shutil
import glob
# A decimal value that will decrease the output file size as it increases
REDUCE_BY = 1.0
# A decimal value t... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.