content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
from keras.models import Sequential, model_from_json
from keras.layers.core import Dense, Activation, Flatten, Dropout, Lambda
from keras.layers import Cropping2D
from keras.layers.convolutional import Conv2D
from keras.layers.pooling import MaxPooling2D
from keras.layers.advanced_activations import ELU
from keras.opti... | nilq/baby-python | python |
#!/usr/bin/env python
import logging
from p4p.client.thread import Context
_log = logging.getLogger(__name__)
def getargs():
from argparse import ArgumentParser
P = ArgumentParser()
P.add_argument('pvname', help='SIGS pvname (eg. RX:SIG')
P.add_argument('filename', help='list of BSA/signal PV names.... | nilq/baby-python | python |
#!/usr/bin/env python
# coding: utf-8
import rospy
import tf
from geometry_msgs.msg import PoseStamped
from sensor_msgs.msg import JointState
from std_msgs.msg import Float64
import numpy as np
class Pose_pub:
def __init__(self):
self._sub_pos = rospy.Subscriber("/head", PoseStamped, self.pose_callback)
... | nilq/baby-python | python |
"""
语言概念与机制
http://coolpython.net/python_interview/basic/py_concept_mechanism.html
"""
# 01 谈下GIL 全局解释器锁
# 02 遍历文件夹,输出文件夹下所有文件的路径
import os
def print_directory_contents(path):
test02_dirList = os.listdir(path)
for childfile in test02_dirList:
childPath = os.path.join(path, childfile)
# 判断为文件夹... | nilq/baby-python | python |
import gzip
import jsonpickle
from mdrsl.rule_models.eids.st_to_mt_model_merging import MergedSTMIDSClassifier
def store_merged_st_mids_model(merged_model_abs_file_name: str, merged_st_mids_classifier: MergedSTMIDSClassifier) -> None:
frozen = jsonpickle.encode(merged_st_mids_classifier)
with gzip.open(merg... | nilq/baby-python | python |
#https://www.youtube.com/watch?v=2egPL5KFCC8&list=PLGKQkV4guDKEKZXAyeLQZjE6fulXHW11y&index=2
#java scrip cannot be pull by beautifulsoap, java scrip use sileniun
#resultdo 0 para atributo existentem, vem exemplo imagem como pegar
import requests
from bs4 import BeautifulSoup
url = "https://www.marketwatch.com/"
respons... | nilq/baby-python | python |
# coding: utf-8
"""
jatdb
JSON API to DB: Fetch JSON from APIs and send to a TinyDB database. # noqa: E501
OpenAPI spec version: 0.0.2
Contact: Nathan@Genetzky.us
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
impor... | nilq/baby-python | python |
import json
import os
import sys
import re
import pickle
import logging
import gzip
import shutil
import urllib.request
from tqdm import tqdm
from collections import defaultdict
from utils.data_utils import load_jsonl_file, create_pkl_file, load_pkl_file
module_path = os.path.dirname(os.path.abspath(__file__))
# ---... | nilq/baby-python | python |
KEYWORDS = ["dev", "backup", "develop", "int", "internal", "staging", "test"]
with open("../../roots.txt") as roots:
with open("targets.txt", "w+") as targets:
for domain in roots:
for keyword in KEYWORDS:
target = domain.strip("\n") + "-" + keyword.strip("\n") + ".oss.eu-west-1.... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Module docstring
TODO:
* Write module docstring
"""
from .player.dealer import Dealer
from .player.player import Player
from .carddeck.deck import Deck
class Game():
"""Class to represent the blackjack Game"""
def __init__(self):
self.dealer = Dealer()
self.pl... | nilq/baby-python | python |
from flask_pymongo import PyMongo
from flask_compress import Compress
from flask_cors import CORS
from flask_bcrypt import Bcrypt
from itsdangerous import URLSafeTimedSerializer
mongo = PyMongo()
flask_bcrypt = Bcrypt()
flask_compress = Compress()
flask_cors = CORS(resources={"/api/*": {"origins": "*"}})
RECAPTCHA_SI... | nilq/baby-python | python |
#
# Jasy - Web Tooling Framework
# Copyright 2013-2014 Sebastian Werner
#
import json
import copy
class AbstractNode(list):
__slots__ = [
# core data
"line", "type", "tokenizer", "start", "end", "rel", "parent",
# dynamic added data by other modules
"comments", "scope", "values"... | nilq/baby-python | python |
from useless import base
from useless.base import *
class Resolver(CMakePackage):
def __init__(self):
super().__init__()
self.name = 'openvdb'
self.depends(require('openexr'))
self.depends(require('tbb'))
self.depends(require('boost'))
self.set('USE_BLOSC','OFF')
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
""" Diffraction image analysis """
from .alignment import (
align,
ialign,
shift_image,
itrack_peak,
masked_register_translation,
)
from .calibration import powder_calq
from .correlation import mnxc, xcorr
from .metrics import (
snr_from_collection,
isnr,
mask_fr... | nilq/baby-python | python |
class AbstractObject(object):
def __init__(self):
pass
def get_class(self, universe):
raise NotImplementedError("Subclasses need to implement get_class(universe).")
def get_object_layout(self, universe):
raise NotImplementedError(
"Subclasses need to implement get_objec... | nilq/baby-python | python |
"""
Tests for Galaxy Queue Worker
"""
| nilq/baby-python | python |
from io import BytesIO
import json
import cgi
from pathlib import Path
from abeja.common.docker_image_name import DockerImageName, ALL_GPU_19_04, ALL_CPU_19_10
from abeja.training import JobDefinition, JobDefinitionVersion # noqa: F401
def test_job_definition_version(
requests_mock,
api_base_url,
... | nilq/baby-python | python |
"""
Import as:
import dataflow.core.dag_adapter as dtfcodaada
"""
import logging
from typing import Any, Dict, List
import core.config as cconfig
import dataflow.core.builders as dtfcorbuil
import dataflow.core.dag as dtfcordag
import dataflow.core.node as dtfcornode
import helpers.hdbg as hdbg
import helpers.hprint... | nilq/baby-python | python |
from distutils.core import setup
setup(name='DefenseLab',
version='1.0',
author='Andrew Meserole',
packages=['DefenseLab', ])
| nilq/baby-python | python |
#!/usr/bin/python
#_*_coding:utf-8_*_
import sys
# Point类
class Point:
lng = ''
lat = ''
def __init__(self,lng,lat):
self.lng = lng
self.lat = lat
def show(self):
print self.lng,"\t",self.lat
#采用射线法判断点是否在多边形集内
def isPointsInPolygons(point,xyset):
... | nilq/baby-python | python |
from . import utils
from discord.utils import get
async def update_admins(guild, bot_log):
role_admin = get(guild.roles, name='Админ')
role_past_admin = get(guild.roles, name='Бивш Админ')
for admin in utils.get_members_with_role(guild, role_admin):
await bot_log.send(f'{admin.mention}')
... | nilq/baby-python | python |
from statistics import multimode
def migratoryBirds(arr):
mode = multimode(arr)
mode.sort()
return mode[0]
if __name__ == "__main__":
arr = [1 ,2 ,3 ,4 ,5 ,4 ,3 ,2 ,1 ,3 ,4]
print(migratoryBirds(arr)) | nilq/baby-python | python |
'''Test configuration constants, functions ...
'''
import subprocess
import os
import unittest
TVM_ROOT_PART='may not need'
TVM_SWAP_PART='may not need'
TVM_HOSTNAME='cworld.local'
TVM_GITREPO_URL = 'git@cworld.local'
def product_topdir():
'''return the project's top level directory (according to git)
'''
... | nilq/baby-python | python |
import pytest
from core import helpers
@pytest.mark.parametrize('path,expected_prefix', (
('/', 'en-gb'),
('/ar/', 'ar'),
('/es/industries/', 'es'),
('/zh-hans/industries/', 'zh-hans'),
('/de/industries/aerospace/', 'de'),
('/fr/industries/free-foods/', 'fr'),
))
def test_get_language_from_pr... | nilq/baby-python | python |
from os import path, environ
from imgaug import augmenters as iaa
from keras import backend as K
from keras import optimizers
from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau
from keras.layers import BatchNormalization, Activation
from keras.layers import Input, Conv2D, MaxPooling2D, GlobalAveragePooling... | nilq/baby-python | python |
# mb, 2012-05-26, 2013-02-28
import os
import sys
import subprocess
import shutil
from datetime import datetime
ospj = os.path.join
dest_path_to_extensions = '/home/mbless/public_html/TYPO3/extensions'
tempdir = '/home/mbless/HTDOCS/render-ter-extensions/temp'
proceeding = True
stats = {}
def walk_ter_extensions_... | nilq/baby-python | python |
def test(i):
print("test", i)
def add_test(mf):
def add_test_print(i):
print("added to test", i)
mf.register_event("test", add_test_print, unique=False)
def main(event):
event.test(0)
event.add_test()
event.test(1)
def register(mf):
mf.register_event("test", test, unique=False... | nilq/baby-python | python |
"""
Entendendo Interadores e Iteraveis
#Interador
- Um objeto que poder ser iterado
- Um objeto que retorna um dado, sendo um elemento por vez quando uma função next() é chamada;
#Interaveis
- Um objeto que irá retorna um interator quando inter() for chamada.
""" | nilq/baby-python | python |
from infosystem.common.subsystem import router
class Router(router.Router):
def __init__(self, collection, routes=[]):
super().__init__(collection, routes)
@property
def routes(self):
# TODO(samueldmq): is this the best way to re-write the defaults to
# only change bypass=true fo... | nilq/baby-python | python |
from ubikagent import Project
from ubikagent.introspection import get_methods
class DummyAgent:
"""Test class needed by `InstantiableProject` and `TestProject`."""
pass
class NonInstantiableProject(Project):
"""Test class needed by `TestProject`."""
pass
class InstantiableProject(Project):
"""... | nilq/baby-python | python |
# coding:utf-8
import threading
import redlock
class Locker(object):
def __init__(self,resource,ttl=0,servers=[{"host": "localhost", "port": 6379, "db": 0}, ]):
self.servers = servers
self.resource = resource
self.ttl = ttl
self.dlm = None
self.r = None
def lock(self... | nilq/baby-python | python |
#!/usr/bin/env python
# Copyright 2020 MaaT Pharma
#
# 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 logging
from io import BytesIO
from datetime import datetime, timezone
from kermes_infra.mail import MailService
from kermes_infra.repositories import FileRepository, UserRepository, EBookRepository
from kermes_infra.queues import SQSConsumer
from kermes_infra.messages import DeliverEBookMessage, CleanUpMessag... | nilq/baby-python | python |
# values_from_literature.py (flowsa)
# !/usr/bin/env python3
# coding=utf-8
"""
Values from the literature used for data allocation are
specified here and can be called on using functions.
"""
import pandas as pd
import numpy as np
from flowsa.common import datapath
def get_US_urban_green_space_and_public_parks_rati... | nilq/baby-python | python |
"""
sentry.plugins.base.v2
~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
__all__ = ('Plugin2',)
import logging
from django.http import HttpResponseRedirect
fro... | nilq/baby-python | python |
# Copyright (C) 2019 Analog Devices, 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 cond... | nilq/baby-python | python |
# Dindo Bot
# Copyright (c) 2018 - 2019 AXeL
from lib.shared import LogType, DebugLevel
from lib import tools, parser
from .job import JobThread
class BotThread(JobThread):
def __init__(self, parent, game_location, start_from_step, repeat_path, account_id, disconnect_after):
JobThread.__init__(self, parent, game_... | nilq/baby-python | python |
class ForeignCountry:
def __init__(self, code):
self.code = code
self.name = "Paese Estero"
| nilq/baby-python | python |
import json
import pytest
from tests.unit.resources import searched_observable
from trustar2.models.searched_observable import SearchedObservable
from trustar2.trustar_enums import ObservableTypes
VALUE = "2.2.2.2"
TYPE = ObservableTypes.IP4.value
FIRST_SEEN = 1623273177255
LAST_SEEN = 1623701072520
ENCLAVE_GUIDS = ... | nilq/baby-python | python |
#!/usr/bin/env python
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot3/blob/master/LICENSE
| nilq/baby-python | python |
import ipywidgets as widgets
a = widgets.IntText(description='Value A')
b = widgets.IntSlider(description='Value B')
vbox = widgets.VBox(children=[a, b])
vbox
| nilq/baby-python | python |
"""
Char. number range | UTF-8 octet sequence
(hexadecimal) | (binary)
--------------------+---------------------------------------------
0000 0000-0000 007F | 0xxxxxxx
0000 0080-0000 07FF | 110xxxxx 10xxxxxx
0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx
0001 0000-0010... | nilq/baby-python | python |
from fastapi import FastAPI, status
from pydantic import BaseModel, ValidationError
from requests_html import HTMLSession
from starlette.middleware.cors import CORSMiddleware
from starlette.responses import JSONResponse
session = HTMLSession()
app = FastAPI(
title="corona virus real time data",
description=""... | nilq/baby-python | python |
#! /usr/bin/env python3
from typing import Dict, List, Tuple
import graphics
import day24
from utils import get_file_lines
class Hexagon(graphics.Polygon):
def __init__(self, x, y, length):
delta_x = (1, 0.5, -0.5, -1, -0.5, 0.5)
delta_y = (0, -0.86602540378443864676372317075294, -0.8660254037... | nilq/baby-python | python |
# TODO
# class MeanAbsoluteError():
# def __init__(self): pass
# TODO
# class MeanBiasError():
# def __init__(self): pass
# TODO
# class ClassificationLosses():
# def __init__(self): pass
# TODO
# class Elbow():
# def __init__(self): pass
# TODO
# class EuclideanDistance():
# def __init__(self)... | nilq/baby-python | python |
## @packege zeus_security_py
# Helper package for data security that will implement zeus microservices
#
#
from Cryptodome.Cipher import AES
from Cryptodome import Random
from hashlib import sha256
import base64
import os
import json
__author__ = "Noé Cruz | contactozurckz@gmail.com"
__copyright__ = "Copyright 2007... | nilq/baby-python | python |
# Copyright 2022 MosaicML Composer authors
# SPDX-License-Identifier: Apache-2.0
"""Helper function to generate the README table."""
import json
import os
from pathlib import Path
import utils
import composer
from composer import functional as CF
EXCLUDE_METHODS = ['no_op_model', 'utils']
HEADER = ['Name', 'Functi... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""IdentityServicesEngineAPI network_access_time_date_conditions API fixtures and tests.
Copyright (c) 2021 Cisco and/or its affiliates.
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... | nilq/baby-python | python |
"""Run calcsfh or hybridMC in Parallel (using subprocess)"""
import argparse
import logging
import os
import subprocess
import sys
from glob import glob1
import numpy as np
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
# Could be in a config or environ
calcsfh = '$HOME/research/match2... | nilq/baby-python | python |
import os
import pickle
import sys
import time
import logging
from watchdog.observers import Observer
from watchdog.events import LoggingEventHandler, FileCreatedEvent, FileDeletedEvent, FileModifiedEvent, FileMovedEvent, \
DirCreatedEvent, DirDeletedEvent, DirModifiedEvent, DirMovedEvent
from watchdog.utils.dirsna... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright © Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
# -----------------------------------------------------------------------------
"""
Te... | nilq/baby-python | python |
from discord.ext.alternatives import silent_delete
from bot import Bot
Bot().run()
| nilq/baby-python | python |
import distutils.command.build
import setuptools.command.egg_info
from setuptools import setup, Extension, find_packages
from Cython.Build import cythonize
import os
def get_build_dir(default):
return os.environ.get('STFPY_BUILD_DIR', default)
# Override egg command
class EggCommand(setuptools.command.egg_info.eg... | nilq/baby-python | python |
from geolocalizador import *
endereco = u'Universidade de Sao Paulo, Instituto de Matematica e Estatastica, Departamento de Ciencia da Computacao. Rua do Matao 1010 Cidade Universitaria 05508090 - Sao Paulo, SP - Brasil Telefone: (11) 30916135 Ramal: 6235 Fax: (11) 30916134 URL da Homepage: http://www.ime.usp.br/~cesa... | nilq/baby-python | python |
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import sys
from telemetry import test
from measurements import image_decoding
class ImageDecodingToughImageCases(test.Test):
test = image_decoding.... | nilq/baby-python | python |
from .hook_group import HookGroup
class Event(HookGroup):
def __init__(self, event=None, hooks=None, config=None):
self.type = event
super().__init__(hooks=hooks, config=config)
| nilq/baby-python | python |
# -------------------------------------------------
# Data Types for Data Science in Python - Handling Dates and Times
# 24 set 2020
# VNTBJR
# ------------------------------------------------
#
# Load packages
reticulate::repl_python()
# Load data
import csv
csvfile2 = open("Datasets/cta_summary.csv", mode = 'r')
da... | nilq/baby-python | python |
import requests
import folium
import geocoder
import string
import os
import json
from functools import wraps, update_wrapper
from datetime import datetime
from pathlib import Path
from flask_bootstrap import Bootstrap
from flask_nav import Nav
from flask_nav.elements import *
from dominate.tags import img
from edibl... | nilq/baby-python | python |
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver
from asset_events.models import StatusChangingEvent
@receiver(post_save)
def update_asset_status(sender, instance, **kwargs):
if not issubclass(sender, StatusChangingEvent):
return
sender.post_save(instance... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2018-06-05 08:38
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('yaksh', '0015_auto_20180601_1215'),
]
operations = [
migrations.AlterField(
... | nilq/baby-python | python |
# Generated by Django 3.0.5 on 2020-12-11 07:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('content_api', '0002_auto_20201002_1228'),
]
operations = [
migrations.AlterModelOptions(
name='... | nilq/baby-python | python |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed u... | nilq/baby-python | python |
# Copyright (C) 2013 Claudio "nex" Guarnieri (@botherder)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This pro... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from calendar import timegm
from collections import defaultdict
from datetime import datetime
from importlib import import_module
from os import path as op
import re
from pkg_resources import DistributionNotFound, iter_entry_points, load_entry_point
from pygments import highlight
from pygments... | nilq/baby-python | python |
import asyncio
from xwing.socket.server import Server
BACKEND_ADDRESS = '/var/tmp/xwing.socket'
async def start_server(loop):
server = Server(loop, BACKEND_ADDRESS, 'server0')
await server.listen()
conn = await server.accept()
while True:
data = await conn.recv()
if not data:
... | nilq/baby-python | python |
import sys
import json
if len(sys.argv) < 2:
print('uso: python tag_input.py <arquivo>')
exit(-1)
arquivo_entrada = open(sys.argv[1], 'r', encoding='utf8')
fluxo = json.load(arquivo_entrada)
arquivo_entrada.close()
for bloco in fluxo:
for action_moment in ['$enteringCustomActions', '$leavingCustomAction... | nilq/baby-python | python |
# coding=utf-8
from setuptools import setup, find_packages
setup(
name="wsgi-listenme",
description="WSGI middleware for capture and browse requests and responses",
version='1.0',
author='Mario César Señoranis Ayala',
author_email='mariocesar.c50@gmail.com',
url='https://github.com/humanzilla... | nilq/baby-python | python |
name=("Rayne","Coder","Progammer","Enginner","VScode")
(man,*item,software)=name
print(man)
#*item container for all value that not contain by man and software
print(item)
print(software)
| nilq/baby-python | python |
import unittest
from unittest import mock
from .. import surface
class TestEllipsoidDem(unittest.TestCase):
def test_height(self):
test_dem = surface.EllipsoidDem(3396190, 3376200)
self.assertEqual(test_dem.get_height(0, 0), 0)
self.assertEqual(test_dem.get_height(0, 180), 0)
sel... | nilq/baby-python | python |
# ==正規表現によるスクレイピング==
import re
from html import unescape
# プロジェクト配下にダウンロードしたhtmlファイルを開き、レスポンスボディを変数に格納。
with open('../sample.scraping-book.com/dp.html') as f:
html = f.read()
# findallを使って書籍一冊分のhtml情報を取得する
# re.DOTALL => 改行も含むすべての文字にマッチ
for partial_html in re.findall(r'<a itemprop="url".*?</ul>\s*</a></li>', htm... | nilq/baby-python | python |
"""
735. Asteroid Collision
Medium
We are given an array asteroids of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed.
Find out the state ... | nilq/baby-python | python |
import torch
import time
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self, name, fmt=':f'):
self.name = name
self.fmt = fmt
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
sel... | nilq/baby-python | python |
from time import time
from json import dumps, loads
from redis import StrictRedis, ConnectionPool, WatchError
from PyYADL.distributed_lock import AbstractDistributedLock
class RedisLock(AbstractDistributedLock):
def __init__(self, name, prefix=None, ttl=-1, existing_connection_pool=None, redis_host='localhost', ... | nilq/baby-python | python |
from .elbo import ELBO
__all__ = [
'ELBO'
]
| nilq/baby-python | python |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2010 OpenStack Foundation
# 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.apach... | nilq/baby-python | python |
from baseline.train import create_trainer, register_trainer, register_training_func, Trainer
from baseline.embeddings import register_embeddings
from baseline.reporting import register_reporting, ReportingHook
from baseline.tf.embeddings import TensorFlowEmbeddings
from baseline.tf.optz import optimizer
from baseline.c... | nilq/baby-python | python |
"""Super class of contextual bandit algorithm agent class"""
import numpy as np
class ContextualBanditAlgorithm(object):
"""
Args:
n_features : 特徴量の次元数
Attributes:
iter_num(int) : 現在の反復回数
"""
def __init__(self, n_features:int):
self.n_features = n_features
self.ite... | nilq/baby-python | python |
# Generated by Django 2.1.8 on 2019-08-08 23:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('wagtailnhsukfrontendsettings', '0003_footersettings'),
]
operations = [
migrations.AddField(
model_name='footersettings',
... | nilq/baby-python | python |
# --------------
# Import packages
import numpy as np
import pandas as pd
from scipy.stats import mode
# code starts here
bank = pd.read_csv(path)
categorical_var = bank.select_dtypes(include = 'object')
print(categorical_var)
numerical_var = bank.select_dtypes(include = 'number')
print(numerical_var)
# code e... | nilq/baby-python | python |
# Copyright © 2018 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2-Clause OR GPL-3.0-only
# !/usr/bin/python
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = '''
---
module: vcd_vapp_netcommit
short_description: Ansibl... | nilq/baby-python | python |
# Copyright 2018 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | nilq/baby-python | python |
import asyncio
import unittest
from unittest.mock import ANY
from aiobeanstalk.proto import Client
from aiobeanstalk.packets import Using, Inserted
def btalk_test(fun):
fun = asyncio.coroutine(fun)
def wrapper(self):
@asyncio.coroutine
def full_test():
cli = yield from Client.c... | nilq/baby-python | python |
import os.path
charmap = []
charmapDescription = []
if os.path.isfile('charmap.mif'):
charmapFile = open('charmap.mif', 'r+')
lines = charmapFile.readlines()
cont = 0
character = []
for line in lines:
if line[0] == " ":
newLine = line[-10:-2]
if cont % 8 == 0 and cont... | nilq/baby-python | python |
'''
Copyright 2017, Fujitsu Network Communications, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in w... | nilq/baby-python | python |
from flask import Blueprint, request, jsonify
from werkzeug import check_password_hash
from flask.ext.login import login_user, logout_user
from app.core import db
from app.api_decorators import requires_login, requires_keys
from app.models.user import User
blueprint = Blueprint('api_slash', __name__, url_prefix='/api'... | nilq/baby-python | python |
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... | nilq/baby-python | python |
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class FaceSearchUserInfo(object):
def __init__(self):
self._customuserid = None
self._merchantid = None
self._merchantuid = None
self._score = None
@p... | nilq/baby-python | python |
import torch
import torch.nn as nn
class SLAF(nn.Module):
def __init__(self, k=2):
super().__init__()
self.k = k
self.coeff = nn.ParameterList(
[nn.Parameter(torch.tensor(1.0)) for i in range(k)])
def forward(self, x):
out = sum([self.coeff[k] * torch.pow(x, k) for... | nilq/baby-python | python |
#from keras.models import Sequential, Model
#from keras.layers import Dense, Dropout, Flatten, Input
#from keras.layers import Conv2D, MaxPooling2D, Reshape, Concatenate
from keras.optimizers import Adam
#import tensorflow as tf
import numpy as np
import sys
import os
import cv2
import keras.backend as K
imp... | nilq/baby-python | python |
import torch
import torchvision
def get_loader(root='.', batch_size=512):
transform = torchvision.transforms.Compose([
torchvision.transforms.ToTensor(),
torchvision.transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5)),
])
train_dataset = torchvision.datasets.CIFAR10(root, train=True,
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from guillotina.factory import serialize # noqa
from guillotina.factory.app import make_app # noqa
from guillotina.factory.content import ApplicationRoot # noqa
from guillotina.factory.content import Database # noqa
from guillotina.factory import security # noqa
| nilq/baby-python | python |
import typing
from kubernetes import client
from kubernetes import config
from kubernetes.client.rest import ApiException
from kuber import definitions
from kuber import versioning
def load_access_config(in_cluster: bool = False, **kwargs):
"""
Initializes the kubernetes library from either a kube configura... | nilq/baby-python | python |
# coding: utf-8
from abc import ABCMeta
from config.config_loader import logger
from mall_spider.spiders.actions.action import Action
from mall_spider.spiders.actions.context import Context
class DefaultAction(Action):
__metaclass__ = ABCMeta
def on_error(self, context, exp):
task = context.get(Cont... | nilq/baby-python | python |
import pygame
from Player import PlayerBase
class Player2():
def __init__(self, image, speed = [0,0], pos = [0,0]):
self.image = pygame.image.load(image)
| nilq/baby-python | python |
import theano.tensor as T
class Regularizer(object):
def __call__(self, **kwargs):
raise NotImplementedError
class L2Regularizer(Regularizer):
def __call__(self, alpha, params):
return alpha * l2_sqr(params) / 2.
def l2_sqr(params):
sqr = 0.0
for p in params:
sqr += T.sum((... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# pylint: disable=missing-docstring
from __future__ import absolute_import, unicode_literals
# 3rd party imports
import pytest
from six import string_types
# project imports
from restible.url_params import from_string
@pytest.mark.parametrize('value,expected_type', (
('123', int),
('... | nilq/baby-python | python |
from frangiclave.bot.templates.base import make_section, DIVIDER, URL_FORMAT
from frangiclave.compendium.deck import Deck
def make_deck(deck: Deck):
draw_messages = '\n'.join(f'• <https://www.frangiclave.net/element/{dm.element.element_id}/|{dm.element.element_id}>: {dm.message}' for dm in deck.draw_messages)
... | nilq/baby-python | python |
import collections
import logging
import re
import socket
import subprocess
def json_update(d, u):
for k, v in u.items():
if isinstance(v, collections.abc.Mapping):
d[k] = json_update(d.get(k, {}), v)
else:
d[k] = v
return d
def remove_dict_null(d: dict):
"""Remov... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import re
import scrapy
from locations.items import GeojsonPointItem
class GuzmanyGomezSpider(scrapy.Spider):
name = "guzmany_gomez"
item_attributes = {"brand": "Guzman Y Gomez"}
allowed_domains = ["guzmanygomez.com.au"]
start_urls = [
"https://www.guzmanygomez.com.au... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.