content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets, svm
from sklearn.feature_selection import SelectPercentile, f_classif
# http://scikit-learn.org/stable/modules/feature_selection.html
# #############################################################################
# Univariate feature s... | nilq/baby-python | python |
#Enter a number and identify whether it is palindrome or not.
n=int(input("Enter a no.:"))
n1=n2=n
count=0
temp=0
ans=0
while n!=0:
n=n//10
count=count+1
#print("count=",count)
count=count-1
while n1!=0:
temp=n1%10
n1=n1//10
ans=ans+(10**count)*temp
count=count-1
#print("ans=... | nilq/baby-python | python |
from operator import attrgetter
import pyangbind.lib.xpathhelper as xpathhelper
from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType
from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType
from pyangbind.lib.base import PybindBase
from d... | nilq/baby-python | python |
import os
from mock import Mock
from mock import patch
from tests.base_unittest import BaseUnitTest
from aceonrivergui.server.game_manager import GameManager
import aceonrivergui.server.message_manager as MM
class MessageManagerTest(BaseUnitTest):
def test_broadcast_config_update(self):
uuids = ["hoge",... | nilq/baby-python | python |
import qt
import numpy as np
import os
import shutil
import sys
import progressbar
from constants import *
fsv = qt.instruments.create('FSV', 'RhodeSchwartz_FSV', address = FSV_ADDRESS)
## FSV parameters
center_frequency = 6018.416185*MHz
span = 2000*Hz
RBW = 10*Hz
numpoints = 501
ref_level = -70 #dB... | nilq/baby-python | python |
"""
This script is used to develop a baseline policy using only the observed patient data via Behavior Cloning.
This baseline policy is then used to truncate and guide evaluation of policies learned using dBCQ. It should only need to be
run once for each unique cohort that one looks to learn a better treatment policy ... | nilq/baby-python | python |
from twisted.internet.defer import inlineCallbacks
from zope.interface import implements
from vumi.dispatchers.base import BaseDispatchWorker
from vumi.middleware import MiddlewareStack
from vumi.tests.helpers import (
MessageHelper, PersistenceHelper, WorkerHelper, MessageDispatchHelper,
generate_proxies, IH... | nilq/baby-python | python |
test_cases = int(input().strip())
for t in range(1, test_cases + 1):
s = input().strip()
stack = []
bracket = {'}': '{', ')': '('}
result = 1
for letter in s:
if letter == '{' or letter == '(':
stack.append(letter)
elif letter == '}' or letter == ')':
if not ... | nilq/baby-python | python |
from typing import Dict, List, Union
from icolos.core.containers.compound import Compound
from icolos.core.containers.perturbation_map import Edge
from icolos.core.workflow_steps.pmx.base import StepPMXBase
from pydantic import BaseModel
from icolos.utils.enums.program_parameters import (
GromacsEnum,
StepPMXEn... | nilq/baby-python | python |
# Generated by Django 3.2.9 on 2022-02-06 17:56
import ckeditor.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pet', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='pet',
name='explan... | nilq/baby-python | python |
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Gabor
def Gabor_filter(K_size=111, Sigma=10, Gamma=1.2, Lambda=10, Psi=0, angle=0):
# get half size
d = K_size // 2
# prepare kernel
gabor = np.zeros((K_size, K_size), dtype=np.float32)
# each value
for y in range(K_size):
for x in range(K_size)... | nilq/baby-python | python |
from aoc21.days.day04 import Board, BoardScore
NUMBERS = [
7,
4,
9,
5,
11,
17,
23,
2,
0,
14,
21,
24,
10,
16,
13,
6,
25,
12,
22,
18,
20,
8,
19,
3,
26,
1,
]
BOARD = Board(
[
22,
13,
17,
... | nilq/baby-python | python |
from maza.core.exploit.option import OptEncoder
from maza.core.exploit.payloads import (
GenericPayload,
Architectures,
BindTCPPayloadMixin,
)
from maza.modules.encoders.perl.base64 import Encoder
class Payload(BindTCPPayloadMixin, GenericPayload):
__info__ = {
"name": "Perl Bind TCP",
... | nilq/baby-python | python |
"""
Flask-AntiJs
-------------
Flask-AntiJs is a Flask extension the protects endpoints against
'undefined' javascript values by checking the URL, query params and payloads
and return a 400 (Bad request) response.
"""
from setuptools import setup
version = "0.0.2"
setup(
name='Flask-AntiJs',
version=version,... | nilq/baby-python | python |
import configparser
import json
import os
import subprocess
import sys
import requests
import betamax
from betamax_serializers.pretty_json import PrettyJSONSerializer
import pytest
ABS_PATH = os.path.abspath(os.path.dirname(__file__))
FIXTURES_PATH = ABS_PATH + '/fixtures'
CASSETTES_PATH = FIXTURES_PATH + '/cassett... | nilq/baby-python | python |
"""
Solution to Compound Interest Calculator
"""
if __name__ == '__main__':
principal = input('Enter the Principal: ')
# type checking here
try:
principal = float(principal)
except ValueError:
print('Invalid principal Amount')
exit(0)
rate = input('Enter ... | nilq/baby-python | python |
# encoding: utf-8
"""
Core properties part, corresponds to ``/docProps/core.xml`` part in package.
"""
from __future__ import (
absolute_import, division, print_function, unicode_literals
)
from datetime import datetime
from ..constants import CONTENT_TYPE as CT
from ..extendedprops import ExtendedProperties
fr... | nilq/baby-python | python |
import pytest
from django.core.exceptions import ValidationError
from django.urls import reverse
from django.utils import timezone
from vms import models
def test_approve(client_admin_factory, employee_factory):
"""
Approving an employee should save the approval information and mark
the employee as activ... | nilq/baby-python | python |
class Solution:
def maximumCandies(self, candies: List[int], k: int) -> int:
l = 1
r = sum(candies) // k
def numChildren(m: int) -> bool:
return sum(c // m for c in candies)
while l < r:
m = (l + r) // 2
if numChildren(m) < k:
r = m
else:
l = m + 1
retur... | nilq/baby-python | python |
# Generated from grammar/Evans.g4 by ANTLR 4.7.2
from antlr4 import *
if __name__ is not None and "." in __name__:
from .EvansParser import EvansParser
else:
from EvansParser import EvansParser
# This class defines a complete listener for a parse tree produced by EvansParser.
class EvansListener(ParseTreeListe... | nilq/baby-python | python |
from builtins import object
import logging
from twisted.internet import abstract
from twisted.internet.tcp import Server
from twisted.internet import address, fdesc
log = logging.getLogger(__name__)
# AcceptedSocket
class AcceptedSocket(object):
transport = Server
def __init__(self, skt, addr, factory, re... | nilq/baby-python | python |
import unittest
from user import User
from credentials import Credentials
import pyperclip
class TestUser(unittest.TestCase):
"""
Test case that defines the behavior that should be evident in the user class
"""
new_user= User("Mary","Wanjiku","wanjiku254")
new_account_name= Credentials("Instagram","... | nilq/baby-python | python |
symbols = []
exports = [{'type': 'function', 'name': '??$_Getvals@_W@?$time_get@DV?$istreambuf_iterator@DU?$char_traits@D@std@@@std@@@std@@IEAAX_WAEBV_Locinfo@1@@Z', 'address': '0x7ffb3bb2d310'}, {'type': 'function', 'name': '??$_Getvals@_W@?$time_get@GV?$istreambuf_iterator@GU?$char_traits@G@std@@@std@@@std@@IEAAX_WAE... | nilq/baby-python | python |
#!/usr/bin/env python
# FormatTIFFRayonixESRF.py
# Copyright (C) 2011 Diamond Light Source, Graeme Winter
#
# This code is distributed under the BSD license, a copy of which is
# included in the root directory of this package.
#
# Sub class of FormatTiffRayonix to deal with images who have beam centers
# specifie... | nilq/baby-python | python |
from unittest.mock import Mock
import pytest
from sso.user import context_processors
@pytest.fixture
def request_with_next_user_authenticated(rf):
request = rf.get('/', {'next': 'http://www.example.com'})
request.user = Mock(is_authenticated=Mock(return_value=True))
return request
@pytest.fixture
def ... | nilq/baby-python | python |
from typing import Dict
from .expressions import (
Expression, Operation, Wildcard, AssociativeOperation, CommutativeOperation, SymbolWildcard, Pattern, OneIdentityOperation
)
__all__ = [
'is_constant', 'is_syntactic', 'get_head', 'match_head', 'preorder_iter', 'preorder_iter_with_position',
'is_a... | nilq/baby-python | python |
from openzwave.network import ZWaveNode
from openzwave.value import ZWaveValue
from Firefly import logging
from Firefly.components.zwave.zwave_device import ZwaveDevice
from Firefly.const import ACTION_OFF, ACTION_ON, AUTHOR, DEVICE_TYPE_SWITCH, LEVEL, SWITCH
from Firefly.helpers.device_types.switch import Switch
from... | nilq/baby-python | python |
import signal
import os
import subprocess
# Initializes a multi processing worker and prevents the interupt signal to be handled. This should be handled by the
# parent process.
def init_worker():
signal.signal(signal.SIGINT, signal.SIG_IGN)
def minimal_ext_cmd(cmd):
# construct minimal environment
env ... | nilq/baby-python | python |
"""Unit test package for aioxmppd."""
| nilq/baby-python | python |
#! /usr/bin/env python3
# coding: utf-8
# flow@SEA
# Licensed under the MIT License.
import time
import hashlib
import datetime
from binascii import unhexlify
from base58 import b58encode, b58decode
class CommonTool:
@staticmethod
def now():
return time.time()
@staticmethod
def sci_to_str(s... | nilq/baby-python | python |
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: bool
"""
s_len = len(s)
dp = [False] * (s_len+1)
dp[0] = True
for i in range(s_len):
for j in range(i+1, n+1):
... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
# input is a H*W ndarray
def display(npimg):
plt.imshow(npimg, cmap='gray')
plt.show()
if __name__ == '__main__':
images_path = "./HCL2000-100/HCL2000_100_train.npz"
labels_path = "./HCL2000-100/HCL2000_100_train_label.npz"
... | nilq/baby-python | python |
import socket
host, port = '', 8888
listen_socket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
listen_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
listen_socket.bind((host, port))
listen_socket.listen(1)
print("listening on port %s" % port)
while True:
client_connection, client_address = l... | nilq/baby-python | python |
import sys
from setuptools import setup
from setuptools.command.test import test as TestCommand
packageName = "arthur"
import re
versionLine = open("{0}/_version.py".format(packageName), "rt").read()
match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", versionLine, re.M)
versionString = match.group(1)
class Tox(... | nilq/baby-python | python |
import os
from pip._vendor.colorama import Fore
from ws.RLUtils.monitoring.tracing.log_mgt import log_mgt
if __name__ == '__main__':
cwd = os.path.curdir
acwd = os.path.join(cwd, '_tests')
log_dir = os.path.join(acwd, "logs")
fn_log = log_mgt(log_dir, show_debug=False, fixed_log_file=False)[0]
c... | nilq/baby-python | python |
real = float ( input(' Digite o valor em reais: R$'))
#dola = 5.34
dola = real / 5.34
euro = real / 6.25
print (' Convertendo o valor de R${:.2f}, você consegue US${:.2f} ou €{:.2f}.' .format( real,dola, euro))
#print (' Convertendo o valor de R${:.2f}, você consegue US${:.2f} ou € {:.2f}.'.format(real,(real/dola)))
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from openprocurement.auctions.core.tests.base import snitch
from openprocurement.auctions.core.tests.blanks.contract_blanks import (
# AuctionContractResourceTest
create_auction_contract_invalid,
get_auction_contracts,
# AuctionContractDocumentResourceTest
not_found,
crea... | nilq/baby-python | python |
matrix = [
#0, 1, 2, 3, 4, 5, 6, 7], #0
[0, 1, 1, 0, 0, 0, 0, 0], #0
[1, 0, 1, 1, 0, 0, 0, 0], #1
[1, 1, 0, 0, 0, 0, 0, 0], #2
[0, 1, 0, 0, 1, 1, 0, 0], #3
[0, 0, 0, 1, 0, 0, 1, 0], #4
[0, 0, 0, 1, 0, 0, 1, 0], #5
[0, 0, 0, 0, 1, 1, 0, 1], #6
[0, 0, 0, 0, 0, 0, 1, 0], #7... | nilq/baby-python | python |
from code.cli import Cli
if __name__ == '__main__':
Cli().run()
| nilq/baby-python | python |
import cv2
import shutil
import os
import numpy as np
from pathlib import Path
from tqdm import tqdm
from utils import get_all_files_in_folder
def create_images_for_labeling():
dirpath = Path('denred0_data/prepare_images_for_labeling/result')
if dirpath.exists() and dirpath.is_dir():
shutil.rmtree(d... | nilq/baby-python | python |
import datetime
import time
from huey import crontab
from hueyx.queues import hueyx
HUEY_Q1 = hueyx('queue1')
HUEY_Q2 = hueyx('queue2')
@HUEY_Q1.task()
def my_task1():
print('my_task1 called')
return 1
@HUEY_Q1.db_task()
def my_db_task1():
print('my_db_task1 called')
return 1
@HUEY_Q1.db_task(he... | nilq/baby-python | python |
"""The FleetGO component."""
| nilq/baby-python | python |
from typing import List
from .expresion_node import ExpressionNode
from .let_node import LetNode
class LetInNode(ExpressionNode):
def __init__(self, let_body: List[LetNode], in_body: ExpressionNode, line: int, column: int):
super(LetInNode, self).__init__(line, column)
self.let_body: List[LetNode]... | nilq/baby-python | python |
from pyspark import SparkContext, SparkConf
from pyspark.sql import SparkSession
import pyspark.sql as sql
from pyspark.sql.functions import *
from pyspark.sql.types import *
from collections import defaultdict
from pyspark.sql import functions as F
NUMBER_PRECISION = 2
def addSampleLabel(ratingSamples):
ratingS... | nilq/baby-python | python |
from django.shortcuts import render
# Create your views here.
def home(request):
return render(request, 'website_component/home.html', {'ViewName': request})
| nilq/baby-python | python |
"""
Entradas
Salidas
Impares-->int-->a
"""
a=0
while(a<100):
if(a%2!=0 and a%7!=0):
print(a)
a=a+1 | nilq/baby-python | python |
from pyplan_core.classes.wizards.BaseWizard import BaseWizard
import json
class Wizard(BaseWizard):
def __init__(self):
self.code = "CreateIndex"
def generateDefinition(self, model, params):
nodeId = params["nodeId"]
if model.existNode(nodeId):
base_node = model.getNode(n... | nilq/baby-python | python |
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
# Find the sum of all the multiples of 3 or 5 below the provided parameter value number.
# multiplesOf3and5(10) should return a number.
# multiplesOf3and5(49) should return 543.
# multiple... | nilq/baby-python | python |
# lextab.py. This file automatically created by PLY (version 3.6). Don't edit!
_tabversion = '3.5'
_lextokens = set(['DO', 'REMAINDER_ASSIGN', 'RSHIFT', 'SYNCHRONIZED', 'GTEQ', 'MINUS_ASSIGN', 'OR_ASSIGN', 'VOID', 'STRING_LITERAL', 'ABSTRACT', 'CHAR', 'LSHIFT_ASSIGN', 'WHILE', 'SHORT', 'STATIC', 'PRIVATE', 'LSHIFT... | nilq/baby-python | python |
from vpv.ui.controllers import importer
from pathlib import Path
import pytest
def test_folder_filter():
#path: str, folder_include_pattern: str
assert importer.folder_filter('/mnt/bit_nfs/neil/mutants/output/jag2/20150409_JAG2_E14.5_13.3f_HOM_XX_REC_scaled_4.6823_pixel_14.0001/output/registrations/deformable_... | nilq/baby-python | python |
from django.urls import path,include
from . import views
from bookshop.views import index
from django.contrib.auth import views as auth_views
urlpatterns = [
path('account/register',views.register,name='register'),
path('account/login',views.login,name='login'),
path('dashboard',index,name='dashboard'),
... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
from astropy.io import fits
from astropy import wcs
from astropy.io import ascii
# TODO set the
# UC4 296-009008
# (90.140913, -30.99747)
# ASASSN ID AP 18326421 V=12.79
def find_min(xobj,yobj, xlist, ylist):
'find the index of the star closest to position xobj,... | nilq/baby-python | python |
# @file globalclasses.py
# @brief global classes and objects
# -
# MODULE_ARCH:
# CLASS_ARCH:
# README:
# Global variables dependence:
#
#standard
#start.py
#[GAP=FastApp(), life_cycle: always exist]
#used by: start.py, scli.py
#init at: start.globalclasses_init()
global GAP
GAP=None
# refer configobj.readthed... | nilq/baby-python | python |
from http.server import HTTPServer, BaseHTTPRequestHandler
from logger import logger
from config import change_config, get_config
BADREQUEST = 400
handlers = {
'get': [],
'post': []
}
class BaseServer(BaseHTTPRequestHandler):
def match_and_call(self, method):
url = self.path.replace('..', '') #... | nilq/baby-python | python |
'''MIT License
Copyright (c) 2021 Aditya Dangwal
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish,... | nilq/baby-python | python |
from data_collection.management.commands import BaseHalaroseCsvImporter
class Command(BaseHalaroseCsvImporter):
council_id = "E07000107"
addresses_name = (
"local.2019-05-02/Version 1/polling_station_export-2019-03-04Dart.csv"
)
stations_name = (
"local.2019-05-02/Version 1/polling_sta... | nilq/baby-python | python |
import numpy as np
def check_temperature(T, melting_point=3000):
"""
Check if an instantaneous temperature will melt the divertor.
"""
if T > melting_point:
print("Destroyed divertor!")
melted = True
elif T <= 0:
raise ValueError("Unphysical temperature value!")
else:... | nilq/baby-python | python |
# T-SNEを用いた文章分散表現の可視化
import sys, os
sys.path.append('../')
from src import *
import matplotlib.pyplot as plt
import japanize_matplotlib
import numpy as np
from scipy import sparse
def visualize(xs, ys, labels, dataname):
plt.figure(figsize=(15, 15), dpi=300)
emotion = [ "happy", "sad", "angry", "fear/surp... | nilq/baby-python | python |
"""HOBO API"""
from __future__ import annotations
import json
import logging
import time
from typing import Any, List, Optional, Union
import requests
from ..exceptions import ResponseError
# https://docs.python.org/3/howto/logging.html#logging-basic-tutorial
logger = logging.getLogger('hobo_iot')
# logger.setLeve... | nilq/baby-python | python |
from Lib.statistics import mean, harmonic_mean, median, mode, median_low, median_high, median_grouped, stdev, pstdev, \
pvariance, variance, StatisticsError
class Statistics(object):
"""The library used to define statistical outputs"""
def __init__(self):
self.allTimers = []
self... | nilq/baby-python | python |
"""Simple test for using adafruit_motorkit with a DC motor"""
import time
import board
from adafruit_motorkit import MotorKit
kit = MotorKit(i2c=board.I2C())
kit.motor1.throttle = 1.0
time.sleep(0.5)
kit.motor1.throttle = 0
| nilq/baby-python | python |
#!/usr/bin/env 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 ... | nilq/baby-python | python |
from django.conf.urls import url, include
urlpatterns = [
url(r'^oauth2/', include('django_auth_adfs.urls')),
url(r'^oauth2/', include('django_auth_adfs.drf_urls')),
]
| nilq/baby-python | python |
from typing import List, Tuple
from instagrapi.exceptions import ClientError, HashtagNotFound
from instagrapi.extractors import (
extract_hashtag_gql,
extract_hashtag_v1,
extract_media_gql,
extract_media_v1,
)
from instagrapi.types import Hashtag, Media
from instagrapi.utils import dumps
class Hashta... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class ZhimaCreditEpDataRatingQueryResponse(AlipayResponse):
def __init__(self):
super(ZhimaCreditEpDataRatingQueryResponse, self).__init__()
self._amount = None
sel... | nilq/baby-python | python |
# Import from standard library
import logging
import datetime
import math
# Import from third-party
from flask import Flask, render_template, json, request, jsonify, session
import pytz
# Import local files
import DAO.db_connect as db_connect
from config.config import ElasticConfig
def nessus_overview():
try:
... | nilq/baby-python | python |
#!/usr/bin/env python
import distutils.log
import os
import subprocess
from distutils.spawn import find_executable
from setuptools import Command, find_packages, setup
from distutils.command.build import build
class BuildCommand(build):
def run(self):
self.run_command('compile_webui')
build.run(... | nilq/baby-python | python |
from PyQt5.QtCore import QSize, Qt
from PyQt5.QtGui import QResizeEvent
from PyQt5.QtWidgets import QScrollArea, QVBoxLayout, QWidget
from brainframe_qt.ui.resources import stylesheet_watcher
from brainframe_qt.ui.resources.mixins.style import TransientScrollbarMI
from brainframe_qt.ui.resources.paths import qt_qss_pa... | nilq/baby-python | python |
# coding: utf-8
import os
import logging
import sys
import torch
import time
import copy
# my staff
from models.modules.context_embedder_base import ContextEmbedderBase, BertContextEmbedder, \
BertSeparateContextEmbedder, NormalContextEmbedder, BertSchemaContextEmbedder, BertSchemaSeparateContextEmbedder, \
Ele... | nilq/baby-python | python |
# Copyright 2013 - Noorul Islam K M
#
# 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 w... | nilq/baby-python | python |
"""
Crie um módulo chamado moeda.py que tenha as funções incorporadas aumentar(),
diminuir(), dobro() e metade(). Faça também um programa que importe esse módulo e
use algumas dessas funções.
"""
import moeda
from exercicios.geral import tratamento
p = tratamento.leiaFloat('Digite o preço: R$', 'preço')
print(f'A met... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/5/12 14:44
# @Author : PPq
from __future__ import print_function
import argparse
import os
import shutil
import time
from torch.nn import DataParallel
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import ... | nilq/baby-python | python |
# Copyright (c) 2018 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 app... | nilq/baby-python | python |
from __future__ import print_function
import os
import sys
import re
import json
from copy import deepcopy
# Build job list
###########################################
def job_builder(meta, valid_meta, workflow, job_dir, out_dir, coprocess=None, other_args="", writeimg=False):
"""Build a list of image processing ... | nilq/baby-python | python |
from . import Plugin
class CatchallPlugin(Plugin):
priority = -5
"""
Turns metrics that aren't matched by any other plugin in something a bit more useful (than not having them at all)
Another way to look at it is.. plugin:catchall is the list of targets you can better organize ;)
Note that the ass... | nilq/baby-python | python |
import sys
import logging
import numpy as np
import sympy as sp
import ANNarchy_future.api as api
import ANNarchy_future.parser as parser
class Symbol(sp.core.Symbol):
"""Subclass of sp.core.Symbol allowing to store additional attributes.
"""
def __new__(self, name, method='euler'):
obj = sp.co... | nilq/baby-python | python |
from juriscraper.OpinionSite import OpinionSite
from datetime import datetime
import re
class Site(OpinionSite):
def __init__(self, *args, **kwargs):
super(Site, self).__init__(*args, **kwargs)
self.court_id = self.__module__
self.url = "http://www.courts.state.va.us/scndex.htm"
def _... | nilq/baby-python | python |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from core.views import JobList, JobDetail, JobCreate
admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'emplea_do.views.home', name='home'),
# url(r'^blog/', include('blog.urls')),
url(r'^$', J... | nilq/baby-python | python |
import RPi.GPIO as GPIO
import time
from pathlib import Path
import os
import sys
relay_signal = 4
# GPIO setup
GPIO.setmode(GPIO.BCM)
GPIO.setup(relay_signal, GPIO.OUT)
# pulls the signal pin high signalling the relay switch to close
def garage_btn_down(pin):
GPIO.output(pin, GPIO.HIGH) # Close OSC
# pulls ... | nilq/baby-python | python |
# Common libraries
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Restrict minor warnings
import warnings
warnings.filterwarnings('ignore')
# Import test and train data
df_train = pd.read_csv('../input/train.csv')
df_Test = pd.read_csv('../input/test.csv')
df_test = df_... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Gromov-Wasserstein transport method
===================================
"""
# Author: Erwan Vautier <erwan.vautier@gmail.com>
# Nicolas Courty <ncourty@irisa.fr>
#
# License: MIT License
import numpy as np
from .bregman import sinkhorn
from .utils import dist
... | nilq/baby-python | python |
# coding: utf-8
"""
Cloudbreak API
Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. SequenceIQ's Cloud... | nilq/baby-python | python |
"""initialize the connection and wait for a message directed at it"""
from irc import *
from decision import *
import os
import random
channel = "#bitswebteam"
server = "irc.freenode.net"
nickname = "EisBot"
irc = IRC()
irc.connect(server, channel, nickname)
while 1:
text = irc.get_text()
... | nilq/baby-python | python |
import pickle
import argparse
import cv2
from tqdm import tqdm
from lib.config import Config
def parse_args():
parser = argparse.ArgumentParser(description="Tool to generate qualitative results videos")
parser.add_argument("--pred", help=".pkl file to load predictions from")
parser.add_argument("--cfg",... | nilq/baby-python | python |
# Copyright (c) 2008, Willow Garage, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of co... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Copyright (c) 2018 Keitaro AB
Use of this source code is governed by an MIT license
that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
"""
"""
Executable module for checking github version updates for repositories from repositories.txt
and alerting the slack ch... | nilq/baby-python | python |
from enum import Enum
class Order(Enum):
ASC = "ASC"
DESC = "DESC"
class DatabaseType(Enum):
PSYCOPG2 = "PSYCOPG2"
SQLITE3 = "SQLITE3"
class Fetch(Enum):
ONE = "ONE"
ALL = "ALL"
| nilq/baby-python | python |
# -*- coding:utf-8 -*-
import threading
local_value = threading.local()
def test_put_thread(value):
local_value.value = value
test_read_thread()
def test_read_thread():
print(local_value.value + " in thread: %s" % threading.current_thread().name)
t1 = threading.Thread(target=test_put_thread, args=("张... | nilq/baby-python | python |
from flask import (Blueprint, render_template, redirect, request, url_for,
abort, flash)
from itsdangerous import URLSafeTimedSerializer
from app import app, models, db
from app.models import Survey, SurveyOptions
from app.forms import survey as survey_forms
from sqlalchemy import func
# Create a su... | nilq/baby-python | python |
# coding: utf-8
import os
import sys
from threading import Thread
sys.path.append(os.path.join(os.path.dirname(__file__), '../util'))
from pluginbase import PluginBase
class NotifierBase(PluginBase):
def __init__(self):
self.modtype = 'notifier'
super().__init__()
def start_notification(sel... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright (c) 2017, FinByz Tech Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
from frappe.utils import add_days
class TruckPartsInventory(Docum... | nilq/baby-python | python |
import pygame
import json
class Spritesheet:
# Takes in Spritesheet file name. Assumes a png and a json file exist
def __init__(self, filename):
self.filename = filename
self.sprite_sheet = pygame.image.load(filename).convert()
self.meta_data = self.filename.replace('png', 'js... | nilq/baby-python | python |
"""
This configuration file contains common data for
parametrizing various tests such as isotherms.
"""
PRESSURE_PARAM = [
(1, {}), # Standard return
(100000, {
'pressure_unit': 'Pa'
}), # Unit specified
(0.128489, {
'pressure_mode': 'relative'
}), # Mode relative
(12.8489, {
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import platform
import sys
if platform.system() != 'Linux':
sys.exit(-1)
from .killer import Killer
from .utils import load_config
parser = argparse.ArgumentParser(description='ssh key killer')
parser.add_argument('-c', '--config', dest='config', m... | nilq/baby-python | python |
# coding: utf-8
'''
@Date : 2021-05-05
@Author : Zekang Li
@Mail : zekangli97@gmail.com
@Homepage: zekangli.com
'''
import torch
import string
import torch.nn as nn
from transformers import *
SPECIAL_TOKENS = ["<bos>", "<eos>", "<info>", "<speaker1>", "<speaker2>", "<empty>", "<pad>"]
SPECIAL_TOKENS_... | nilq/baby-python | python |
import os
import json, decimal
import boto3
from boto3.dynamodb.conditions import Key, Attr
tableName = os.environ.get('ACCESS_TABLE_NAME')
def handler(event, context):
client = boto3.resource('dynamodb')
table = client.Table(tableName)
print(table.table_status)
print(event)
username = event['requestCont... | nilq/baby-python | python |
A_0219_9 = {0: {'A': 0.2420334938061355, 'C': -0.12964532145406094, 'E': -0.30716253311729963, 'D': -0.20136070573849837, 'G': 0.09315559829464488, 'F': 0.414085377622071, 'I': -0.11091042509341746, 'H': -0.40154576951031906, 'K': -0.11190222068525454, 'M': -0.16860437072777687, 'L': 0.20901824078912526, 'N': 0.0322878... | nilq/baby-python | python |
# from typing import Dict
# import os
# from unittest import TestCase, main
#
# import json
#
# from monolithcaching import CacheManager
#
#
# class TestCacheManager(TestCase):
#
# @staticmethod
# def get_meta_data(meta_data_path: str) -> Dict:
# with open(meta_data_path) as json_file:
# met... | nilq/baby-python | python |
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
traversal1 = l1
traversal2 = l2
dummy = head = ListNode(0)
carry = 0
while traversal1 != None or traversal2 != None or carry != 0:
i... | nilq/baby-python | python |
# coding=utf-8
import json
from common import constant
from common import errcode
from common.mylog import logger
from dao.question.question_dao import QuestionDao
from dao.question.user_question_map_dao import UserQuestionMapDao
from handlers.base.base_handler import BaseHandler
from myutil import tools
class GetQu... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.