content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
# Copyright (c) 2019 leosocy. All rights reserved.
# Use of this source code is governed by a MIT-style license
# that can be found in the LICENSE file.
import io
import os
from setuptools import setup
import edcc
# Package meta-data.
NAME = "edcc"
DESCRIPTION = "EDCC: An efficient and accurate algorithm for palmpr... | nilq/baby-python | python |
from toolkit.modules.make_follow_sets import follow_sets
from toolkit.modules.make_first_sets import first_sets
from toolkit.modules.grammar import is_terminal
from tabulate import tabulate
def parsing_table(pgrammar, fs, fls, error_recovery=True):
"""
Input:
pgrammar: parsed grammar
fs: first... | nilq/baby-python | python |
class MemcacheError(Exception):
pass
class MemcacheServerError(Exception):
def __init__(self, server: str, message: str) -> None:
self.server = server
super().__init__(message)
| nilq/baby-python | python |
watchdog_config = """
# SDSLabs Watchdog configuration START
UsePAM yes
PasswordAuthentication no
AuthorizedKeysCommand /opt/watchdog/bin/watchdog auth -u %u -t %t -p %k
AuthorizedKeysCommandUser root
# SDSLabs Watchdog configuration END
"""
modified_options = [
'AuthorizedKeysCommand',
'AuthorizedKeysCommandUser... | nilq/baby-python | python |
#!/usr/bin/env python
#author mark_purcell@ie.ibm.com
#NOTE: FOR GOFLEX OPERATIONS DONT CHANGE THE CONTENTS OF THIS FILE
#REQUEST BUG FIXES OR ENHANCEMENTS AS NECESSARY
class GoFlexMessageFormatter():
def __init__(self):
pass
def request_meter_data(self, meter, from_date, to_date):
return {... | nilq/baby-python | python |
from .gradient_penalty import *
from .wasserstain_div import *
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
import sys
from formalchemy import templates
__doc__ = """
There is two configuration settings available in a global config object.
- encoding: the global encoding used by FormAlchemy to deal with unicode. Default: utf-8
- engine: A valide :class:`~formalchemy.templates.TemplateEngine`
- dat... | nilq/baby-python | python |
'''
Copyright (c) 2021-2022 OVGU LIA
Author: Harish Kumar Pakala
This source code is licensed under the Apache License 2.0 (see LICENSE.txt).
This source code may use other Open Source software components (see LICENSE.txt).
'''
try:
import queue as Queue
except ImportError:
import Queue as Queue
class DataMan... | nilq/baby-python | python |
# Последовательность треугольных чисел образуется путем сложения натуральных чисел. К примеру, 7-ое треугольное число
# равно 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. Первые десять треугольных чисел:
#
# 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
#
# Перечислим делители первых семи треугольных чисел:
#
# 1: 1
# 3: 1, 3
# 6: 1,... | nilq/baby-python | python |
from django.conf import settings
if settings.WITH_WQDB:
from wq.db import rest
from wq.db.patterns import serializers as patterns
from .models import Note
rest.router.register_model(
Note,
serializer=patterns.NaturalKeyModelSerializer,
fields="__all__",
)
| nilq/baby-python | python |
# Introduction to Python
# Structure of if statements
"""
if condition:
Statements
elif condition:
Statements
else:
Statements
"""
#Grade of a student
marks = 90
# No braces in Python, Indectation does the job
if marks > 90:
print("Grade O")
elif marks > 80:
print("Grade E")
elif marks > 70:
... | nilq/baby-python | python |
class DeprecatedEnv(ImportError):
pass
| nilq/baby-python | python |
#!/usr/bin/env python
# coding: utf-8
# ## Case Challenge Part I (Individual Assignment 1)
# After three years serving customers across the San Francisco Bay Area, the executives at
# Apprentice Chef have decided to take on an analytics project to better understand how much
# revenue to expect from each customer withi... | nilq/baby-python | python |
from flocx_ui.api import schema
from flocx_ui.api.utils import generic_provider_request as generic_request
from flocx_ui.api.utils import validate_data_with
def post(path, **kwargs):
"""An alias for generic_request with the type set to 'POST'
:param path: A url path
:param **kwargs: The keyword arguments ... | nilq/baby-python | python |
import bluesky.plan_stubs as bps
import bluesky.plans as bp
import bluesky.preprocessors as bpp
import numpy as np
import pytest
from ophyd.sim import SynAxis, hw
import nabs.plans as nbp
from nabs.simulators import validate_plan
hw = hw()
class LimitedMotor(SynAxis):
def check_value(self, value, **kwargs):
... | nilq/baby-python | python |
def test_list_devices(client):
devices = client.devices()
assert len(devices) > 0
assert any(map(lambda device: device.serial == "emulator-5554", devices))
def test_version(client):
version = client.version()
assert type(version) == int
assert version != 0
| nilq/baby-python | python |
import numpy as np
from gutfit import model, parameterlist
def matrix_diag3(d1,d2,d3):
return np.array([[d1, 0.0, 0.0], [0.0, d2, 0.0], [0.0, 0.0, d3]])
# Generic Rotations #
def matrix_rot23(th23):
return np.array([[1.0, 0.0 , 0.0],
[0.0, np.cos(th23), np.sin(th23)],
... | nilq/baby-python | python |
import argparse
import json
import logging
import random
import numpy as np
import torch
from decouple import config
from tqdm import tqdm
from GPT2.config import GPT2Config
from GPT2.encoder import get_encoder
from GPT2.model import GPT2LMHeadModel
from GPT2.utils import load_weight
# import os
# import torch.nn.... | nilq/baby-python | python |
#
# PySNMP MIB module SUN-T300-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SUN-T300-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:04:28 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... | nilq/baby-python | python |
# ******************************************************************************
# Copyright 2017-2018 Intel Corporation
#
# 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.apa... | nilq/baby-python | python |
def foo():
print "hello every body" | nilq/baby-python | python |
from relevanceai.base import _Base
from relevanceai.api.endpoints.centroids import CentroidsClient
class ClusterClient(_Base):
def __init__(self, project, api_key):
self.project = project
self.api_key = api_key
self.centroids = CentroidsClient(project=project, api_key=api_key)
supe... | nilq/baby-python | python |
import requests
import urllib
from bs4 import BeautifulSoup
from os import path, makedirs
import wget
class Crawler:
"""
Class for crawl by page ulr-like 'http(s)://page_path/page_name_{number}/ and download pictures
"""
def __init__(self, url_pattern, page_number, css_alt=None):
self.url_patt... | nilq/baby-python | python |
# Copyright 2017-2019 EPAM Systems, Inc. (https://www.epam.com/)
#
# 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 |
#!/usr/bin/env python3
# Povolene knihovny: copy, math
# Import jakekoli jine knihovny neprojde vyhodnocovaci sluzbou.
# To, ze jsou nejake knihovny povolene, neznamena, ze je nutne je pouzit.
# IB002 Domaci uloha 9.
#
# V teto uloze se budeme zabyvat binarnimi vyhledavacimi stromy.
#
# V prvni casti bude Vasi uloho... | nilq/baby-python | python |
class Item:
def __init__(self, name, tag, desc, intro):
self.name = name
self.tag = tag
self.desc = desc
self.intro = intro
def __str__(self):
return f"=> {self.name} - {self.desc}"
def getItem(self, player):
player.inventory.append(self)
def getIntro(self):
return self.intro
# so t... | nilq/baby-python | python |
# pylint: skip-file
| nilq/baby-python | python |
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | nilq/baby-python | python |
import logging
def get_logger(log_filename=None, module_name=__name__, level=logging.INFO):
# select handler
if log_filename is None:
handler = logging.StreamHandler()
elif type(log_filename) is str:
handler = logging.FileHandler(log_filename, 'w')
else:
raise ValueError("log_f... | nilq/baby-python | python |
from view import View
from tkinter import Tk
class Controller:
def __init__(self, model):
self.model = model
self.view = View(self.model.graph.width(),
self.model.graph.height(),
self.model.graph_path)
def run(self):
self.view.draw_mode... | nilq/baby-python | python |
#! /usr/bin/env python
# -*- Mode: Python -*-
# -*- coding: ascii -*-
"""
Dump layer name list
layer containing the mesh
"""
import lwsdk
__lwver__ = "11"
class HistoryData():
def __init__(self):
self.string = ''
self.select_contains = False
self.select_others = False
class DumpLayerN... | nilq/baby-python | python |
# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
import os
import unittest
from unittest.mock import Mock, call, patch
from ci_workflow.ci_check_manifest_component import CiCh... | nilq/baby-python | python |
from plugins.adversary.app.operation.operation import Step, OPVar, OPHost, OPRat, OPSoftware
from plugins.adversary.app.commands import *
from plugins.adversary.app.custom import *
class WebServerInstall(Step):
""" Description:
This step prepares the installation of a PHP webserver.
Requi... | nilq/baby-python | python |
from django.apps import AppConfig
from django.db.models.signals import post_save, post_delete
from django.conf import settings
class SyncConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'sync'
def ready(self):
try:
from .signals import init_signals
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Launch small HTTP server for TimeoutTest test case
Should work with Python 2 and 3.
"""
import sys
import time
try:
from SimpleHTTPServer import SimpleHTTPRequestHandler as RequestHandler
except ImportError:
from http.server import CGIHTTPRequestHandler as RequestHandler
try:
... | nilq/baby-python | python |
"""
PPO with tensorflow implementation
The goal of RL is to find an optimal behavior strategy for the agent to obtain
optimal rewards. The policy gradient methods target at modeling and optimizing
the policy directly. The policy loss is defined as
L = E [log pi (a|s)] * AF
where, 'L' is the policy loss, 'E' is the... | nilq/baby-python | python |
#!/usr/bin/python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "Licen... | nilq/baby-python | python |
import math as m
import numpy as np
from matplotlib import pyplot as plt
from BDPoisson1D import dirichlet_non_linear_poisson_solver_amr
from BDFunction1D import Function
from BDFunction1D.Functional import Functional
class TestFunction(Function):
"""
Some known differentiable function
"""
def evalu... | nilq/baby-python | python |
#!/usr/bin/env python
import glob
for name in glob.glob('dir/*'):
print name
| nilq/baby-python | python |
"""
Image conversion functions.
"""
# Copyright (c) 2020 Ben Zimmer. All rights reserved.
from typing import Tuple
import numpy as np
from PIL import Image
# Some functions for colorizing single channel black and white image (PIL "L" mode)
# or the alpha channels of text_scala output.
# ~~~~ function from text_... | nilq/baby-python | python |
import pandas as pd
def generate_train(playlists):
# define category range
cates = {'cat1': (10, 50), 'cat2': (10, 78), 'cat3': (10, 100), 'cat4': (40, 100), 'cat5': (40, 100),
'cat6': (40, 100),'cat7': (101, 250), 'cat8': (101, 250), 'cat9': (150, 250), 'cat10': (150, 250)}
cat_pids = {}
... | nilq/baby-python | python |
'''
Copyright (C) 2018 PyElo.
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, distribute, sublice... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
import unittest
from gilded_rose import Item, GildedRose
class GildedRoseTest(unittest.TestCase):
def test_foo_quality_never_below_zero(self):
items = [Item("foo", 0, 0)]
gilded_rose = GildedRose(items)
gilded_rose.update_quality()
self.assertEqual("foo", it... | nilq/baby-python | python |
#!/usr/bin/env python
import gpt_2_simple as gpt2
import sys
if len(sys.argv) > 1:
prompt = sys.argv[1]
else:
prompt = "prompt: So, what's new around here?"
print(prompt)
sys.exit(1)
sess = gpt2.start_tf_sess()
gpt2.load_gpt2(sess)
single_text = gpt2.generate(
sess,
return_as_list=True,
... | nilq/baby-python | python |
# Please refrain from specifying a micro version if possible.
# --------------------------------------------------------------------------- #
VERSION = (1, 1)
# --------------------------------------------------------------------------- #
def _get_version(vt): ... | nilq/baby-python | python |
# GUI Application automation and testing library
# Copyright (C) 2006-2018 Mark Mc Mahon and Contributors
# https://github.com/pywinauto/pywinauto/graphs/contributors
# http://pywinauto.readthedocs.io/en/latest/credits.html
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# ... | nilq/baby-python | python |
# Make sure to have CoppeliaSim running, with followig scene loaded:
#
# scenes/messaging/ikMovementViaRemoteApi.ttt
#
# Do not launch simulation, then run this script
from zmqRemoteApi import RemoteAPIClient
print('Program started')
client = RemoteAPIClient()
sim = client.getObject('sim')
tipHandle = sim.getObject... | nilq/baby-python | python |
import attr
from .document import Document
from .has_settings import HasSettings
from .templated import Templated
import exam_gen.util.logging as logging
log = logging.new(__name__, level="DEBUG")
@attr.s
class GradeData():
points = attr.ib(default=None)
children = attr.ib(factory=dict)
comment = attr.... | nilq/baby-python | python |
import sys
def op(arg1, arg2):
if (len(sys.argv) != 3):
raise Exception("InputError: only numbers\n\n")
if (arg1.isdigit() and arg2.isdigit()):
arg1 = int(arg1)
arg2 = int(arg2)
else:
raise Exception("InputError: only numbers\n\n")
print("Sum: ", arg1 + arg2)
print("Difference: ", arg1 - arg2)
print("Pr... | nilq/baby-python | python |
def xprop(layout, data, prop, enabled=True, **kwargs):
attrs = getattr(data.bl_rna, prop)[1]
name = attrs.get('name', prop)
lay = layout.row().split(percentage=0.33)
lay.label(name + ':')
lay = lay.row(align=True)
lay_l = lay.row(align=True)
lay_r = lay
if not enabled:
lay = lay.... | nilq/baby-python | python |
#!/usr/bin/env python
from distutils.core import setup
setup(name='pyledsign',
version='1.01',
description='pyledsign - control led signs from python',
author='Kerry Schwab',
author_email='sales@brightsigns.com',
url='http://www.python.org/tbd/',
packages=['pyledsign'],
)
| nilq/baby-python | python |
from django.conf import settings
from django.http import Http404
from django.shortcuts import redirect, render
from .models import Link
def redirect_(request, key):
try:
link = Link.find_by_key(key.lower())
except Link.DoesNotExist:
raise Http404("Link does not exist.")
return redirect(... | nilq/baby-python | python |
# Generated by Django 2.1 on 2018-08-08 04:35
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
]
operations = [
migrations.CreateModel(... | nilq/baby-python | python |
"""Tests the DNC class implementation."""
import sonnet as snt
import tensorflow as tf
import unittest
from numpy.testing import assert_array_equal
from .. dnc import dnc
def suite():
"""Create testing suite for all tests in this module."""
suite = unittest.TestSuite()
suite.addTest(DNCTest('test_const... | nilq/baby-python | python |
# Source : https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree/
# Author : henrytine
# Date : 2020-08-19
#####################################################################################################
#
# Given a binary tree, find the lowest common ancestor (LCA) of two given nodes in the tr... | nilq/baby-python | python |
import pymysql
import urllib.request
from bs4 import BeautifulSoup
import requests
def connectDatabase():
"""Create database connection"""
global db
db = pymysql.connect(host='localhost', user='root', password='',
db='vg_dapi', cursorclass=pymysql.cursors.DictCursor,charset='utf8')... | nilq/baby-python | python |
from mycroft import MycroftSkill, intent_file_handler
class RoomBooking(MycroftSkill):
def __init__(self):
MycroftSkill.__init__(self)
@intent_file_handler('booking.room.intent')
def handle_booking_room(self, message):
amount = message.data.get('amount')
building = message.data.ge... | nilq/baby-python | python |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class DialogEvent:
def __init__(self, bubble: bool = False, name: str = "", value: object = None):
self.bubble = bubble
self.name = name
self.value: object = value
| nilq/baby-python | python |
import traceback
from twisted.internet import reactor
def stack():
print("The Python Stack.")
traceback.print_stack()
reactor.callWhenRunning(stack)
reactor.run()
| nilq/baby-python | python |
import os
import sys
import codecs
import difflib
sys.path.insert(0, os.path.dirname(__file__))
from logger import log
def restore_file_case(text_file, orig_file, debug=False):
text_io = codecs.open(text_file, 'r', encoding='utf8')
orig_io = codecs.open(orig_file, 'r', encoding='utf8')
for line in text... | nilq/baby-python | python |
"""Test for our weighted graph."""
# {'A': {'B': 7, 'C': 9}, 'B': {'D': 2, 'E': 4}, 'C': {'F':6}}
"""Test our graph implementation."""
import pytest
from weighted_graph import Weighted
@pytest.fixture
def new_weighted_graph():
"""Graph for testing."""
from weighted_graph import Weighted
empty_graph = Weig... | nilq/baby-python | python |
import os.path
from unittest import TestCase
from pkg_resources import require, DistributionNotFound
from subprocess import call
from sys import platform, executable, exit
from src.info import AppInfo
try:
REQUIRED = open(os.path.join(AppInfo.root_dir, "requirements.txt")).read()
except Exception as e:
raise E... | nilq/baby-python | python |
# Copyright The PyTorch Lightning team.
#
# 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 i... | nilq/baby-python | python |
#!/usr/bin/env python
import discord
import configparser
from libs import raid_combat
# Setup the config and Discord client
config = configparser.RawConfigParser()
config.read('config.conf')
client = discord.Client()
# create the dict of combat managers for each server
combat_managers = {}
@client.event
async def ... | nilq/baby-python | python |
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
apikey = 'mykey'
secretkey = 'mysecret'
Driver = get_driver(Provider.AURORACOMPUTE)
conn = Driver(key=apikey, secret=secretkey)
| nilq/baby-python | python |
# Copyright 2019 Atalaya Tech, 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 writing, ... | nilq/baby-python | python |
# app/chats/forms.py
| nilq/baby-python | python |
from django.views.generic import UpdateView, ListView
import pyperclip
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.http.response import Http404
from django.shortcuts import render
from .models import Image, Categories, Location
# modal window settings
class Moda... | nilq/baby-python | python |
from os import environ
def assert_in(file, files_to_check):
if file not in files_to_check:
raise AssertionError("{} does not exist in the list".format(str(file)))
return True
def assert_in_env(check_list: list):
for item in check_list:
assert_in(item, environ.keys())
return True
| nilq/baby-python | python |
from django.contrib import messages
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
from misago.admin.views import generic
from misago.users.forms.admin import RankForm
from misago.users.models import Rank
class RankAdmin(generic.AdminBase... | nilq/baby-python | python |
# Copyright (c) 2021 - present / Neuralmagic, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... | nilq/baby-python | python |
#!/usr/bin/python
"""
This work targets for emulating fog computing infrastructure and fog service and network evaluation.
Original author Tzu-Chiao Yeh (@tz70s), 2017@National Taiwan University, Dependable Distributed System and Network Lab.
Checkout the License for using, modifying and publishing.
"""
import docker... | nilq/baby-python | python |
# Generated by Django 3.2.4 on 2021-09-09 13:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("accounts", "0005_add_field_last_modified_20210621_1058"),
]
operations = [
migrations.AddField(
model_name="govdepartment",
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Shared utility functions for interacting with the data model."""
import logging
logger = logging.getLogger(__name__)
import os
from binascii import hexlify
def generate_random_digest(num_bytes=28, urandom=None, to_hex=None):
"""Generates a random hash and returns the hex digest as a u... | nilq/baby-python | python |
#CGI(Common Gateway Interface),通用网关接口,它是一段程序,运行在服务器上如:HTTP服务器,提供同客户端HTML页面的接口
'''
开启apache: sudo apachectl start
重启apache: sudo apachectl restart
关闭apache: sudo apachectl stop
'''
#http://localhost/cgi-bin/hello.py
#/private/etc/apache2/httpd.conf apache服务器的配置路径
#/资源库/WebServer/Documents apache服务器访问路径
#/资... | nilq/baby-python | python |
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
idx = len(nums1) - 1
hi1, hi2 = m -... | nilq/baby-python | python |
"""Manages plotting, provides a single interface
for different plots with different backends."""
from __future__ import print_function, absolute_import
import os
import sys
import importlib
import traceback
import numpy
from matplotlib.colors import LinearSegmentedColormap
from vcs.colors import matplotlib2vcs
import ... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
@author: Aditya Intwala
Copyright (C) 2016, Aditya Intwala.
Licensed under the Apache License 2.0. See LICENSE file in the project root for full license information.
"""
import cv2
from Core.Math.Point2 import Point2
class Eraser():
@staticmethod
def ErasePixel(img, pixel):
... | nilq/baby-python | python |
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Licen... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-10-25 15:27
from __future__ import unicode_literals
import calaccess_raw.annotations
import calaccess_raw.fields
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('calaccess_raw', '0007_auto_20160831_0132'... | nilq/baby-python | python |
import numpy as np
import matplotlib.pyplot as plt
import struct
import os, sys
import re
import copy
class Matrix:
"""
Class to Read and Hangle Matrix files
"""
def __init__(self,Path): # Give the Path of the folder containing all the mtrx files
# Read PATH and open file
self.Path = Pa... | nilq/baby-python | python |
import os
import sys
import logging
import json
import typing
import collections
from ConfigSpace.configuration_space import ConfigurationSpace, Configuration
from ConfigSpace.hyperparameters import FloatHyperparameter, IntegerHyperparameter
__author__ = "Marius Lindauer"
__copyright__ = "Copyright 2016, ML4AAD"
__li... | nilq/baby-python | python |
#!/usr/bin/env python3
# This is run by the "run-tests" script.
import unittest
import signal
import socket
class TestTimeout(unittest.TestCase):
def test_timeout(self):
port = 12346
s = socket.socket()
s.connect(("0.0.0.0", port))
# Assumes the server has --timeout 1
signal... | nilq/baby-python | python |
import numpy as np
matrizquadrada = int(input("Definir o tamanho Matriz: "))
Geracoes = int(input("Definir quantas geracoes: "))
# Considerando 1 como celula viva e 0 como celula morta.
# Rodar o jogo no terminal
# A cada geração irá aplicar as condições do jogo, criando assim uma nova matriz atualizada.
def atual... | nilq/baby-python | python |
import itertools
def reduce_undefined(obj):
if isinstance(obj, dict):
r = {}
for k, v in obj.items():
if v == UNDEFINED:
pass
else:
r[k] = reduce_undefined(v)
return r
elif isinstance(obj, (tuple, list)):
r = []
for ... | nilq/baby-python | python |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import abc
import time
import datetime
import importlib
from pathlib import Path
from typing import Type, Iterable
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import pandas as pd
from tqdm import tqdm
from loguru impo... | nilq/baby-python | python |
#!/usr/bin/env python
## This file comes from Jennifer Fourquier's excellent ghost-tree project
## Some modifications by Lela Andrews to fit within akutils framework
##
## Ghost-tree is provided under BSD license
##
## Copyright (c) 2015--, ghost-tree development team.
## All rights reserved.
##
"""
This file can be do... | nilq/baby-python | python |
from distutils import log
from setuptools import setup
try:
from setuptools.command import egg_info
egg_info.write_toplevel_names
except (ImportError, AttributeError):
pass
else:
def _top_level_package(name):
return name.split('.', 1)[0]
def _hacked_write_toplevel_names(cmd, basename, file... | nilq/baby-python | python |
import sys
from collections import OrderedDict
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as functional
from ptsemseg.models._util import try_index
from modules import IdentityResidualBlock, ABN, GlobalAvgPool2d
from modules.bn import ABN, InPlaceABN, InPlaceABNSync
... | nilq/baby-python | python |
import logging
from flask import Flask
from flask.logging import default_handler
from flask_logging_decorator import trace
app = Flask(__name__)
app.logger.setLevel(logging.WARN)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
default_handler.setFormatter(formatter)
@app.rout... | nilq/baby-python | python |
import logging
import os
import torch
from transformers import BertTokenizer
from .data_cls import BertDataBunch
from .learner_cls import BertLearner
from .modeling import (
BertForMultiLabelSequenceClassification,
XLNetForMultiLabelSequenceClassification,
RobertaForMultiLabelSequenceClassification,
Dis... | nilq/baby-python | python |
"""
handles logging for:
- auth
- contact
- msg
- label
- report
- att
modules
"""
import csv
from datetime import datetime
import os
import shutil
from config import config
log_dir = config.data["log"]["log_dir"]
logfiles = config.data["log"]["logfiles"]
def get_logpath(logtype):
filen... | nilq/baby-python | python |
import io
import json
import unittest
from datetime import datetime
from unittest.mock import Mock
import boto3
from botocore.response import StreamingBody
from botocore.stub import Stubber, ANY
from redis import StrictRedis
from s3_log_shipper.parsers import ParserManager, Parser
from s3_log_shipper.shipper import R... | nilq/baby-python | python |
from pyramid.config import Configurator
from pyramid.static import static_view
import kinto.core
def includeme(config):
config.scan("kinto.tests.core.testapp.views")
# Add an example route with trailing slash (here to serve static files).
# This is only used to test 404 redirection in ``test_views_errors... | nilq/baby-python | python |
class BaseFilter:
"""
This is the reference implementation for all filters/hooks.
Just passes the data as-is without changing it.
"""
def register(self, kernel, shell):
self.kernel = kernel
self.shell = shell
shell.events.register('post_run_cell', self.post_run_cell)
... | nilq/baby-python | python |
"""
常见的颜色名称
"""
color_dict={
"almond":(239,222,205),
"amaranth":(229,43,80),
"amazon":(59,122,87),
"amber":(255,191,0),
"sae":(255,126,0),
"amethyst":(153,102,204),
"ao":(0,128,0),
"apricot":(251,206,177),
"aqua":(0,255,255),
"aquamarine":(127,255,212),
"arsenic":(59,68,75),
"artichoke":(143,151,121),
"asparagus":(135,... | nilq/baby-python | python |
import argparse, operator
from collections import defaultdict
from gpToDict import gpToDict, makeEntities
from utility import readFromFile
def run(target):
fileType = target.split('.')[-1]
if fileType == 'data':
entities = makeEntities(gpToDict(target)[0])
elif fileType == 'json':
entities ... | nilq/baby-python | python |
from modules.discriminator import MultiScaleDiscriminator, RandomWindowDiscriminator
from modules.generator import Aligner, Decoder, Encoder
from modules.mel import MelSpectrogram
| nilq/baby-python | python |
from django_roa.remoteauth.models import User
from django.contrib.auth.backends import ModelBackend
class RemoteUserModelBackend(ModelBackend):
"""
Authenticates against django_roa.remoteauth.models.RemoteUser.
"""
def authenticate(self, username=None, password=None, **kwargs):
try:
... | nilq/baby-python | python |
"""
Mountain Car environment adapted from OpenAI gym [1].
* default reward is 0 (instead of -1)
* reward in goal state is 1 (instead of 0)
* also implemented as a generative model (in addition to an online model)
* render function follows the rlberry rendering interface.
[1] https://github.com/openai/gym/blob/m... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.