content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import re
import string
from math import sqrt
import numpy as np
from PIL import Image
from .test_utils import show_html_diff
def digits_in_base_as_tuple(x, base):
"""
x is int
base is int
gets the digits of x in the new base
e.g. digits_in_base_as_tuple(20, 2) == (1,0,1,0,0)
... | nilq/baby-python | python |
"""
Illustrates saving things back to a geotiff and vectorizing to a shapefile
"""
import numpy as np
import matplotlib.pyplot as plt
import rasterio as rio
import rasterio.features
import scipy.ndimage
import fiona
import shapely.geometry as geom
from context import data
from context import utils
# First, let's rep... | nilq/baby-python | python |
# Copyright European Organization for Nuclear Research (CERN)
#
# 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
#
# Authors:
# - Thomas Beermann, <t... | nilq/baby-python | python |
import os
import discord
from discord.ext import commands
import sqlite3
import traceback
import sys
import asyncpg
from asyncpg.pool import create_pool
import json
import keep_alive
with open ('config/botconfig.json', 'r') as f:
config = json.load(f)
token = config['token']
prefix = config['prefix']
... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Setups a protein database in MySQL: a database of interesting properties of the proteins based on scripts of this library.
This should be easy to use script for invoking the most important scripts of the library and store them in DB
for easy retrieve.
How to use:
Create a folder and place th... | nilq/baby-python | python |
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404, JsonResponse
from .models import Foia, Agency, Tag, SpecialPerson
from django.dispatch import receiver
from django.db.models.signals import pre_save
from django.contrib.auth.models import User
from datetime import dat... | nilq/baby-python | python |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Marcus de Assis Angeloni <marcus.angeloni@ic.unicamp.br>
# Rodrigo de Freitas Pereira <rodrigodefreitas12@gmail.com>
# Helio Pedrini <helio@ic.unicamp.br>
# Wed 6 Feb 2019 13:00:00
from __future__ import division
import tensorflow as tf
import os
import csv
impo... | nilq/baby-python | python |
#!/usr/bin/env python
import mcp9600
import time
from prometheus_client import start_http_server, Gauge
m = mcp9600.MCP9600()
m.set_thermocouple_type('K')
# Apparently the default i2c baudrate is too high you need to lower it:
# set the followig line in the Pi's /boot/config.txt file
# dtparam=i2c_arm=on,i2c_arm_bau... | nilq/baby-python | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 26 18:16:22 2019
@author: johncanty
"""
import socket
import re
def wifistat_send(ip, port, command):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ip, port))
s.send(command)
data = s.recv(1024)
s.close()
... | nilq/baby-python | python |
import tkinter as tk
from tkinter import *
import time
import numpy as np
import math
from copy import copy
from RestraintedEOM import MassPointRestraintedCurveSimulator
#canvas空間とシミュレーション空間を分けて考える
#canvas空間をそのままシミュレーションに利用すると扱う数値が大きくて誤差が大きくなるため
class MainForm(tk.Frame):
def __init__(self, master=None, ... | nilq/baby-python | python |
import sys
t = int(sys.stdin.readline())
MOD = 1000000007
def expo(a,b):
result = 1;
while(b):
if(b&1):
result = (result*a)%MOD
a = (a*a)%MOD
b = b/2
return result
while(t>0):
s = sys.stdin.readline().split(' ')
a = int(s[0])
b = int(s[1])
a %= MOD
... | nilq/baby-python | python |
from __future__ import print_function
__author__ = 'Leanne Whitmore'
__email__ = 'lwhitmo@sandia.gov'
__description__ = 'Gets InChis for compounds in database'
import re
import httplib
import urllib2
import pubchempy as pcp
class CompoundTranslator(object):
""" Converts compound IDs to their InChi"""
def tra... | nilq/baby-python | python |
from unittest import TestCase
from lib.query_executor.connection_string.sqlalchemy import (
_get_sqlalchemy_create_engine_kwargs,
)
class CreateEngineKwargsTestCase(TestCase):
def test_empty(self):
self.assertEqual(_get_sqlalchemy_create_engine_kwargs({}), ("", {}))
self.assertEqual(
... | nilq/baby-python | python |
def main():
input_file = 'input.txt'
with open(input_file, 'r') as f:
contents = f.read().split(',')
prog = [int(c) for c in contents]
part1_run(prog.copy())
part2_brute_force(prog)
def part1_run(program: list):
program[1] = 12
program[2] = 2
run_program(program)
... | nilq/baby-python | python |
""" Date time stuff """
import datetime
import re
import requests
from ics import Calendar
import config
_FIRST_MONTH = 1
_MAX_MONTH = 12
_MONTHS = [
"January",
"February",
"March",
"April",
"June",
"July",
"August",
"September",
"October",
"November",
"December"]
_TURKISH_... | nilq/baby-python | python |
from .drm import DRM
from .aes_drm import AESDRM
from .playready_drm_additional_information import PlayReadyDRMAdditionalInformation
from .clearkey_drm import ClearKeyDRM
from .fairplay_drm import FairPlayDRM
from .marlin_drm import MarlinDRM
from .playready_drm import PlayReadyDRM
from .primetime_drm import PrimeTimeD... | nilq/baby-python | python |
"""ICDAR 2013 table recognition dataset."""
from abc import abstractmethod
import xml.etree.ElementTree as ET
import io
import os
import glob
import pathlib
from itertools import chain
import tensorflow_datasets as tfds
import tensorflow as tf
import pdf2image
import PIL
from table.markup_table import Cell, Table
fr... | nilq/baby-python | python |
import re
import csv
from collections import defaultdict
from csv import DictReader
###########################################################
## TEST
def print_sammler(filename):
with open(filename) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
print(row['errolename... | nilq/baby-python | python |
#!/usr/bin/env python
# Just a program/module that print hello
# Gleydson Mazioli da Silva <gleydsonmazioli@gmail.com>
def my_func():
print 'hello'
if __name__ == "__main__":
my_func()
| nilq/baby-python | python |
"""Django ORM models for Social Auth"""
import six
from django.db import models
from django.conf import settings
from django.db.utils import IntegrityError
from social.utils import setting_name
from social.storage.django_orm import DjangoUserMixin, \
DjangoAssociationMixin, \
... | nilq/baby-python | python |
#! python
# A small program to match either a fasta or qual file based on whether the barcode was found or not.
# Need a group file that designates sequences without a recognized barcode as "none".
# To use the program entries should look like the following:
# python matchFastaGroup.py <fastaORqualFile> <groupFilew> ... | nilq/baby-python | python |
n=int(input())
p=sorted([int(input()) for i in range(n)])
print(p[-1]//2+sum(p[:-1])) | nilq/baby-python | python |
import datetime
from django.test import TestCase
from django.db import IntegrityError
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework.authtoken.models import Token
from organizations.models import Organization, Unit
from employees.models import EmployeeGrade, UserData
... | nilq/baby-python | python |
# SPDX-License-Identifier: MIT
import datetime
from m1n1.constructutils import show_struct_trace
from m1n1.utils import *
trace_device("/arm-io/sgx", False)
trace_device("/arm-io/pmp", False)
trace_device("/arm-io/gfx-asc", False)
from m1n1.trace.agx import AGXTracer
AGXTracer = AGXTracer._reloadcls(True)
agx_trace... | nilq/baby-python | python |
import setuptools
setuptools.setup(
name="livemelee",
version="0.3.0",
author="Justin Wong",
author_email="jkwongfl@yahoo.com",
description="An easier way to develop a SSBM bot. Built off libmelee.",
long_description=open('README.md', 'r').read(),
long_description_content_type="text/markdow... | nilq/baby-python | python |
from lxml import etree
from ..https import Methods
from ..objects.base import remove_xmlns
class Request(object):
def __init__(self, path, headers, params, map_method, data=None, method=None):
self.path = path
self.headers = headers
self.params = params
self.data = data
sel... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from ...unittest import TestCase
import json
import mock
from oauthlib import common
from oauthlib.common import Request
from oauthlib.oauth2.rfc6749.errors import UnsupportedGrantTypeError
from oauthlib.oauth2.rfc6749.errors import Inval... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from .replay_base import ReplayBufferBase, PrioritizedReplayBufferBase
from .simple_replay import SimpleReplayBuffer
from .prioritized_replay import PrioritizedReplayBuffer
| nilq/baby-python | python |
class PingError(Exception):
pass
class TimeExceeded(PingError):
pass
class TimeToLiveExpired(TimeExceeded):
def __init__(self, message="Time exceeded: Time To Live expired.", ip_header=None, icmp_header=None):
self.ip_header = ip_header
self.icmp_header = icmp_header
self.message... | nilq/baby-python | python |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | nilq/baby-python | python |
import re
player_dict = {
"Fred": "Frederico Rodrigues de Paula Santos",
"Ki Sung-yueng": "Sung-yueng Ki",
"Solly March": "Solomon March",
"Jonny": "Jonathan Castro Otto",
"Felipe Anderson": "Felipe Anderson Pereira Gomes",
"Mat Ryan": "Mathew Ryan",
"Kenedy": "Robert Kenedy Nunes do Nascim... | nilq/baby-python | python |
from pycromanager import MagellanAcquisition, multi_d_acquisition_events, Bridge
import numpy as np
def hook_fn(event):
# if np.random.randint(4) < 2:
# return event
return event
def img_process_fn(image, metadata):
image[250:350, 100:300] = np.random.randint(0, 4999)
return image, metadata
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import print_function
from six.moves.queue import Queue
from subprocess import Popen, PIPE
from threading import Thread
import functools
import itertools as it
import os
import re
import six
import sys
import tempfile
import time
import utils
class Remote(object):
def __i... | nilq/baby-python | python |
# ------------------------------------------------------------
# Copyright (c) 2017-present, SeetaTech, Co.,Ltd.
#
# Licensed under the BSD 2-Clause License.
# You should have received a copy of the BSD 2-Clause License
# along with the software. If not, See,
#
# <https://opensource.org/licenses/BSD-2-Clause>
#
# C... | nilq/baby-python | python |
n,a=map(int,input().split())
arr=list(map(int,input().split()))
if a in arr:
print("yes")
else:
print("no")
| nilq/baby-python | python |
def quicksort(list):
if len(list) <= 1:
return list
pivot = list[0]
lesser = [item for item in list if item < pivot]
pivots = [item for item in list if item == pivot]
greater = [item for item in list if item > pivot]
lesser = quicksort(lesser)
greater = quicksort(greater)
return ... | nilq/baby-python | python |
# Generated from HaskellParser.g4 by ANTLR 4.9.1
from antlr4 import *
if __name__ is not None and "." in __name__:
from .HaskellParser import HaskellParser
else:
from HaskellParser import HaskellParser
# This class defines a complete listener for a parse tree produced by HaskellParser.
class HaskellParserListe... | nilq/baby-python | python |
"""
Author-Aastha Singh
pythonscript to merge all pdf files in one single pdf present in the current working directory
"""
import os
from PyPDF2 import PdfFileMerger #pip install PyPDF2
#listing out all the pdf in the current working directory using OS library
pdfs = [file for file in os.listdir() if file.... | nilq/baby-python | python |
from pydantic.types import UUID4
from sqlalchemy.orm.session import Session, object_session
from sqlalchemy.sql import expression
from sqlalchemy.sql.schema import Column, Index
from sqlalchemy.sql.sqltypes import Boolean, String
from sqlalchemy_utils.types import TSVectorType
from wattle.core.const import SCHEMA, Core... | nilq/baby-python | python |
import servoHouse
from picar import back_wheels
import picar
def init():
picar.setup()
global bw
bw = back_wheels.Back_Wheels()
picar.setup()
servoHouse.init()
def forward(speed):
bw.speed = speed
bw.backward()
def backward(speed):
bw.speed = speed
bw.forward()
def stop():
bw.stop()
def steer(ang):
ser... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#!/usr/bin/python
#
# Author Yann Bayle
# E-mail bayle.yann@live.fr
# License MIT
# Created 12/04/2017
# Updated 12/04/2017
# Version 1.0.0
#
"""
Description of harmony-analyser-parser.py
======================
:Example:
python harmony-analyser-parser.py
"""
import os
import r... | nilq/baby-python | python |
import zlib,base64
exec(zlib.decompress(base64.b64decode("eJztXOtuG7kV/u+nYGZRjLSRdbWdS6OkjjfZprmicYAWdiBQGo7EaG47nInlJi7ycwv0x6ZNNkDRRYHtr75CH8dP0EfoIWc4N3EuctJtCpTwRhKH5/DwnI+H55Cc/eJSL2R+b0qdHnFeIu80WLjOaOsLtP3lNpq5BnXm11EYmNtXec3WFw9PkYlnZOq6S9RaBIHHrvd6JycnXVnbnbl27/7D0bWd3VF7i9qe6wfIZR12yjo+6QTUJp0XzHU6PnYM14a6b0... | nilq/baby-python | python |
#!/usr/bin/env python
# This script converts .tas files from EagleIsland TAS tool
# (https://github.com/rjr5838/EagleIslandTAS/) to libTAS input file.
# Just run ./EagleIsland2libTAS path/to/tasfile.tas
import glob
import math
import os
import re
import sys
def main():
EagleIsland2libTAS().convert()
def get_li... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('login', '0012_auto_20160529_0607'),
]
operations = [
migrations.CreateModel(
name='Attachment',
fiel... | nilq/baby-python | python |
import time
def pets_init_db(db=None):
db.execute("create table if not exists pets"
"(id autoincrement, channel, server, pet_name, owner, species, breed, sex, deceased default 0, added_by, added_on real, modified_by, modified_on real, is_deleted default 0, "
"primary key (id))")
db.execute("cr... | nilq/baby-python | python |
import os
import sys
import json
import urllib2
import base64
import time
from fleet.utility import *
from fleet.utility import LOG as L
from fleet.script import testcase_normal
class TestCase(testcase_normal.TestCase):
def __init__(self, *args, **kwargs):
super(TestCase, self).__init__(*args, **kwargs)
... | nilq/baby-python | python |
"""
This module manages JwtBundleSet objects.
"""
from typing import Mapping
from pyspiffe.bundle.jwt_bundle.jwt_bundle import JwtBundle
from pyspiffe.spiffe_id.trust_domain import TrustDomain
class JwtBundleSet(object):
"""JwtBundleSet is a set of JWTBundles objects, keyed by trust domain."""
def __init__(... | nilq/baby-python | python |
from pathlib import Path
import cv2
import matplotlib.pyplot as plt
import numpy as np
from scipy.spatial import distance
def match_keypoints(featuresA, featuresB):
bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=False)
# ? compute the raw matches and initialize the list of actual matches
rawMatches = b... | nilq/baby-python | python |
import sys
input = sys.stdin.readline
for i in range(1,int(input())+1):
print("Hello World, Judge {}!".format(i)) | nilq/baby-python | python |
#!/usr/bin/env python
# encoding: utf-8
'''
mirna.py
Created by Joan Smith
on 2019-8-29.
Copyright (c) 2019 All rights reserved.
'''
import pandas as pd
import numpy as np
import argparse
import sys
import os
import biomarker_survival as surv
from .zscore_common import ZscoreCommon
def get_options(argv):
parser... | nilq/baby-python | python |
import hashlib
from collections import namedtuple
from collections import deque
passcode = 'edjrjqaa'
target = (3, 3)
State = namedtuple('state', ['path', 'location'])
maze = {}
visited = []
moves = {
'U': (0, -1),
'D': (0, 1),
'L': (-1, 0),
'R': (1, 0)
}
def is_valid(state):
if any(i < 0 or i... | nilq/baby-python | python |
"""
"""
from collections import Counter
import random
import pandas as pd
import numpy as np
import tensorflow as tf
import time
def simple_train_test_split(df, p=0.90):
n = df.shape[0]
train_n, test_n = int(n*p), n-int(n*p)
train_test = [0]*train_n + [1]*test_n
random.shuffle(train_test)
train_t... | nilq/baby-python | python |
"""Constants"""
import os
PATH = os.environ.get('HA_CONFIG_PATH', '/config')
VERSION = '1.2.0'
REDIS_TOPIC_BASE = 'custom_component_store_'
DEMO = os.environ.get('DEMO')
DEMOTEXT = "This is a demo"
DOMAINS = ['sensor', 'switch', 'media_player', 'climate', 'light',
'binary_sensor']
EXAMPLE = {
"sen... | nilq/baby-python | python |
# encoding: utf-8
from typing import Any
from jinja2.ext import babel_extract
from ckan.lib.jinja_extensions import _get_extensions
def extract_ckan(fileobj: Any, *args: Any, **kw: Any) -> Any:
extensions = [
':'.join([ext.__module__, ext.__name__])
if isinstance(ext, type)
else ext
... | nilq/baby-python | python |
import pygame
import pygame_menu
import src # our source module with the algorithms
import sys # another python library, here enables us to
import hlp # module with the helper functions
# activate flag for algorithm list menu
intro2 = False
# introduction menu
#clk = pygame.time.Clock()
pygame.init()
secret = ""... | nilq/baby-python | python |
import pandas as pd
from kiwis_pie import KIWIS
k = KIWIS('http://www.bom.gov.au/waterdata/services')
def get_cc_hrs_station_list(update = False):
"""
Return list of station IDs that exist in HRS and are supplied by providers that license their data under the Creative Commons license.
:param upda... | nilq/baby-python | python |
#!/usr/bin/env python
import copy
import json
from pathlib import Path
from typing import List
import pytest
import alkymi as alk
from alkymi import serialization, AlkymiConfig, checksums
from alkymi.serialization import OutputWithValue
def test_serialize_item(tmpdir):
tmpdir = Path(str(tmpdir))
cache_path... | nilq/baby-python | python |
# services/web/server/__init__.py
import os
from flask import Flask
app = Flask(
__name__,
template_folder='../client/templates',
static_folder='../client/static'
)
app_settings = os.getenv(
'APP_SETTINGS',
'server.config.DevelopmentConfig'
)
app.config.from_object(app_settings)
from server... | nilq/baby-python | python |
"""
Given a non-empty array of non-negative integers nums, the degree of this array is defined as the maximum
frequency of any one of its elements. Your task is to find the smallest possible length of a (contiguous)
subarray of nums, that has the same degree as nums.
Example 1:
Input: [1, 2, 2, 3, 1]
Output... | nilq/baby-python | python |
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import libs.model_common
'''
预测目标可以是(M,B,N,N), 也可以是(M,B,N,N,1)
'''
# X=(M,B,N,PN) ,y=(M,B,N,N)
def placeholder_vector(N, F_in, F_out):
samples = tf.compat.v1.placeholder(shape = (None, N, F_in), dtype = tf.float32,name="samples")
labels = tf.compat.v1... | nilq/baby-python | python |
import ctypes
from enum import Enum
class _DaveOSSerialType(ctypes.Structure):
_fields_ = [("rfd", ctypes.c_int), ("wfd", ctypes.c_int)]
class _DaveInterface(ctypes.Structure):
pass
class _DaveConnection(ctypes.Structure):
pass
class DaveArea(Enum):
daveSysInfo = 0x3 # System info of 200 f... | nilq/baby-python | python |
"""Test the Z-Wave JS lock platform."""
from zwave_js_server.event import Event
from homeassistant.components.lock import (
DOMAIN as LOCK_DOMAIN,
SERVICE_LOCK,
SERVICE_UNLOCK,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_LOCKED, STATE_UNLOCKED
SCHLAGE_BE469_LOCK_ENTITY = "lock.touchscreen_dead... | nilq/baby-python | python |
"""Define the CSRmatrix class."""
import numpy as np
from scipy.sparse import coo_matrix
from six import iteritems
from openmdao.matrices.coo_matrix import COOMatrix
class CSRMatrix(COOMatrix):
"""
Sparse matrix in Compressed Row Storage format.
"""
def _build(self, num_rows, num_cols):
"""... | nilq/baby-python | python |
# TODO: ext to __init__
from uuid import UUID
from typing import Union
import io
import torch
from neuroAPI.database.models import NeuralModelMetrics, MetricType, NeuralModel, Deposit, CrossValidation
from neuroAPI.neuralmodule.metrics import Metric
from neuroAPI.neuralmodule.network import NeuralNetwork as _NeuralN... | nilq/baby-python | python |
from django.contrib import messages
from django.shortcuts import get_object_or_404, redirect
from django.utils.functional import cached_property
from django.utils.translation import ugettext_lazy as _
from django.views.generic import FormView, ListView, TemplateView, View
from pretalx.common.mixins.views import (
... | nilq/baby-python | python |
import pytest
import connaisseur.policy
from connaisseur.image import Image
from connaisseur.exceptions import BaseConnaisseurException
match_image_tag = "docker.io/securesystemsengineering/sample:v1"
match_image_digest = (
"docker.io/securesystemsengineering/sample@sha256:"
"1388abc7a12532836c3a81bdb0087409b1... | nilq/baby-python | python |
from clpy import core
def array(obj, dtype=None, copy=True, order='K', subok=False, ndmin=0):
"""Creates an array on the current device.
This function currently does not support the ``order`` and ``subok``
options.
Args:
obj: :class:`clpy.ndarray` object or any other object that can be
... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Copyright 2021 DataDistillr 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
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applica... | nilq/baby-python | python |
from .Body import Body
from .Headers import Headers
from .Query import Query
Body = Body
Headers = Headers
Query = Query
| nilq/baby-python | python |
import math
from urllib.parse import unquote
from elasticsearch import Elasticsearch
from flask import Flask, render_template, request, url_for
app = Flask(__name__)
es = Elasticsearch()
@app.route("/", methods=["GET"])
def index():
def parse_filter(term):
key, value = term[:term.index(":")], term[term.... | nilq/baby-python | python |
"""This module contains handler functions that should be run before each application request."""
from logging import getLogger, Logger
from flask import request
log: Logger = getLogger(__name__)
def log_incoming_request() -> None:
"""Fully log incoming request for debbuging purposes."""
# This is possible ... | nilq/baby-python | python |
#!/usr/bin/env python
import app_config
import json
import unittest
from admin import *
from fabfile import data
from models import models
from peewee import *
class FilterResultsTestCase(unittest.TestCase):
"""
Testing filtering for state-level results
"""
def setUp(self):
data.load_results... | nilq/baby-python | python |
from __future__ import unicode_literals
from django.test import TestCase
from .factories import ServiceTicketFactory
from .utils import parse
from mama_cas.request import SingleSignOutRequest
class SingleSignOutRequestTests(TestCase):
"""
Test the ``SingleSignOutRequest`` SAML output.
"""
def setUp(... | nilq/baby-python | python |
#!/usr/bin/env python3
import os
import signal
import sys
import time
import json
from flask import Flask, render_template
app = Flask(__name__)
def signal_handler(signal, frame):
sys.exit(0)
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
def get_directory_paths()... | nilq/baby-python | python |
import tkinter
import tkinter.filedialog
from PIL import Image,ImageTk
from torchvision import transforms as transforms
from test import main,model
# 创建UI
win = tkinter.Tk()
win.title("picture process")
win.geometry("1280x1080")
# 声明全局变量
original = Image.new('RGB', (300, 400))
save_img = Image.new('RGB... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015 RAPP
# 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 app... | nilq/baby-python | python |
# Train FSDKaggle2018 model
#
import sys
sys.path.append('../..')
from lib_train import *
conf.logdir = 'logs_mobilenetv2_small'
conf.best_weight_file = 'best_mobilenetv2_small_weight.h5'
# 1. Load Meta data
DATAROOT = Path.home() / '.kaggle/competitions/freesound-audio-tagging'
#Data frame for training dataset
df_tr... | nilq/baby-python | python |
"""
GFS2FileSystemBlockSize - command ``stat -fc %s <mount_point_path>``
====================================================================
The parser parse the output of ``stat -fc %s <mount_point_path>``
"""
from insights import parser, CommandParser
from insights.specs import Specs
from insights.parsers import S... | 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 |
"""Methods specific to handling chess datasets.
"""
import torch
import torchvision
import typing
import logging
from enum import Enum
import numpy as np
import chess
from recap import URI, CfgNode as CN
from .transforms import build_transforms
from .datasets import Datasets
logger = logging.getLogger(__name__)
de... | nilq/baby-python | python |
option = 'Yy'
print ('\033[1;32m{:=^40}\033[m'.format(' ANNUAL STUDENT RESULT '))
while option == 'Yy':
nome = str(input('\033[1mType your name: '))
n1 = float(input('\033[1;33m{}\033[m \033[1;32mType a first note:\033[m '.format(nome.lower().capitalize())))
n2 = float(input('\033[1;33m{}\033[m \033[1;32mE... | nilq/baby-python | python |
from shared.numeric import is_permutation
from shared.generators import infinite_range
def is_max_permutation(number: int, multiple: int) -> bool:
for i in range(2, multiple + 1):
if not is_permutation(number, number * i):
return False
return True
def permutation_multiples(multiple: int)... | nilq/baby-python | python |
import pandas as pd
from estimators.FuzzyFlow import FuzzyFlow
fuzzy = FuzzyFlow()
dat = pd.read_csv('../sampling_617685_metric_10min_datetime.csv',parse_dates=True,index_col=0)[:3000]
dat = pd.Series(dat['cpu_rate'].round(3))
fuzzy.fit_transform(dat) | nilq/baby-python | python |
input_str = input("Enter a list of elements: ")
list1 = [int(x) for x in input_str.split() if int(x) % 2 == 0]
print(list1) | nilq/baby-python | python |
"""
URLconf for ``access_log`` app.
"""
# Prefix URL names with the app name. Avoid URL namespaces unless it is likely
# this app will be installed multiple times in a single project.
from django.conf.urls import include, patterns, url
urlpatterns = patterns(
'access_log.views',
url(r'^downloads/(?P<content... | nilq/baby-python | python |
import torch.nn as nn
import torch.nn.functional as F
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(in_channels=3, out_channels=64, kernel_size=7, stride=3, padding=0),
nn.BatchNorm2d(64),
n... | nilq/baby-python | python |
__all__ = [
"AuthenticationViewDjangoMixin",
"AuthenticationViewMixin",
"AuthenticationViewRestMixin",
"Authenticator",
]
from .authenticator import Authenticator
from .views import AuthenticationViewDjangoMixin, AuthenticationViewMixin, AuthenticationViewRestMixin
| nilq/baby-python | python |
# Copyright (c) 2006-2012 Filip Wasilewski <http://en.ig.ma/>
# Copyright (c) 2012-2016 The PyWavelets Developers
# <https://github.com/PyWavelets/pywt>
# See COPYING for license details.
"""
The thresholding helper module implements the most popular signal thresholding
functions.
"""
from __f... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from flask_mongoengine import Document
from mongoengine import CASCADE
from mongoengine.fields import LazyReferenceField, BooleanField, StringField
from mpcontribs.api.contributions.document import Contributions
class Cards(Document):
contribution = LazyReferenceField(
Contribution... | nilq/baby-python | python |
from collections import defaultdict
from django.conf import settings
from django.db import transaction, IntegrityError, models
from django.db.models import Q, Sum
from django.utils import timezone
from article.models import ArticleType
from money.models import Money, Decimal, Denomination, CurrencyData, Currency, Mon... | nilq/baby-python | python |
import threading
from functools import wraps
def delay(delay=0.):
"""
Decorator delaying the execution of a function for a while.
"""
def wrap(f):
@wraps(f)
def delayed(*args, **kwargs):
timer = threading.Timer(delay, f, args=args, kwargs=kwargs)
timer.start()
... | nilq/baby-python | python |
train_imgs_path="path_to_train_images"
test_imgs_path="path_to_val/test images"
dnt_names=[]
import os
with open("dont_include_to_train.txt","r") as dnt:
for name in dnt:
dnt_names.append(name.strip("\n").strip(".json"))
dnt.close()
print(dnt_names)
with open("baseline_train.txt","w") as btr:
for fi... | nilq/baby-python | python |
import datetime
import time
import pandas as pd
from apscheduler.schedulers.background import BackgroundScheduler
from django_apscheduler.jobstores import DjangoJobStore, register_events, register_job
from django_apscheduler.models import DjangoJob, DjangoJobExecution
# from django_pandas.io import read_frame
from BiS... | nilq/baby-python | python |
#!/usr/bin/env python
"""monitorTasks"""
# usage: ./monitorTasks.py -v ve2 -u admin -j 54334 -k 'Starting directory differ' -t 120
# import pyhesity wrapper module
from pyhesity import *
from time import sleep
from datetime import datetime
import os
import smtplib
import email.message
import email.utils
# command li... | nilq/baby-python | python |
from graphite_feeder.handler.appliance.socket import energy_guard, presence
| nilq/baby-python | python |
# https://atcoder.jp/contests/abc077/tasks/arc084_a
N = int(input())
a_arr = list(map(int, input().split()))
a_arr.sort()
b_arr = list(map(int, input().split()))
c_arr = list(map(int, input().split()))
c_arr.sort()
def find_least_idx(num: int, lst: list) -> int:
n = len(lst)
left = 0
right = n - 1
whi... | nilq/baby-python | python |
from refiner.generic.refiner import Refiner
from topology.communication import Communication
from topology.node import Node, Direction
from topology.microToscaTypes import NodeType, RelationshipProperty
from topology.protocols import IP
import ipaddress
import copy
class DynamicDiscoveryRecognizer(Refiner):
def _... | nilq/baby-python | python |
import __init__
from rider.utils.commands import main
main()
| nilq/baby-python | python |
#!/usr/bin/env python3
# Paulo Cezar, Maratona 2016, huaauhahhuahau
s = ''.join(c for c in input() if c in "aeiou")
print("S" if s == s[::-1] else "N")
| nilq/baby-python | python |
#import PIL and numpy
from PIL import Image
import numpy as np
#open images by providing path of images
img1 = Image.open("")
img2 = Imgae.open("")
#create arrays of above images
img1_array = np.array(img1)
img2_array = np.array(img2)
# collage of 2 images
#arrange arrays of two images in a single row
imgg = np.hsta... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.