content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
#!/usr/bin/env python3 -u # -*- coding: utf-8 -*- # copyright: sktime developers, BSD-3-Clause License (see LICENSE file) __author__ = ["Markus Löning"] __all__ = ["test_gscv_fit", "test_rscv_fit"] import numpy as np import pytest from sklearn.base import clone from sklearn.linear_model import LinearRegression from s...
nilq/baby-python
python
# Copyright 2018 Xanadu Quantum 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 applicable law...
nilq/baby-python
python
## @file test_git_dependency.py # Unit test suite for the GitDependency class. # ## # Copyright (c) Microsoft Corporation # # SPDX-License-Identifier: BSD-2-Clause-Patent ## import unittest from edk2toolext.environment import var_dict class TestVarDict(unittest.TestCase): def setUp(self): pass def te...
nilq/baby-python
python
import os from os import listdir from os.path import isfile, join import cv2 import numpy as np number = 2 mypath = "pillPictures/" + str(number) savepath = "pillPictures/saved" onlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))] img_count = 0 for file in onlyfiles: img_count = img_count + 1 image_...
nilq/baby-python
python
import numpy as np import cv2 from mss import mss from PIL import Image # There's no native way of handling the feature of getting the window "always on top" # It's OS dependent forcing it to not be cross platform # -> this is a windows way of handling things. Marked with TODOs #import os # signals and signal handler...
nilq/baby-python
python
from overrides import overrides from typing import Dict, Iterator, List, Tuple import json from functools import reduce from operator import mul import os def compute_alignment_differences(align_str: str): aligns = align_str.split(" ") align_diff = 0. for align in aligns: i, j = align.split("-") ...
nilq/baby-python
python
from rockstar import RockStar css_code = """body:before { content: "Hello, world!"; }""" rock_it_bro = RockStar(days=400, file_name='helloworld.css', code=css_code) rock_it_bro.make_me_a_rockstar()
nilq/baby-python
python
"""Read command line argument. Assign to _x the string value of the first command line parameter, after the program name. Source: programming-idioms.org """ # Implementation author: nickname # Created on 2016-02-18T16:58:00.600634Z # Last modified on 2016-02-18T16:58:00.600634Z # Version 1 # argv[0] is the program ...
nilq/baby-python
python
# -*- coding: utf-8 -*- """ Created on Tue Mar 20 11:24:29 2018 @author: mayank """ import numpy as np #import pandas as pd #from time import time from sklearn.model_selection import StratifiedKFold #import os #from sklearn.cluster import KMeans from sklearn.utils import resample from scipy.stats import...
nilq/baby-python
python
#!/usr/local/Cellar/python/2.7.6/bin/python # -*- coding: utf-8 -*- import sys import scipy.misc, scipy.io, scipy.optimize from sklearn import svm, grid_search from numpy import * import pylab from matplotlib import pyplot, cm from mpl_toolkits.mplot3d import Axes3D import matplotlib.mlab as mlaba from util import U...
nilq/baby-python
python
# # Copyright 2021 Red Hat Inc. # SPDX-License-Identifier: Apache-2.0 # """Test the OCPReportProcessor.""" import datetime from unittest.mock import patch from api.utils import DateHelper from masu.database import OCP_REPORT_TABLE_MAP from masu.database.ocp_report_db_accessor import OCPReportDBAccessor from masu.datab...
nilq/baby-python
python
# MQTT import sensor # Shock sensor import RPi.GPIO as GPIO class ShockSensor(sensor.Sensor): def __init__(self): super(ShockSensor, self).__init__() GPIO.setmode(GPIO.BCM) self.SHOCK_PIN = 17 GPIO.setup(self.SHOCK_PIN, GPIO.IN) def get_value(self): # The vibration sensor is 1 when no vibration is detect...
nilq/baby-python
python
from comm.ntlmrelayx.servers.httprelayserver import HTTPRelayServer from impacket.examples.ntlmrelayx.servers.smbrelayserver import SMBRelayServer
nilq/baby-python
python
# Generated by Django 3.1.4 on 2021-01-10 00:37 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('resume', '0003_auto_20210109_1855'), ] operations = [ migrations.AlterField( model_name='resumesubsection', name='su...
nilq/baby-python
python
#coding=utf-8 from django import forms from common.models import PersonTelephoneNumber, TelephoneNumber from django.core import validators from django.forms.models import ModelForm from personal.models import Firefighter class PersonPhoneForm(forms.Form): id = forms.CharField(widget=forms.HiddenInput, required=Fa...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ """ from __future__ import unicode_literals from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import range from builtins import object from threading import Thread import socket import pickle a...
nilq/baby-python
python
from django.core.management.base import BaseCommand from flatblocks.models import FlatBlock from camper.pages.models import Chunk class Command(BaseCommand): help = 'Copes FlatBlock content into new Chunk objects' def handle(self, *args, **options): for fb in FlatBlock.objects.all(): t...
nilq/baby-python
python
__all__ = ["configreader"]
nilq/baby-python
python
import discord from discord.ext import commands class Hater(commands.Cog): def __init__(self, client): self.client = client self.client.hated_list = [] @commands.command() async def hate(self, ctx, hated): hated_id = int(hated[3:-1]) hated_member = ctx.guild.get_member...
nilq/baby-python
python
# Copyright 2018 NTRlab # # 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, softw...
nilq/baby-python
python
#!/usr/bin/env python """This module provides functionality to create a custom preoptimization sequence from a directed acyclic graph (DAG) using topological sorting. In the current version the DAG have to be specified manually via constants. """ import multiprocessing import random import logging import polyjit.expe...
nilq/baby-python
python
from typing import overload from UdonPie import System from UdonPie import UnityEngine from UdonPie.Undefined import * class AnimatorOverrideController: def __new__(cls, arg1=None): ''' :returns: AnimatorOverrideController :rtype: UnityEngine.AnimatorOverrideController ''' ...
nilq/baby-python
python
from pydantic import BaseModel, Field class DOIDoc(BaseModel): """ DOIs to reference specific materials on Materials Project. """ doi: str = Field( None, description="DOI of the material.", ) bibtex: str = Field( None, description="Bibtex reference of the material.", ) ...
nilq/baby-python
python
from flask import g, jsonify, request from app import auth from app.services.base.models import User, LoginLog from app.services.base.views import bp @bp.route('/login_logs') @auth.login_required def list_login_logs(): query = LoginLog.query \ .join(User, LoginLog.userIntID == User.id) \ .with_...
nilq/baby-python
python
import json import os from typing import List from stonehenge.db.operations import Operation from stonehenge.db.migrations.exceptions import UnappliedMigrationException class Migration: def __init__( self, operations: List[Operation], migrations_dir: str, ): self.operations = ...
nilq/baby-python
python
""" web server 为使用者提供一个类, 使用这可以快速的搭建web服务, 展示自己的网页 """ from socket import * from select import select # 主体功能 class HTTPServer: def __init__(self,host='0.0.0.0',port=8080,dir=None): self.host = host self.port = port self.dir = dir def start(self): pass if __name__ == '__main__...
nilq/baby-python
python
## HOST and PORT info HOST = "127.0.0.1" PORT = 8000 ## Server name SERVER = "Lemon Server" ## folder config STATIC = "static" RENDER = "render" ## Token info for sessions token = "SessionToken" token_length = 100 #blacklist blacklist = [] #Temp Folder TEMP = "Temp" #File extension for files that can have vari...
nilq/baby-python
python
# # Copyright 2018 Dynatrace 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 writi...
nilq/baby-python
python
#!/usr/bin/python import sys import re import os fasta_file = sys.argv[1] fasta_file_AT_only = sys.argv[2] if not os.path.exists(os.path.dirname(fasta_file_AT_only)): try: os.makedirs(os.path.dirname(fasta_file_AT_only)) except OSError as exc: # Guard against race condition if exc.errno != er...
nilq/baby-python
python
""" * Vehicle Routing Problem * Steps of the algorithm: 1. Creation of a given number of clusters 2. Creation of an optimal path (loop) for each cluster Graph Optimisation : basic 2-opt algorithm Clustering : centroid-based method """ from random import * from math import sqrt import matplotlib.pyplot as plt import ne...
nilq/baby-python
python
def append_new_line(file_name, text_to_append): """Append given text as a new line at the end of file""" # Open the file in append & read mode ('a+') with open(file_name, "a+") as file_object: # Move read cursor to the start of file. file_object.seek(0) # If file is not empty then ap...
nilq/baby-python
python
import discord import os import requests import json import random from replit import db from keepmealive import keep_alive client = discord.Client() sad_words=["sad","depressed","unhappy","lost","angry","miserable","depressing"] starter_encouragements=[ "cheer Up! ", "You are a great Guy!" ] def ge...
nilq/baby-python
python
from copy import deepcopy import numpy from theano.gof.op import PureOp from theano.gof import Apply, generic, Container from theano.gof.link import LocalLinker, map_storage, add_clear_storage from theano import function, Mode from theano.ifelse import ifelse import theano.tensor as T class IfElseIfElseIf(PureOp): ...
nilq/baby-python
python
import sqlite3 def connectTab(db_name: str = 'dados.db') -> sqlite3.Connection: conexao = sqlite3.connect(f'../{db_name}') conexao.row_factory = sqlite3.Row return conexao def createTab(tab_name: str = 'pessoas'): conexao = connectTab() print(type(conexao)) with conexao: cursor =...
nilq/baby-python
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may ...
nilq/baby-python
python
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from pants.base.exceptions import TaskError from pants.task.lint_task_mixin import LintTaskMixin from pants.contrib.go.tasks.go_fmt_task_base import GoFmtTaskBase class GoCheckstyle(Lin...
nilq/baby-python
python
import yaml import torch from torch import package import sys sys.path.append('../../') import config class Punctuation(object): def __init__(self, model_path=config.model_path_punctuation, step=config.step_punctuation): self.model_path = model_path sel...
nilq/baby-python
python
#! /usr/bin/env python from __future__ import print_function from FWCore.ParameterSet.pfnInPath import pfnInPath import FWCore.ParameterSet.Config as cms import sys import os import re if os.getenv('LOCAL_TOP_DIR') == None: print("The environment variable LOCAL_TOP_DIR must be set to run this script") print("...
nilq/baby-python
python
# Copyright (c) 2018, Novo Nordisk Foundation Center for Biosustainability, # Technical University of Denmark. # # 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/lic...
nilq/baby-python
python
#!/usr/bin/env python3 import unittest import subprocess as sub from astropy.time import Time from bin import epics_fetch class TestEPICSFetch(unittest.TestCase): def test_known_date(self): t = Time('2020-06-07T00:00', format='isot') data = epics_fetch.get_data(['25m:mcp:cwPositions'], t.datetime,...
nilq/baby-python
python
""" Customfield. Do not edit this file by hand. This is generated by parsing api.html service doc. """ from ambra_sdk.exceptions.service import AccountNotFound from ambra_sdk.exceptions.service import FilterNotFound from ambra_sdk.exceptions.service import InvalidCondition from ambra_sdk.exceptions.service import Inva...
nilq/baby-python
python
from adafruit_servokit import ServoKit from dcservo import DogCamServoBase # Don't export ServoLib __all__ = ("DogCamServoAda") # Bring in global instance ServoLib = ServoKit(channels=16) class DogCamServoAda(DogCamServoBase): def __init__(self, InName, InPin, ZeroAngle=0.0, Steps=1.0, LowerBounds=0.0, UpperBounds...
nilq/baby-python
python
''' code by Tae Hwan Jung(Jeff Jung) @graykode ''' import tensorflow as tf import matplotlib.pyplot as plt import numpy as np tf.reset_default_graph() # 3 Words Sentence sentences = [ "i like dog", "i like cat", "i like animal", "dog cat animal", "apple cat dog like", "dog fish milk like", ...
nilq/baby-python
python
import ply.lex as lex import ply.yacc as yacc KEYWORDS = ("run", "load", "save", "insert", "clear", "quit", "exit") PARAMS = ("topology", "width", "height") DOMAINS = ("'KleinBottle'", "'MoebiusBand'", "'Torus'", "'Cylinder'", "'Plane'") class Parser: """ Base class for a lexer/parser that has the rules defin...
nilq/baby-python
python
""" Images should have the shape b x c x h x w. Masks attach an alpha channel with masking values in the range [0, 1], which can be consumed by other augmentation layers. Masks themselves consume alpha channels by multiplying the old with the new. """ import math import torch import torch.fft from torch import Tensor ...
nilq/baby-python
python
# Copyright (c) Microsoft Corporation. # Licensed under the MIT license. PAD_WORD_ID = 0 UNK_WORD_ID = 1 END_WORD_ID = 2 PAD_CHAR = 261 BOW_CHAR = 259 EOW_CHAR = 260
nilq/baby-python
python
import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt file_1 = '/ai4efs/models/object_detection/faster_rcnn_inception_resnet_v2_atrous/train_on_ss/predictions/eccv_train_per_cat_prec_recall_data.npz' data_1 = np.load(open(file_1,'r')) file_2 = '/ai4efs/models/object_detection/fast...
nilq/baby-python
python
from pathlib import Path import pytest import git import json import os from conftest import TEST_DIR from masonry import main from cookiecutter.exceptions import FailedHookException, UndefinedVariableInTemplate @pytest.fixture(scope='module') def init_simple_project(tmpdir_factory): # Setup a basic project ...
nilq/baby-python
python
# standard import os # BASE DIRECTORY BASE_DIR = os.path.dirname(os.path.dirname(__file__)) # HEARTBEAT HEARTBEAT = 10 * 1000 # INTERNET INTERNET = { 'address': '1.1.1.1', 'port': 53, 'timeout': 3, 'interval': 5 * 1000 } # MODULES MODULES = ('fb', 'synker') MODULES_DIR = 'src.modules' MODULES_CO...
nilq/baby-python
python
from django.db import models # Create your models here. class douban_top250(models.Model): serial_number=models.IntegerField() movie_name=models.CharField(max_length=255) introduce=models.CharField(max_length=255) star=models.FloatField(max_length=12) evaluate=models.CharField(max_length=255) ...
nilq/baby-python
python
#!/usr/bin/env python3 import os import math import sys from abc import abstractmethod import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from nets import nets_factory, resnet_utils import aardvark import cv2 from tf_utils import * import cpp flags = tf.app.flags FLAGS = flags.FLAGS fl...
nilq/baby-python
python
import os import sys import yaml import json import pprint import pathlib import logging import inspect import argparse import itertools import importlib from genie.metaparser import MetaParser IGNORE_DIR = ['.git', '__pycache__', 'template', 'tests'] IGNORE_FILE = ['__init__.py', 'base.py', 'utils.py'] AVAILABLE_FUN...
nilq/baby-python
python
from nltk import tokenize from operator import itemgetter import math import nltk from nltk.corpus import stopwords from nltk.tokenize import word_tokenize stop_words = set(stopwords.words('english')) #nltk.download('stopwords') ## 2 Declare Variables doc = '''I am from speak english with vanessa da com.You are so ...
nilq/baby-python
python
#!/usr/bin/env python """Provides Generic Classes to make an image analysis. """ from abc import ABC, abstractmethod import pandas as pd class InputData(ABC): def __init__(self, data): self._content = data @abstractmethod def read(self): pass class Cohort(InputData): def __init__(...
nilq/baby-python
python
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging from dataclasses import dataclass, field from typing import Dict, List, Optional import torch from fairseq.dataclass import Fa...
nilq/baby-python
python
def cbrt(a): s = -1 if a < 0 else 1 return s * (a*s) ** (1/3) print(cbrt(-8)) # -2.0 print(cbrt(8)) # 2.0 print(cbrt(0)) # 0.0
nilq/baby-python
python
import pytest from eth_account import Account from eth_keys import KeyAPI from eth_utils import is_same_address @pytest.fixture def c(w3, get_contract): a0, a1, a2, a3, a4, a5, a6 = w3.eth.accounts[:7] with open("examples/wallet/wallet.vy") as f: code = f.read() # Sends wei to the contract for fut...
nilq/baby-python
python
from django.db import models # Create your models here. class Course(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255, null=False) class Slot(models.Model): MON = 1 TUE = 2 WED = 3 THU = 4 FRI = 5 DAY_CHOICES = [ (MON, 'Mon'), ...
nilq/baby-python
python
import Tkinter import tkinter class TkinterImplementation(object): def begin(self, wrappedIdleImage): self.root = tkinter.Tk() self.root.overrideredirect(True) self.root.geometry( "{0}x{1}+0+0".format(self.root.winfo_screenwidth(), self.root.winfo_screenheight())) self...
nilq/baby-python
python
""" Some utility functions that are only used for unittests. Placing them in test/ directory seems to be against convention, so they are part of the library. """ from __future__ import print_function, division, absolute_import import random import copy import numpy as np import six.moves as sm # unittest.mock is not...
nilq/baby-python
python
"""io Core IO Modules """ import os import json import pickle ############################################################### # Common I/O operations # ====================== # def makedirs(filepath): os.makedirs(os.path.dirname(filepath), exist_ok=True) def walk(source_dir): paths = list() for root, ...
nilq/baby-python
python
from django.shortcuts import render from account.models import Account from datetime import datetime def home(request): # Editing Earl of the Day ID should update all data on home page earl_of_the_day_id = 2 month = datetime.today().month upcoming_birthdays = Account.objects.filter(birthday__month=mon...
nilq/baby-python
python
from pyrk.materials.material import Material from pyrk.utilities.ur import units from pyrk.density_model import DensityModel from pyrk.inp import validation class LiquidMaterial(Material): ''' subclass of material for liquid''' def __init__(self, name=None, k=0 * units.watt ...
nilq/baby-python
python
# -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incor...
nilq/baby-python
python
#!/usr/bin/env python '''Generate a series of calibration frames using POV-ray.''' from __future__ import division import sys, os, math def do_scene (x, y, z, fn): '''Generate a frame with the camera at x,y,z into fn and render it.''' f = open (fn, 'w') print >>f, '#include "calibration_target.pov"' pr...
nilq/baby-python
python
from pypeflow.common import * from pypeflow.data import PypeLocalFile, makePypeLocalFile, fn from pypeflow.task import PypeTask, PypeThreadTaskBase, PypeTaskBase from pypeflow.controller import PypeWorkflow, PypeThreadWorkflow import os import uuid import sys def run_script(job_data, job_type = "SGE" ): if job_t...
nilq/baby-python
python
""" ray.py defines a class of rays that can be represented in space. A ray propagates in the optical system and can be refracted, reflected or dispersed. Each instantiation is hence described by several line segments in space which are determined by their endpoints and directions. The final segment determines the curr...
nilq/baby-python
python
from django.views import View from django.http import JsonResponse from django.shortcuts import render, reverse from django.contrib.auth.mixins import LoginRequiredMixin from core.models import DesignDocument, UserDocumentDownload, UserDocumentFavorite class ProfileView(LoginRequiredMixin, View): template_name = ...
nilq/baby-python
python
#Use emcee as a Metropolis-Hastings so we can avoid a lot of the difficulty of the ensemble sampler for the moment. import numpy as np import emcee #create our lnprob as a multidimensional Gaussian, where icov is C^{-1} def lnprob(x, mu, icov): diff = x-mu lnp = -np.dot(diff,np.dot(icov,diff))/2.0 print(...
nilq/baby-python
python
temporario = list() principal = list() maior = menor = 0 while True: temporario.append(input("Nome: ").strip().title()) temporario.append(float(input("Peso: "))) if len(principal) == 0: maior = menor = temporario[1] else: if temporario[1] > maior: maior = temporar...
nilq/baby-python
python
from setuptools import setup setup(name='myslice', version='2.0.0', description='MySlice version 2', url='http://myslice.info', author='Ciro Scognamiglio', author_email='ciro.scognamiglio@lip6.fr', license='MIT', packages=['myslice'], #install_requires=[ # 'torn...
nilq/baby-python
python
import logging import operator import time from functools import reduce from typing import Optional, Union, Dict, Collection, Any logger = logging.getLogger(__name__) class Configuration(object): def __init__(self, c:Optional[Union['Configuration', Dict]]=None): """Create Configuration object py...
nilq/baby-python
python
""" collection of helper functions """ from __future__ import print_function, division, absolute_import import os from glob import glob from collections import defaultdict import tables from .. import NcsFile, options def check_sorted(channel_dirname): """ check how many 'sorted_...' folder there are """ ...
nilq/baby-python
python
# -*- coding: utf-8 -*- import unittest from hamlish_jinja import Hamlish, Output import testing_base class TestDebugOutput(testing_base.TestCase): def setUp(self): self.hamlish = Hamlish( Output(indent_string='', newline_string='', debug=False)) def test_pre_tags(self): s...
nilq/baby-python
python
import os os.environ['CUDA_DEVICE_ORDER']='PCI_BUS_ID' os.environ['CUDA_VISIBLE_DEVICES']='' import numpy as np from tensorflow.keras.layers import Input, Dense, SimpleRNN, GRU, LSTM, Bidirectional from tensorflow.keras.models import Model REC = LSTM sequence_length = 3 feature_dim = 1 features_in = Input(batch_shap...
nilq/baby-python
python
import b128 import itertools import os import plyvel import secp256k1 from binascii import unhexlify from utxo.script import OP_DUP, OP_HASH160, OP_EQUAL, \ OP_EQUALVERIFY, OP_CHECKSIG def ldb_iter(datadir): db = plyvel.DB(os.path.join(datadir, "chainstate"), compression=None) obf_key = db.get((unhexlify...
nilq/baby-python
python
# # Copyright 2021 Red Hat Inc. # SPDX-License-Identifier: Apache-2.0 # """Provider Model Serializers.""" import logging from collections import defaultdict from django.conf import settings from django.db import transaction from rest_framework import serializers from rest_framework.fields import empty from api.common...
nilq/baby-python
python
""" collision_detection.py is used on each iteration to detect whether an agent has collided with walls and to provide an adequate environment response (i.e. updated position & velocity such that agen slides along the wall). """ import numpy as np import pygame as pg from decimal import Decimal import configs as cfg ...
nilq/baby-python
python
import copy import numpy as np import pytest import xarray as xr from gcm_filters import Filter, FilterShape, GridType from gcm_filters.filter import FilterSpec def _check_equal_filter_spec(spec1, spec2): assert spec1.n_steps_total == spec2.n_steps_total np.testing.assert_allclose(spec1.s, spec2.s) asse...
nilq/baby-python
python
import configparser import logging import os import shutil from pathlib import Path from urllib.error import URLError import intake import matplotlib.image as mplimg import pandas as pd try: from urllib import urlretrieve except ImportError: from urllib.request import urlretrieve pkg_name = __name__.split("...
nilq/baby-python
python
class Instance(Element,IDisposable): """ The base class for all instance objects. """ def Dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def getBoundingBox(self,*args): """ getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """ pass def GetTotalTransform(self): """ GetTot...
nilq/baby-python
python
from layers import * from encoding import * import matplotlib.pyplot as plt import csv import sys import getopt import random # Path to save the parameters filename = 'parameters.npz' # Train the RNN with the given parameters def train(learning_rate, units, epochs): # Try to load the parameters if they are sa...
nilq/baby-python
python
def selection_sort(some_list): """ https://en.wikipedia.org/wiki/Selection_sort Split the list into a sorted/unsorted portion. Go through the list from left to right, starting with position 0 in the unsorted portion. When we find the minimum element of the unsorted portion, swap it to the end of the sor...
nilq/baby-python
python
""" Boolean Satisfiability Interface Classes: DPLLInterface Interface Functions: backtrack iter_backtrack dpll """ import random class DPLLInterface(object): """DPLL algorithm interface""" def bcp(self): """Boolean Constraint Propagation Return an untyped point that result...
nilq/baby-python
python
import numpy as np class Constant(object): """ Concatenates a constant value to the node attributes. **Arguments** - `value`: the value to concatenate to the node attributes. """ def __init__(self, value): self.value = value def __call__(self, graph): value = np.zeros((g...
nilq/baby-python
python
import glob from os import path as osp import numpy as np import pytest import tqdm import habitat_sim NUM_TESTS = 100 TURN_DEGREE = 30.0 ACCEPTABLE_SPLS = { ("try_step", False): 0.97, ("try_step_no_sliding", False): 0.925, ("try_step", True): 0.82, ("try_step_no_sliding", True): 0.60, } base_dir =...
nilq/baby-python
python
""" Views related to rsync or FTP account access. """ __author__ = "William Tucker" __date__ = "2018-03-13" __copyright__ = "Copyright 2019 United Kingdom Research and Innovation" __license__ = "BSD - see LICENSE file in top-level package directory" from django.shortcuts import render, redirect from uploader.ftp.fo...
nilq/baby-python
python
from dataclasses import dataclass, field from typing import Optional # TODO: remove default Hydra pallets - pallets will become required parameter PALLETS = ["amm", "exchange", "transaction_multi_payment"] @dataclass class Config: do_db_bench: bool = False substrate_repo_path: str = "./substrate" do_pall...
nilq/baby-python
python
import pyaudio class AudioRecorder: def __init__(self, channels_=2, format_=pyaudio.paInt16, rate_=44100, chunk_=256): self.audio = pyaudio.PyAudio() self.stream = self.audio.open(format=format_, channels=channels_, rate=rate_, input=True, frames_per_buffer=chunk_)...
nilq/baby-python
python
import argparse import logging import gdk.commands.methods as methods import gdk.common.parse_args_actions as actions import pytest def test_run_command_with_valid_namespace_without_debug(mocker): # Integ test that appropriate action is called only once with valid command namespace. args_namespace = argparse...
nilq/baby-python
python
# -*- encoding: utf-8 -*- from django import forms from .models import Image, UserProfile, Establishment from django.contrib.auth.models import User from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.forms.widgets import TextInput, PasswordInput from mysite.widgets import MyClearable...
nilq/baby-python
python
#!/usr/bin/python # Copyright 2012 Google Inc. All Rights Reserved. # Author: mrdmnd@ (Matt Redmond) # Based off of code in //depot/google3/experimental/mobile_gwp """Code to transport profile data between a user's machine and the CWP servers. Pages: "/": the main page for the app, left blank so that users cann...
nilq/baby-python
python
from typing import Iterable import torch from torch import Tensor def to_np(arr): return arr.detach().cpu().numpy() def to_t(t: Iterable, device: torch.device = 'cuda', dtype: torch.dtype = torch.float64) -> Tensor: if isinstance(t, Tensor): return t return torch.tensor(t, device=device, dtype=...
nilq/baby-python
python
"""PivotCalculator Pivot points is the top/bottom that the price has ever reached. """ from collections import deque, namedtuple from operator import gt class PivotCalculator(object): def __init__(self, window_size=5, cmp=gt): self.window_size = window_size self.cmp = cmp # exit_check: w...
nilq/baby-python
python
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities from...
nilq/baby-python
python
import logging import os import yaml from DataCuration.main import main as start_web_scrape from util import create_folder def load_config(): """ Loads the configuration file :return: Content of the configuration file """ with open('config.yaml', 'r') as file: content = yaml.load(file, ...
nilq/baby-python
python
######################################## # PROJECT 1 - Linked List # Author: Tony Sulfaro # PID: A52995491 ######################################## class Node: # DO NOT MODIFY THIS CLASS # __slots__ = 'value', 'next_node' def __init__(self, value, next_node=None): """ DO NOT EDIT ...
nilq/baby-python
python
from html_parse.src.parser import Parser import unittest class TestParser(unittest.TestCase): def test_remove_end_tags(self): parser = Parser() html_string = '<title>Hello</title>' self.assertEqual(parser.remove_end_tags(html_string), '<title>Hello|;|') def test_remove_end_tags_wit...
nilq/baby-python
python
""" Book: Building RESTful Python Web Services Chapter 3: Improving and adding authentication to an API with Django Author: Gaston C. Hillar - Twitter.com/gastonhillar Publisher: Packt Publishing Ltd. - http://www.packtpub.com """ from rest_framework.pagination import LimitOffsetPagination class LimitOffsetPagination...
nilq/baby-python
python
# AUTHOR: Dalon Lobo # Python3 Concept: Plotting line plot using matplotlib # GITHUB: https://github.com/dalonlobo import numpy as np import matplotlib.pyplot as plt # Create dummy x and y values. In this case I create values using numpy. # This graph will show sine wave x = np.arange(0, 10, 0.1) # Values for x coor...
nilq/baby-python
python