content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import hassapi as hass
#
# App to turn lights on and off at sunrise and sunset
#
# Args:
#
# on_scene: scene to activate at sunset
# off_scene: scene to activate at sunrise
class OutsideLights(hass.Hass):
def initialize(self):
# Run at Sunrise
self.run_at_sunrise(self.sunrise_cb)
# Run ... | nilq/baby-python | python |
#Hello World python script
print("Hello World")
for i in range(0, 100, 5):
print(i**2)
# y = 'Hello'
# y * 5
# y * 5.0
w = 5 / 3
x = 5.0 / 3
y = 5.0 // 3.0
z = 5 % 3
print(w, x, y, z)
# Variable points to the "object" (unlike C it does not hold the value)
# y = 'Hello'
# z = 'hello'
# print(id(y), id(z))
# a... | nilq/baby-python | python |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import sys
from destination_google_sheets import DestinationGoogleSheets
if __name__ == "__main__":
DestinationGoogleSheets().run(sys.argv[1:])
| nilq/baby-python | python |
PK
| nilq/baby-python | python |
import uuid
import os
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from .utils import auto_delete_filefields_on_delete
class File(models.Model):
name = models.CharField(max_len... | nilq/baby-python | python |
from aiomotorengine import StringField, IntField, BooleanField, FloatField, DateTimeField, ReferenceField, ListField
from xt_base.document.source_docs import InfoAsset
from xt_base.document.base_docs import Project
from dtlib.aio.base_mongo import MyDocument
from dtlib.tornado.account_docs import Organization
from dtl... | nilq/baby-python | python |
<caret>a = 1 # surprise!
b = 2
| nilq/baby-python | python |
# VNA_characteristics_classes_creators
from enum import enum
print "U R in VnaEnums" # Flag 4 debug
SweepType = enum(LINEAR=1, LOG=2, SEGM=3, POW=4)
SParameters= enum(S11=1, S12=2, S21=3, S22=4)
CalType = enum(OPEN=1, SHORT=2, THRU=3, FULL_2PORT=4, FULL_1PORT=5, TRL_2PORT=6)
DataFormat = enum(LOG=1, LIN=2, LIN_PHASE=... | nilq/baby-python | python |
from mongoengine import (
DateTimeField,
IntField,
EmbeddedDocument,
StringField,
EmbeddedDocumentListField,
BooleanField,
)
from mongoengine import Document
class UserEvent(EmbeddedDocument):
event_id = StringField()
type = StringField()
timestamp = DateTimeField()
state = Str... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.TimePeriodRule import TimePeriodRule
from alipay.aop.api.domain.TimePeriodRule import TimePeriodRule
class VoucherTemplateInfo(object):
def __init__(self):
self._amou... | nilq/baby-python | python |
""" Script for generating AE examples.
"""
import argparse
import importlib
import numpy as np
import os
from PIL import Image
import shutil
import sys
import torch
from tqdm import tqdm
from apfv21.attacks.tidr import TIDR
from apfv21.attacks.afv import AFV
from apfv21.utils import img_utils, imagenet_utils
import ... | nilq/baby-python | python |
import csv
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
pd.options.display.max_columns = None
pd.options.display.max_rows = None
# Load the pre-processsed dataset
df = pd.read_hdf('pre-processed.h5')
# Shuffling the dataset
df = df.sample(frac=1).reset_inde... | nilq/baby-python | python |
import matplotlib.pyplot as plt
import cv2 as cv
from color_component import get_channel, remove_channel
img = cv.imread('color_img.png')
plt.subplot(3, 1, 1)
imgRGB = img[:, :, ::-1]
plt.imshow(imgRGB)
ch = 1
imgSingleChannel = get_channel(img, ch)
imgRGB = cv.cvtColor(imgSingleChannel, cv.COLOR_BGR2RGB)
plt.subp... | nilq/baby-python | python |
# Generated by Django 3.0 on 2020-01-06 16:21
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('content', '0001_initial'),
migrations.swappable_dependency(settin... | nilq/baby-python | python |
from django.shortcuts import render
from django.http import HttpResponse
from .models import Pizza
def index(request):
messages = ['Welcome Pizza Lovers', 'Our currently available Pizzas are:']
for pizza in Pizza.objects.all():
messages.append(str(pizza))
for topping in pizza.topping_set.all... | nilq/baby-python | python |
import time
import traceback
import logging
import os
import matplotlib.pyplot as plt
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
from pycqed.analysis import analysis_toolbox as a_tools
class AnalysisDaemon:
"""
AnalysisDaemon is a class that allow to process analysis in a
separate pytho... | nilq/baby-python | python |
# Copyright (c) 2015 Scott Christensen
#
# This file is part of htpython modified from condorpy
#
# condorpy/htpython is free software: you can redistribute it and/or modify it under
# the terms of the BSD 2-Clause License. A copy of the BSD 2-Clause License
# should have be distributed with this file.
from collection... | nilq/baby-python | python |
#!/usr/bin/env python
# landScraper.py -v 1.7
# currently designed for python 3.10.2
# Author- David Sullivan
#
# Credit to Michael Shilov from scraping.pro/simple-email-crawler-python for the base for this code
#
# As a reminder, web scraping for the purpose of SPAM or hacking is illegal. This tool has been provided f... | nilq/baby-python | python |
"""
Dailymotion OAuth2 support.
This adds support for Dailymotion OAuth service. An application must
be registered first on dailymotion and the settings DAILYMOTION_CONSUMER_KEY
and DAILYMOTION_CONSUMER_SECRET must be defined with the corresponding
values.
User screen name is used to generate username.
By default ac... | nilq/baby-python | python |
import sys
import urllib2
import zlib
import time
import re
import xml.dom.pulldom
import operator
import codecs
from optparse import OptionParser
nDataBytes, nRawBytes, nRecoveries, maxRecoveries = 0, 0, 0, 3
def getFile(serverString, command, verbose=1, sleepTime=0):
global nRecoveries, nDataBytes, nRawBytes
if s... | nilq/baby-python | python |
from WonderPy.core.wwConstants import WWRobotConstants
from .wwSensorBase import WWSensorBase
_rcv = WWRobotConstants.RobotComponentValues
_expected_json_fields = (
_rcv.WW_SENSOR_VALUE_DISTANCE,
)
class WWSensorWheel(WWSensorBase):
def __init__(self, robot):
super(WWSensorWheel, self).__init__(robo... | nilq/baby-python | python |
#-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2022, Anaconda, Inc. All rights reserved.
#
# Powered by the Bokeh Development Team.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#---------------------------------------------------... | nilq/baby-python | python |
from ..check import Check
from ..exceptions import CheckError
def is_number(check_obj):
try:
assert isinstance(check_obj._val, check_obj.NUMERIC_TYPES)
return check_obj
except AssertionError:
raise CheckError('{} is not a number'.format(check_obj._val))
def is_not_number(check_obj):
... | nilq/baby-python | python |
import os
import json
import time
import torch
from torch import optim
import models
from utils import reduce_lr, stop_early, since
_optimizer_kinds = {'Adam': optim.Adam,
'SGD': optim.SGD}
class SimpleLoader:
def initialize_args(self, **kwargs):
for key, val in kwargs.i... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
#
# This file is part of File Dedupe
# Copyright (C) 2015 Lars Holm Nielsen.
#
# File Dedupe is free software; you can redistribute it and/or
# modify it under the terms of the Revised BSD License; see LICENSE
# file for more details.
"""Small utility for detecting duplicate files."""
import o... | nilq/baby-python | python |
#!/usr/bin/env python3
from bs4 import BeautifulSoup as bf
import requests
import json
import random
import webbrowser
import os
import urllib
import time
if not os.path.exists('images'):
os.mkdir('images')
ls = []
def huluxia(id=250):
_key = '6BD0D690D176C706DA83A5D9222E52AEF3708C7537DC1E7AEA069811D93CF42CCDEC8CF... | nilq/baby-python | python |
import rawTAspectrum
import tkinter as tk
from tkinter import ttk
from tkinter import Entry, filedialog, messagebox
from threading import Thread
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
# Implement the default Matplotlib key bindings.
from matplotlib.backend_b... | nilq/baby-python | python |
from django.db import models
import reversion
class Dois(models.Model):
texto = models.TextField(blank=False)
versao = models.PositiveIntegerField(default=1)
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
# if self.id:
# anterior = Dois.object... | nilq/baby-python | python |
from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("component", views.component, name="component"),
path("page1", views.page1, name="page1"),
path("page2", views.page2, name="page2"),
] | nilq/baby-python | python |
from pywikiapi import wikipedia
from helpers import clean_api, chunker
import os, pymysql, json, re
# Connect to English Wikipedia
class WikidataAPI:
site = None
def __init__(self):
self.site = wikipedia('www', 'wikidata')
def get_item_data(self, wd_items, raw=False, attributes = ['sitelinks', 'cla... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# vim:ts=4:sw=4:expandtab 2
# Copyright 2016, 2017 juga (juga at riseup dot net), MIT license.
version = "0.8.5"
| nilq/baby-python | python |
# SPDX-License-Identifier: MIT
"""Views in the context of rendering and compilation of layouts."""
# Python imports
from datetime import date
from logging import getLogger
# Django imports
from django.conf import settings
from django.contrib.auth.mixins import LoginRequiredMixin
from django.shortcuts import redirect... | nilq/baby-python | python |
from tabulate import tabulate
from ..helpers.resource_matcher import ResourceMatcher
try:
from IPython.core.display import display, HTML
get_ipython
def display_html(data):
display(HTML(data))
except (NameError, ImportError):
def display_html(data):
print(data)
def _header_print(head... | nilq/baby-python | python |
from hashmap.hashmap import HashMap, LinearHashMap
__all__ = ['HashMap', 'LinearHashMap'] | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Same as calc_velocity.py, but calls mpi with changa to allow many nodes
NOTE. mpirrun must be already loaded. Also, should do export MX_RCACHE=0
before loading python
Created on Wed Apr 9 15:39:28 2014
@author: ibackus
"""
import numpy as np
import pynbody
SimArray = pynbody.array.SimA... | nilq/baby-python | python |
class Country:
def __init__(self, name, capital, population, continent):
self.__name = name
self.__capital = capital
self.__population = population
self.__continent = continent
my_country = Country('France', 'Paris', 67081000, 'Europe')
print(my_country._Country__name)
print(my_country._Country__cap... | nilq/baby-python | python |
from . import utils | nilq/baby-python | python |
import torch
from torch import nn
class WeightComputer(nn.Module):
def __init__(self, mode="constant", constant_weight=1.0, consistency_fn=None, consistency_neigh=1, logits=False, device="cpu", min_weight=0.0):
"""
:param mode: in {'constant', 'balance_gt', 'pred_entropy', 'pred_consistency', 'pre... | nilq/baby-python | python |
# import the module, psqlwrapper is a class defined inside the postgresqlwrapper module
from sqlwrapper import psqlwrapper
#create a db object
db = psqlwrapper()
#let's connect to our postgres server
#remember to start your postgres server, either by using pgadmin interface or command line
db.connect('dbname', 'us... | nilq/baby-python | python |
import logging
from pathlib import Path
from typing import Optional
from genomics_data_index.storage.MaskedGenomicRegions import MaskedGenomicRegions
from genomics_data_index.storage.io.mutation.NucleotideSampleData import NucleotideSampleData
from genomics_data_index.storage.io.mutation.SequenceFile import SequenceFi... | nilq/baby-python | python |
'''Approach :
1. Create a new list "temp" containing a empty list node, i.e. value is None, as the head node
2. Set the next pointer of the head node to the node with a smaller value in the given two linked lists. For example l1's head node is smaller than l2's then set the next pointer of the new list's head node to ... | nilq/baby-python | python |
import os
import sys
import unittest
from shutil import copyfile
from unittest.mock import MagicMock, patch
import fs
import pytest
from moban.core.definitions import TemplateTarget
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
class TestCustomOptions(unittest.TestCase):
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Multilingual support postpone indefinitely. Only Help has a language option.
# (Making `app` method that handles all strings that should contain property `lang` which comes from config",
# doesn't work either because `app` doesn't exist when widgets are initialized.)
"""
Besides differences ... | nilq/baby-python | python |
from django.core.management.base import BaseCommand
from pages.models import Invite
import csv
class Command(BaseCommand):
def handle(self, *args, **options):
print('Loading CSV')
csv_path = './academy_invites_2014.csv'
with open(csv_path, 'rt') as csv_file:
csv_reader = csv.Di... | nilq/baby-python | python |
import logging
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
from galaxy_api.api import models
from galaxy_api.auth import models as auth_models
from galaxy_api.api import permissions
from .base import BaseTestCase
from .x_rh_identity import user_x_rh_id... | nilq/baby-python | python |
from __future__ import absolute_import, division, print_function
import numpy as np
import iminuit as minuit
import time
import functools
import logging
from .processing import build_trigger_windows
from scipy import optimize as op
from collections import OrderedDict
from copy import deepcopy
from scipy.special import ... | nilq/baby-python | python |
import BaseHTTPServer
import time
import sys
import SocketServer, os
import md5
try:
import json
except:
import simplejson as json
HOST_NAME = ''
PORT_NUMBER = 8000
SERVER_VERSION = '1.0.1'
SSDP_PORT = 1900
SSDP_MCAST_ADDR = '239.255.255.250'
savedDescription = {}
delay = {}
counter = {}
us... | nilq/baby-python | python |
'''
In this exercise, you'll use the Baby Names Dataset (from data.gov) again. This time, both DataFrames names_1981 and names_1881 are loaded without specifying an Index column (so the default Indexes for both are RangeIndexes).
You'll use the DataFrame .append() method to make a DataFrame combined_names. To distingu... | nilq/baby-python | python |
#!/usr/bin/env python3
import os
telamon_root = os.path.realpath("../../")
tuning_path = os.path.realpath(".")
setting_path = tuning_path + "/settings/"
spec = {
"log_file": str,
"num_workers": int,
"stop_bound": float,
"timeout": float,
"distance_to_best": float,
"algorithm": {
"type"... | nilq/baby-python | python |
#-*-coding:utf-8-*-
from pyspark.sql.types import IntegerType, TimestampType
from pyspark.sql.functions import *
from base import spark
from utils import uuidsha
columns = [
col('docu_dk').alias('alrt_docu_dk'),
col('docu_nr_mp').alias('alrt_docu_nr_mp'),
col('docu_orgi_orga_dk_responsavel').alias('alrt_... | nilq/baby-python | python |
from .base import BaseCLItest
class TestCliPush(BaseCLItest):
"""
askanna push
We expect to initiate a push action of our code to the AskAnna server
"""
verb = "push"
def test_command_push_base(self):
assert "push" in self.result.output
self.assertIn("push", self.result.outpu... | nilq/baby-python | python |
"""Class performing under-sampling based on the neighbourhood cleaning rule."""
# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
# Christos Aridas
# License: MIT
from __future__ import division, print_function
from collections import Counter
import numpy as np
from ..base import BaseMulticlassSample... | nilq/baby-python | python |
import unittest
import numpy as np
from pavlidis import pavlidis
class TestPavlidis(unittest.TestCase):
def test_pixel(self):
case = np.zeros((3, 4), np.uint8)
case[1, 2] = True
result = pavlidis(case, 1, 2)
self.assertEqual(len(result), 1)
self.assertEqual(result[0, 0], 1)... | nilq/baby-python | python |
import urllib.parse
from agent import source, pipeline
from agent.pipeline.config.stages.source.jdbc import JDBCSource
class SolarWindsScript(JDBCSource):
JYTHON_SCRIPT = 'solarwinds.py'
SOLARWINDS_API_ADDRESS = '/SolarWinds/InformationService/v3/Json/Query'
def get_config(self) -> dict:
with op... | nilq/baby-python | python |
from logging import getLogger
import multiprocessing
from pathlib import Path
import random
import traceback
from typing import Union
import networkx as nx
from remake.remake_exceptions import RemakeError
from remake.special_paths import SpecialPaths
from remake.task import Task
from remake.task_control import TaskCo... | nilq/baby-python | python |
#!/usr/bin/env python
#
# Copyright 2015 Google 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 o... | nilq/baby-python | python |
# Copyright (c) 2012 Qumulo, 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, sof... | nilq/baby-python | python |
GRAPH_ENDPOINT = 'https://graph.facebook.com/v10.0/'
INSIGHTS_CSV = 'insta_insights.csv'
HTML_FILE = 'index.html'
CSS_FILE = 'style.css'
HTML_TEMPLATE = 'index.html.template'
ID_COL = 'id'
IMPRESSIONS_COL = 'impressions'
ENGAGEMENT_COL = 'engagement'
REACH_COL = 'reach'
TIMESTAMP_COL = 'timestamp'
HOUR_COL = 'hour'
D... | nilq/baby-python | python |
"""Module with git related utilities."""
import git
class GitRepoVersionInfo:
"""
Provides application versions information based on the tags and commits in the repo
"""
def __init__(self, path: str):
"""
Create an instance of GitRepoVersionInfo
:param path: The path to search... | nilq/baby-python | python |
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.views.generic.list_detail import object_list
from django.views.generic.create_update import *
from app.models import Carrier
def index(request):
return object_list(request, Carrier.all().order('-li... | nilq/baby-python | python |
import tweepy
import requests
import json
import os
import sys
import random
import datetime
from time import sleep
# Import relevant files
import twitter
import retquote as rq
import tweetq as tq
#Insert tweet in database
def insert_tweet(tweet,client):
"""
Inserting tweets in a different collection just for lo... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 11 22:14:51 2021
@author: Allectus
"""
import os
import re
import copy
import pandas as pd
import tkinter as tk
import plotly.io as pio
import plotly.express as px
from tkinter import filedialog
from lxml import etree
#=================================================... | nilq/baby-python | python |
import requests
import json
def heapify(n, i, ll = []): #heapify function for heapsort
smallest = i
left = 2*i+1
right = 2*i+2
if left < n and ll[smallest][1] > ll[left][1]:
smallest = left
if right < n and ll[smallest][1] > ll[right][1]:
smallest = right
if i != smallest:
... | nilq/baby-python | python |
class JobError(RuntimeError):
def __init__(self, jobId):
message = "Job Failed: " + jobId
super(JobError, self).__init__(message)
| nilq/baby-python | python |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import List, Tuple, Union
import torch
from pytext.config import ConfigBase
from pytext.models.module import create_module
from .bilstm_doc_slot_attention import BiLSTMDocSlotAttention
from .jointcnn_rep import ... | nilq/baby-python | python |
from collections import namedtuple, defaultdict, Counter
import dbm
from datetime import datetime, timedelta
import json
from wit import Wit
from darksky import forecast
from apis.utils import load_parameter
# time is a unix timestamp
CacheKey = namedtuple('CacheKey', ['lat', 'lon', 'time', 'granularity'])
def cach... | nilq/baby-python | python |
#!/usr/bin/env python3
# Copyright 2019 Christian Henning
#
# 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 l... | nilq/baby-python | python |
"""manage
BaoAI Backend Main File
PROJECT: BaoAI Backend
VERSION: 2.0.0
AUTHOR: henry <703264459@qq.com>
WEBSITE: http://www.baoai.co
COPYRIGHT: Copyright © 2016-2020 广州源宝网络有限公司 Guangzhou Yuanbao Network Co., Ltd. ( http://www.ybao.org )
LICENSE: Apache-2.0
"""
import os
from flask_migrate import Migrate, MigrateComm... | nilq/baby-python | python |
r"""
================================================
CLPT (:mod:`compmech.stiffener.models`)
================================================
.. currentmodule:: compmech.stiffener.models
"""
module_names = [
'bladestiff1d_clt_donnell_bardell',
'bladestiff2d_clt_donnell_bardell',
'tstiff... | nilq/baby-python | python |
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors
# For information on the respective copyright owner see the NOTICE file
#
# 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
#
#... | nilq/baby-python | python |
"""This module contains the general information for SuggestedStorageControllerSecurityKey ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class SuggestedStorageControllerSecurityKeyConsts:
pass
class SuggestedStorageContr... | nilq/baby-python | python |
from django.shortcuts import render, render_to_response, redirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect, HttpResponse
from django.template import RequestContext
from django.core.urlresolvers import reverse
fro... | nilq/baby-python | python |
#
## https://leetcode.com/problems/palindrome-number/
#
## -2147483648 <= x <= 2147483647
#
class Solution(object):
def isPalindrome(self, x):
"""
:type x: int
:rtype: bool
"""
if x < 0:
return False
if int(str(x)[::-1]) > 2147483647 or int(str(x)[::-1]) != x:
return False
re... | nilq/baby-python | python |
from socket import *
def main():
# Cria host e port number
host = ""
port = 5000
# Cria socket
server = socket(AF_INET, SOCK_DGRAM)
# Indica que o servidor foi iniciado
print("Servidor iniciado")
# Bloco infinito do servidor
while True:
# Recebe a data e o endereço da con... | nilq/baby-python | python |
import io
import math
import skbio
from scipy.spatial import distance
from scipy.spatial import ConvexHull
import pandas as pd
import numpy as np
from skbio import TreeNode
NUM_TRI = 100
VERTS_PER_TRI = 3
ELEMENTS_PER_VERT = 5
(R_INDEX, G_INDEX, B_INDEX) = (0, 1, 2)
(R_OFFSET, G_OFFSET, B_OFFSET) = (2, 3, 4)
def in... | nilq/baby-python | python |
from kimonet.system.generators import regular_system, crystal_system
from kimonet.analysis import visualize_system, TrajectoryAnalysis
from kimonet.system.molecule import Molecule
from kimonet import system_test_info
from kimonet.core.processes.couplings import forster_coupling
from kimonet.core.processes.decays import... | nilq/baby-python | python |
import numpy as np
import pytest
from quara.loss_function.loss_function import LossFunction, LossFunctionOption
class TestLossFunctionOption:
def test_access_mode_weight(self):
loss_option = LossFunctionOption()
assert loss_option.mode_weight == None
loss_option = LossFunction... | nilq/baby-python | python |
import os
import io
from setuptools import setup
here = os.path.abspath(os.path.dirname(__file__))
def get_readme():
path = os.path.join(here, 'README.md')
with io.open(path, encoding='utf-8') as f:
return '\n' + f.read()
setup(
name='ndc_parser',
version='0.1',
description='NDC Parser',
... | nilq/baby-python | python |
import unittest
import torch
from fn import F
from fn.op import apply
from tensorneko.layer import Linear
from torch.nn import Linear as PtLinear, LeakyReLU, BatchNorm1d, Tanh
class TestLinear(unittest.TestCase):
@property
def batch(self):
return 4
@property
def in_neurons(self):
r... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Copyright 2016, RadsiantBlue Technologies, 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... | nilq/baby-python | python |
def max_val(t):
"""
t, tuple or list
Each element of t is either an int, a tuple, or a list
No tuple or list is empty
Returns the maximum int in t or (recursively) in an element of t
"""
def find_all_int(data):
int_list = []
for item in data:
if isinstance(item, l... | nilq/baby-python | python |
from __future__ import absolute_import
# noinspection PyUnresolvedReferences
from .ABuPickStockExecute import do_pick_stock_work
# noinspection PyUnresolvedReferences
from .ABuPickTimeExecute import do_symbols_with_same_factors, do_symbols_with_diff_factors
# noinspection all
from . import ABuPickTimeWorker as pick_ti... | nilq/baby-python | python |
#!/usr/bin/env python2.7
# license removed for brevity
import rospy
import numpy as np
import json
import time
from std_msgs.msg import String
from std_msgs.msg import Bool
from rospy.numpy_msg import numpy_msg
from feedback_cclfd.srv import RequestFeedback
from feedback_cclfd.srv import PerformDemonstration
from fee... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2016-2017 China Telecommunication Co., Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/lice... | nilq/baby-python | python |
# Test case that runs in continuous integration to ensure that PTest isn't broken.
from .base import SingleSatOnlyCase
from .utils import Enums, TestCaseFailure
import os
class CICase(SingleSatOnlyCase):
def run_case_singlesat(self):
self.sim.cycle_no = int(self.sim.flight_controller.read_state("pan.cycle_... | nilq/baby-python | python |
from __future__ import division
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import normal_init
from mmcv.cnn import constant_init
from mmdet.core import (PointGenerator, multi_apply, multiclass_rnms,
images_to_levels, unmap)
from mmdet.core... | nilq/baby-python | python |
"""
Django settings for sentry_django_example project.
Generated by 'django-admin startproject' using Django 3.2.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""... | nilq/baby-python | python |
""" calc.py - simple code to show how to execute testing
"""
def sum(a: float, b: float) -> float:
"""sum adds two numbers
Args:
a (float): First number
b (float): Second number
Returns:
float: sum of a and b
>>> sum(2,3)
5
"""
return a+b... | nilq/baby-python | python |
#!/usr/bin/env python
"""
File metadata consistency scanner.
Python requirements: Python 2.7, :mod:`psycopg2`, Enstore modules.
"""
# Python imports
from __future__ import division, print_function, unicode_literals
import atexit
import ConfigParser
import copy
import ctypes
import datetime
import errn... | nilq/baby-python | python |
# SPDX-FileCopyrightText: 2019-2021 REFITT Team
# SPDX-License-Identifier: Apache-2.0
"""Integration tests for forecast interface."""
# type annotations
# standard libs
# external libs
import pytest
# internal libs
from refitt.data.forecast import Forecast
from refitt.database.model import Observation as Observat... | nilq/baby-python | python |
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return render(request,'home.html',{'name':'Smit'})
def add(request):
val1 = request.POST['num1']
val2 = request.POST['num2']
return render(request,'result.html',{'result_add':int(val... | nilq/baby-python | python |
# coding: utf-8
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import json
import tensorflow as tf
from utils import queuer
def decoding(sprobs, samples, params, mask=None):
"""Generate decoded sequence from seqs"""
if mask is None:
... | nilq/baby-python | python |
# --------------------------------------------------------------------------- #
# aionextid.py #
# #
# Copyright © 2015-2022, Rajiv Bakulesh Shah, original author. #
... | nilq/baby-python | python |
import os
import sys
import logging
import re
from django.core.exceptions import ImproperlyConfigured
from pathlib import Path # python3 only
logger = logging.getLogger(__name__)
def dotenv_values(dotenv_path):
lines = []
try:
with open(dotenv_path) as fp:
lines = fp.read().splitlines()
... | nilq/baby-python | python |
"""
Tools for asking the ESP about any alarms that have been raised,
and telling the user about them if so.
The top alarmbar shows little QPushButtons for each alarm that is currently active.
If the user clicks a button, they are shown the message text and a "snooze" button
for that alarm.
There is a single physical ... | nilq/baby-python | python |
"""
atpthings.util.dictionary
-------------------------
"""
def getKeys(dictionary: dict, keys: list) -> dict:
"""Get keys from dictionary.
Parameters
----------
dictionary : dict
Dictionary.
keys : list
List of keys wonted to be extracted.
Returns
-------
dict
... | nilq/baby-python | python |
import wx
from html import escape
import sys
import Model
import Utils
class Commentary( wx.Panel ):
def __init__( self, parent, id = wx.ID_ANY ):
super().__init__(parent, id, style=wx.BORDER_SUNKEN)
self.SetDoubleBuffered(True)
self.SetBackgroundColour( wx.WHITE )
self.hbs = wx.BoxSizer(wx.HORIZONTAL)
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^(?P<username>[\w.@+-]+)/$', views.UserDetailView.as_view(), name='detail'),
]
| nilq/baby-python | python |
import torch
import numpy as np
from torch import nn
import torch.nn.functional as F
from . import *
class GlowLevel(nn.Module):
def __init__(self, in_channel, filters=512, n_levels=1, n_steps=2):
'''
Iniitialized Glow Layer
Parameters
----------
in_channel : int
number of ... | nilq/baby-python | python |
from collections import defaultdict
from glypy.io import iupac, glycoct
from glypy.structure.glycan_composition import HashableGlycanComposition, FrozenGlycanComposition
from glypy.enzyme import (
make_n_glycan_pathway, make_mucin_type_o_glycan_pathway,
MultiprocessingGlycome, Glycosylase, Glycosyltransferase,... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.