content
stringlengths
0
1.05M
origin
stringclasses
2 values
type
stringclasses
2 values
import torch import torch.nn as nn class FocalLoss(nn.Module): def __init__(self,gamma=2,eps=1e-7,size_average=True): super(FocalLoss,self).__init__() self.gamma = gamma self.eps = eps self.size_average = size_average def forward(self,prob,labels): p_t = prob*labels + ...
nilq/baby-python
python
#Crie um programa que tenha uma tupla única com nomes de produtos e seus respectivos preços, #na sequência. No final, mostre uma listagem de preços, organizando os dados em forma tabular. Tabela = ('Lapís', 1.75, 'Borracha', 2, 'Caderno', 15.90, 'Estojo', 25, 'Transferidor', 4.20, ...
nilq/baby-python
python
import maya.cmds as mc import copy def setDrivenKeyToRemapValue(animCurve,remapValueNode='',interpType=3,deleteAnimCurve=True,lockPosition=True,lockValue=False): ''' Convert a set driven key setup to a remapValue node. Each key on the animCurve node is represented as widget on the remapValue ramp control. Incoming...
nilq/baby-python
python
import numpy as np from keras.models import Sequential from keras.layers import Dense,Activation,Flatten,Dropout from keras.layers import Conv2D,MaxPooling2D from keras.callbacks import ModelCheckpoint from sklearn.model_selection import train_test_split from matplotlib import pyplot as plt data=np.load('data....
nilq/baby-python
python
import zipfile import os from time import gmtime, strftime from helper import utility from lxml import etree """ MIT License Copyright (c) 2018 Chapin Bryce, Preston Miller Please share comments and questions at: https://github.com/PythonForensics/Learning-Python-for-Forensics or email pyforcookbook@gmail.com Pe...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding:utf-8 -*- from app import db age_func = db.Table('age_func', db.Column('id', db.Integer, primary_key=True, autoincrement=True), db.Column('age_id', db.Integer, db.ForeignKey('age_group.id'), nullable=False), db.Column('fun...
nilq/baby-python
python
# Tool Imports from bph.tools.windows.nircmd import BphNirCmd as NirCmd # Core Imports from bph.core.server.template import BphTemplateServer as TemplateServer from bph.core.session import BphSession as Session session = Session(project_name='blackhat_arsenal_2019') session.start() templateserver = Templat...
nilq/baby-python
python
from sudachipy import dictionary from sudachipy import tokenizer from sudachipy.plugin import oov from kuro2sudachi.normalizer import SudachiCharNormalizer import jaconv import fileinput import argparse import json import os import re mode = tokenizer.Tokenizer.SplitMode.C parser = argparse.ArgumentParser( descr...
nilq/baby-python
python
############################################################################### # # Copyright (c) 2018, Henrique Morimitsu, # # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions o...
nilq/baby-python
python
#!/usr/bin/env python from setuptools import setup, find_packages setup(name='dynamicmultithreadedexecutor', version='1.0.2', description='Dynamic Multi-threaded Executor', author='Kevin McCabe', author_email='csmp@hotmail.com', url='https://github.com/gumpcraca/dynamicmultithreadedexecu...
nilq/baby-python
python
def EscreverArquivoRelatorio(tabelaDados, somaMegaBytes, dadosMedio): '''Função para escrever o relatorio final do problema''' arquivo_final = open('relatório.txt', 'w') arquivo_final.write('ACME Inc. Uso do espaço em disco pelos usuários') arquivo_final.write('\n') arquivo_final.write('-' * 70) a...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo.tests.common import TransactionCase class TestPointOfSale(TransactionCase): def setUp(self): super(TestPointOfSale, self).setUp() # ignore pre-existing pricelists for the purpose of this ...
nilq/baby-python
python
class TensorflowModelWrapper: def __init__(self): self._model = None def set_model(self, model): self._model = model def forward(self, input_): return self._model.predict(input_) def __call__(self, *args, **kwargs): return self._model.predict(*args, **kwargs)
nilq/baby-python
python
""" Partial Entropy Decomposition with the Hcs measure from Ince (2017) https://arxiv.org/abs/1702.01591 """ from __future__ import division import numpy as np from itertools import combinations from .pid import BasePID from .lattice import pid_lattice from .. import modify_outcomes from ..algorithms import maxent...
nilq/baby-python
python
from unittest import TestCase import numpy as np from pyfibre.tests.probe_classes.utilities import generate_probe_graph from pyfibre.tests.dummy_classes import DummyGraphSegment from pyfibre.tests.probe_classes.objects import ProbeGraphSegment class TestBaseGraphSegment(TestCase): def setUp(self): sel...
nilq/baby-python
python
"""Hack route cipher sent by Abraham Lincoln.""" from itertools import combinations from src.ch03.c1_anagram_generator import split def get_factors(integer: int) -> list: """Get factors of integer. Calculate factors of a given integer. Args: integer (int): Number to get factors of. Returns:...
nilq/baby-python
python
from django.core.files.storage import FileSystemStorage class MediaStorage(FileSystemStorage): pass class ZarrStorage(FileSystemStorage): pass class FilesStorage(FileSystemStorage): pass class LocalStorage(): media = MediaStorage zarr = ZarrStorage files = FilesStorage
nilq/baby-python
python
from django.urls import path, include from . import views app_name = 'blog' urlpatterns = [ path('', views.Home.as_view()), path('posts/', include([ path('create/', views.CriarPost.as_view(), name='criar-post'), path('<slug:titulo>/', views.VerPost.as_view(), name="ver-post"), ])), p...
nilq/baby-python
python
import keras import keras.backend as K from keras.preprocessing import sequence from keras.datasets import imdb from keras.models import Sequential, Model from keras.layers import \ Dense, Activation, Conv2D, MaxPool2D, Dropout, Flatten, Input, Reshape, LSTM, Embedding, RepeatVector,\ TimeDistributed, Bidirect...
nilq/baby-python
python
import asyncio import ffmpeg # Reason: Following export method in __init__.py from Effective Python 2nd Edition item 85 from asynccpu import ProcessTaskPoolExecutor # type: ignore # Reason: Following export method in __init__.py from Effective Python 2nd Edition item 85 from asyncffmpeg import FFmpegCoroutineFactor...
nilq/baby-python
python
import argparse import csv import inspect import os import re import warnings from abc import ABCMeta, abstractmethod from contextlib import contextmanager from pathlib import Path from time import time import pandas as pd warnings.filterwarnings("ignore") REPO = Path(__file__).resolve().parents[2] @contextmanager...
nilq/baby-python
python
# -*- coding: utf8 -*- from ..core.Oracle import Oracle from ..utils.ColorString import ColorString from ..utils.utils import * from .Config import Config import argparse import re import os def install_jdk(): Oracle.install_jdk() def uninstall_jdk(): Oracle.execute_uninstall_jdk() def rsync_server_core_data...
nilq/baby-python
python
import unittest import numpy as np from nptest import nptest class Test_ShapeBaseTests(unittest.TestCase): def test_atleast_1d(self): a = np.atleast_1d(1.0) print(a) print("**************") x = np.arange(9.0).reshape(3,3) b = np.atleast_1d(x) print(b) pri...
nilq/baby-python
python
import os from behave import * from copy import deepcopy from lxml import etree import tempfile import uuid import logging from pds_doi_service.core.entities.exceptions import InputFormatException, CriticalDOIException from pds_doi_service.core.util.doi_xml_differ import DOIDiffer from pds_doi_service.core.actions.d...
nilq/baby-python
python
#!/usr/bin/python # Copyright 2018 Blade M. Doyle # 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 ag...
nilq/baby-python
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jul 5 19:05:19 2018 @author: myoussef """ import ringity import unittest import numpy as np import networkx as nx class TestConversions(unittest.TestCase): def test_ddict2dict2ddict_unweighted(self): E = nx.erdos_renyi_graph(100,0.17) ...
nilq/baby-python
python
ballresponse = [ 'Yes', 'No', 'Take a wild guess...', 'Very doubtful', 'Sure', 'Without a doubt', 'Most likely', 'Might be possible', "You'll be the judge", 'no... (╯°□°)╯︵ ┻━┻', 'no... baka', 'senpai, pls no ;-;' ] owos = [ "✪w✪", "¤w¤", "∅w∅", "⊗w⊗", "⊕w⊕", "∞w∞", "∆w∆", "θwθ", "δwδ", "①w①", "②w②", "③w③"...
nilq/baby-python
python
import unicodedata from collections import defaultdict from itertools import zip_longest from .porter import Stemmer def _normalize(s): return unicodedata.normalize("NFKD", s) def _check_type(s): if not isinstance(s, str): raise TypeError("expected str or unicode, got %s" % type(s).__name__) def l...
nilq/baby-python
python
#!/usr/bin/python def findstem(arr): # Determine size of the array n = len(arr) # Take first word from array # as reference s = arr[0] l = len(s) res = "" for i in range(l): for j in range(i + 1, l + 1): # generating all possible substrings # of our ...
nilq/baby-python
python
#!/usr/bin/env python # -*- coding: utf-8 -*- ####################################################################################### # The MIT License # Copyright (c) 2014 Hannes Schulz, University of Bonn <schulz@ais.uni-bonn.de> # Copyright (c) 2013 Benedikt Waldvogel, University of Bonn <mail@bwaldvog...
nilq/baby-python
python
#!/usr/bin/env python # vim: set fileencoding=utf-8 : # -*- coding: utf-8 -*- # # Last modified: Tue, 23 Jan 2018 23:39:11 +0900 # # try import libsbml try: from libsbml import ASTNode from libsbml import AST_PLUS from libsbml import AST_MINUS from libsbml import AST_TIMES from libsbml import formul...
nilq/baby-python
python
import threading import Pyro4 class NameServerInThread(threading.Thread): def __init__(self): super(NameServerInThread, self).__init__() self.name_server_daemon = None @staticmethod def is_name_server_started(): try: ns = Pyro4.locateNS() return True ...
nilq/baby-python
python
''' Wrapper for bert embeddings ''' import numpy as np import torch from pytorch_pretrained_bert import BertTokenizer, BertModel class BertEmbeddings: def __init__(self, model_name='bert-base-uncased', cache_dir=None, max_seq_length=64, max_batch_size=64, stats_count=False): ''' :param normalize:...
nilq/baby-python
python
"""Copyright 2014 Google 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 by applicable law or agreed to in ...
nilq/baby-python
python
from django.contrib import admin from .models import ChatUser admin.site.register(ChatUser)
nilq/baby-python
python
from config import * from dbMgr import * @app.before_request def clear_trailing(): rp = request.path if rp != '/' and rp.endswith('/'): return redirect(rp[:-1]) @app.route('/test') def default(): return render_template('login.html') @app.before_request def before(): logging.info("IP addr...
nilq/baby-python
python
import doctest import pytest if __name__ == "__main__": doctest.testmod() pytest.main()
nilq/baby-python
python
"Iterative Solvers for Sparse Linear Systems" #from info import __doc__ from .iterative import * from .minres import minres from .lgmres import lgmres from .lsqr import lsqr from .lsmr import lsmr from ._gcrotmk import gcrotmk from .tfqmr import tfqmr __all__ = [ 'bicg', 'bicgstab', 'cg', 'cgs', 'gcrotmk', 'gmres...
nilq/baby-python
python
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # 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 ...
nilq/baby-python
python
"""Tests for reloading generated pyi.""" from pytype import utils from pytype.pytd import pytd from pytype.tests import test_inference class ReingestTest(test_inference.InferenceTest): """Tests for reloading the pyi we generate.""" def testContainer(self): ty = self.Infer(""" class Container: ...
nilq/baby-python
python
import time import numpy as np from pycqed.analysis import analysis_toolbox as a_tools import pycqed.analysis_v2.base_analysis as ba # import dataprep for tomography module # import tomography module # using the data prep module of analysis V2 # from pycqed.analysis_v2 import tomography_dataprep as dataprep from pycqed...
nilq/baby-python
python
from sys import modules from unittest.mock import MagicMock mock_sys_info = modules["pitop.common.sys_info"] = MagicMock() mock_sys_info.is_pi = MagicMock(return_value=False) mock_curr_session_info = modules["pitop.common.current_session_info"] = MagicMock() mock_curr_session_info.get_first_display = MagicMock(return...
nilq/baby-python
python
import os import boto3 AWS_ENDPOINT_URL = os.getenv("AWS_ENDPOINT_URL", None) def handler(event, context): client = boto3.client("s3", endpoint_url=AWS_ENDPOINT_URL) client.create_bucket(Bucket="foo") client.create_bucket(Bucket="bar") buckets = client.list_buckets()["Buckets"] l = [] for buck...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2017-05-17 15:31 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0004_auto_20170509_1559'), ('pfb_analysis', '0025_auto_20170511_1244'), ...
nilq/baby-python
python
from rest_framework.exceptions import APIException from rest_framework import status class InvalidParameterException(APIException): """Exception for invalid request parameters.""" status_code = status.HTTP_400_BAD_REQUEST default_detail = 'Request contained an invalid parameter' default_code = 'invali...
nilq/baby-python
python
import arff import argparse import json import logging import openmlcontrib import openmldefaults import os import sklearnbot def parse_args(): metadata_file = '/home/janvanrijn/experiments/sklearn-bot/results/results__500__svc__predictive_accuracy.arff' parser = argparse.ArgumentParser(description='Creates a...
nilq/baby-python
python
""" This module executes the string matching between a input sequence T and an pattern P using a Finite State Machine. The complexity for building the transition function is O(m^3 x |A|) where A is the alphabet. Since the string matching function scan the input sequence only once, the total complexity is O(n + m^3 x |A...
nilq/baby-python
python
import tkinter window = tkinter.Tk() window.title("Test") top_frame = tkinter.Frame(window).pack() bottom_frame = tkinter.Frame(window).pack(side="bottom") # label = tkinter.Label(window, text="Hello, world!").pack() btn1 = tkinter.Button(top_frame, text="B1", fg="red").pack() btn2 = tkinter.Button(top_frame, text="...
nilq/baby-python
python
from setuptools import setup, Extension with open('README.md', 'r') as f: long_description = f.read() meow_ext = Extension( 'meowhash.cpython', # define_macros=[('MEOW_HASH_256', '0'), ('MEOW_HASH_512', '0')], sources=['meowhash/cpython.c'], extra_compile_args=['-mavx512f', '-mavx512vl', '-maes', ...
nilq/baby-python
python
# Copyright The IETF Trust 2007-2019, All Rights Reserved # from django.contrib.sitemaps import GenericSitemap from ietf.ipr.models import IprDisclosureBase # changefreq is "never except when it gets updated or withdrawn" # so skip giving one queryset = IprDisclosureBase.objects.filter(state__in=('posted','removed'))...
nilq/baby-python
python
from grpclib.exceptions import GRPCError from insanic.exceptions import APIException from interstellar.exceptions import InvalidArgumentError from grpc_test_monkey_v1.monkey_grpc import ApeServiceBase, MonkeyServiceBase from grpc_test_monkey_v1.monkey_pb2 import ApeResponse, MonkeyResponse class PlanetOfTheApes(Ap...
nilq/baby-python
python
#!/usr/bin/env python # Copyright (c) 2005-2011 Grameen Foundation USA # 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....
nilq/baby-python
python
def vatCal(totalPrice): result = totalPrice + (totalPrice*7/100) return result TotalPrice = int(input("Put your price : ")) print("Your total price is",vatCal(TotalPrice))
nilq/baby-python
python
import angr from angr.sim_type import SimTypeInt ###################################### # getchar ###################################### class getchar(angr.SimProcedure): def run(self): self.return_type = SimTypeInt(32, True) data = self.inline_call( # TODO: use a less private ge...
nilq/baby-python
python
#!/usr/bin/env python import sys sys.path.insert(0, '..') import glob import numpy as np from dotmap import DotMap from simpleplotlib import plot from parse_logs import parse_hdfs_logs, parse_hdfs_throughput bytes_units = 2.0**-30 types = ['HDFS+static', 'HDFS+resize', 'HDFS+reTCP', 'reHDFS+static', 'reHDF...
nilq/baby-python
python
''' Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. NVIDIA CORPORATION and its licensors retain all intellectual property and proprietary rights in and to this software, related documentation and any modifications thereto. Any use, reproduction, disclosure or distribution of this software and related docu...
nilq/baby-python
python
import numpy as np from sklearn.neural_network import MLPClassifier from sklearn.metrics import precision_recall_curve from sklearn.metrics import average_precision_score from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix import matplotlib.pyplot as plt import datetime from keras im...
nilq/baby-python
python
from setuptools import setup version = '1.0.2' setup( name='django-mobi2', version=version, keywords='Django UserAgent', description='Django middleware and view decorator to detect phones and small-screen devices', long_description=open('README').read(), url='https://github.com/django-xxx/dj...
nilq/baby-python
python
import pickle from tqdm import tqdm import numpy as np def save_stereotypes(animate_file, text_file, out_file): """ Save list of words that are stereotyped towards men or women :param animate_file: list of noun pairs :param text_file: file to test words counts on :param out_file: output file "...
nilq/baby-python
python
nome = str(input('Digite o nome: ')).strip() caps = nome.upper() truefalse = 'SILVA' in caps print('Há SILVA no nome?\n', truefalse)
nilq/baby-python
python
# %% import numpy as np from scipy import spatial x, y = np.mgrid[0:4, 0:4] points = np.c_[x.ravel(), y.ravel()] tree = spatial.cKDTree(points) tree.query_ball_point([2, 0], 1) tree.query_ball_point(points, 1) # %% tree.query_ball_tree(points, 1)
nilq/baby-python
python
# This is a log file. It is saved as .py so that the following notebooks can easily import it and use its information. # started at: 2022.03.03-15:28:15
nilq/baby-python
python
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. import logging import os import sys import pyauto_functional # Must come before pyauto (and thus, policy_base). import policy_base sys.path.append('/u...
nilq/baby-python
python
"""Unit test for the data_tuils module.""" import pytest import candle @pytest.mark.skip(reason="used by load_Xy_data_noheader") def test_to_categorical(): pass @pytest.mark.skip(reason="used by load_Xy_data2") def test_convert_to_class(): pass @pytest.mark.skip(reason="used by impute_and_scale_array") ...
nilq/baby-python
python
import numpy as np import scipy.optimize as so import cv2 from . import cfilter, cresampler, clz4, report from .struct import * _LZ4_COMPRESSION_LEVEL = 9 def applyBestIntraCompression(img, dropThreshold, minRetSize, fastDecodeMode = 2): h, w, nChannel = img.shape def _addEx(filterModeList, baseMeth...
nilq/baby-python
python
import math import numpy as np from datetime import datetime startTime = datetime.now() natural = range(1, 500000) # Get list of prime numbers def prime_list(max_prime): primes = range(2, max_prime) length = len(primes) for idx in range(len(primes)): p = primes[idx] if p == 0: ...
nilq/baby-python
python
# http://codeforces.com/contest/268/problem/C n, m = map(int, input().split()) d = min(n, m) print(d + 1) for i in range(d + 1): print("{} {}".format(d-i, i))
nilq/baby-python
python
import numpy as np from swarm import metrics import pytest # Example y with 11 points from -1.5 to 1.5. y = np.array( [ -0.997495, -0.9320391, -0.78332686, -0.5646425, -0.29552022, 0.0, 0.29552022, 0.5646425, 0.78332686, 0.9320391, ...
nilq/baby-python
python
import numpy as np from numpy.random import uniform from veneer.pest_runtime import * import pyapprox as pya from scipy.stats import uniform from functools import partial from pyapprox.adaptive_sparse_grid import max_level_admissibility_function from pyapprox.adaptive_polynomial_chaos import variance_pce_refinement_in...
nilq/baby-python
python
# Copyright © 2019 Province of British Columbia # # 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 agr...
nilq/baby-python
python
#!/usr/bin/env python3 #fileencoding: utf-8 #-----------------------------------------------# # python standard library #-----------------------------------------------# import calendar import csv from enum import Enum from datetime import datetime as dt #-----------------------------------------------# # pip #------...
nilq/baby-python
python
#!/usr/bin/env python # coding: utf-8 from collections import namedtuple class IDBase(str): _attrs = ( # ('server_id', 0, 12, ServerID), # ('_non_attr', 12, 13, validator), # ('mountpoint_index', 13, 16, MountPointIndex), # ('port', 13, 16, _port), ) _str_len = 0 _t...
nilq/baby-python
python
""" Test execution of at and cron style scheduler policies when group has updates """ from test_repo.autoscale.fixtures import AutoscaleFixture from time import sleep class UpdateSchedulerScalingPolicy(AutoscaleFixture): """ Verify update scheduler policy """ @classmethod def setUpClass(cls): ...
nilq/baby-python
python
# coding: utf-8 """ CardPay REST API Welcome to the CardPay REST API. The CardPay API uses HTTP verbs and a [REST](https://en.wikipedia.org/wiki/Representational_state_transfer) resources endpoint structure (see more info about REST). Request and response payloads are formatted as JSON. Merchant uses API to c...
nilq/baby-python
python
import numpy as np ## Wan-Ting borrow this function from io from stmpy folder. def _make_attr(self, attr, names, data): ''' Trys to give object an attribute from self.data by looking through each key in names. It will add only the fist match, so the order of names dictates the preferences. Input...
nilq/baby-python
python
#!/usr/bin/env python3 # Author: Ali Assaf <ali.assaf.mail@gmail.com> # Copyright: (C) 2010 Ali Assaf # License: GNU General Public License <http://www.gnu.org/licenses/> from itertools import product def solve_sudoku(size, grid): """ An efficient Sudoku solver using Algorithm X. >>> grid = [ ... [5...
nilq/baby-python
python
import unittest from game_classes import Card class TestCard(unittest.TestCase): def test_init(self): test_card = Card() self.assertEqual(test_card.counter, 0) self.assertEqual(len(test_card.selected_numbers), 15) self.assertEqual(len(test_card.card), 3) def test_print_card(se...
nilq/baby-python
python
# An empty class has a dictionary that ... # holds the attributes of the object. class A(object): pass A = A() A.__dict__ = { 'key11': 1, 'key2': 2, } A.__dict__['key2'] = 3 print(A.__dict__['key2']) # 3
nilq/baby-python
python
qtde = int(input('Qual a Qtde: ')) valor = float(input('Qual valor unitário desse produto: ')) preco_total = qtde * valor print('O preço total é: {}'.format(preco_total))
nilq/baby-python
python
"""Application settings.""" import os import pydantic class Settings(pydantic.BaseSettings): """Main application config. It takes settings from environment variables. """ sqlalchemy_uri: str = os.environ['SQLALCHEMY_URI'] import_token: str = os.environ['AUTH_IMPORT_TOKEN']
nilq/baby-python
python
import math import requests from typing import Tuple, List AUTH_KEY = 'GOOGLE API KEY' PI = math.pi LatLng = Tuple[float, float] Polygon = List[LatLng] """ Various mathematical formulas for use in Google's isLocationOnEdge and containsLocation algorithms. Unless otherwise specified all math utilities have be...
nilq/baby-python
python
# -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: streamlit/proto/DeckGlJsonChart.proto from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symb...
nilq/baby-python
python
import os def skip_if_environ(name): if name in os.environ: def skip_inner(func): return lambda x: None return skip_inner def inner(func): return func return inner
nilq/baby-python
python
from selenium import webdriver import pandas as pd import time import os # load product file product = pd.read_csv('../dataset/glowpick_products.csv') # urls product_urls = product.product_url.unique() url = 'https://www.glowpick.com' # driver driver = webdriver.Chrome() # information dataframe in...
nilq/baby-python
python
import os import sys PROJECT_DIR = os.path.dirname(os.path.abspath(__file__)) BASE_DIR = os.path.dirname(PROJECT_DIR) sys.path.append(os.path.dirname(BASE_DIR)) SECRET_KEY = '@$n=(b+ih211@e02_kup2i26e)o4ovt6ureh@xbkfz!&@b(hh*' DEBUG = True ALLOWED_HOSTS = [] DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' INSTA...
nilq/baby-python
python
from django import forms from .models import AddressEntry class AddressEntryForm(forms.ModelForm): class Meta: model = AddressEntry fields = [ 'address', ]
nilq/baby-python
python
""" Lines 5 and 6 were adapted from SO code: http://stackoverflow.com/questions/4383571/importing-files-from-different-folder-in-python """ import sys sys.path.insert(0, '..') """ END """ import main as program import pytest def test_int_0(): assert '0' == program._get_binary(0,1) def test_int_5(): assert '...
nilq/baby-python
python
from enum import Enum, auto class DatabaseActionType(Enum): WRITE_DATA_STORAGE = auto() # Writes do not require a response on the request WRITE_STORAGE_INDEX = auto() READ_CONNECTED_DEVICES = auto() # Reads need response to get requested data READ_DEVICE = auto() # RPC CALL DELETE_OLD_DATA = auto()
nilq/baby-python
python
import os import imp import setuptools version = imp.load_source("ssh2.version", os.path.join("ssh2", "version.py")).version setuptools.setup( name="python-ssh", version=version, packages=setuptools.find_packages(include=["ssh2", "ssh2.*"]), package_dir={"ssh2": "ssh2"}, license="MIT", autho...
nilq/baby-python
python
#!/usr/bin/env python3 """Demo on how to run the simulation using the Gym environment This demo creates a SimRearrangeDiceEnv environment and runs one episode using a dummy policy. """ from rrc_example_package import rearrange_dice_env from rrc_example_package.example import PointAtDieGoalPositionsPolicy def main():...
nilq/baby-python
python
#!/usr/bin/python3 # # Copyright (c) 2019-2021 Ruben Perez Hidalgo (rubenperez038 at gmail dot com) # # Distributed under the Boost Software License, Version 1.0. (See accompanying # file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) # import requests from bs4 import BeautifulSoup import os from os ...
nilq/baby-python
python
""" Copyright 2016 Stephen Boyd, Enzo Busseti, Steven Diamond, BlackRock 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 appl...
nilq/baby-python
python
# Generated by Django 3.2.1 on 2021-05-09 13:39 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Customer', fields=[ ('id', models.BigAutoFi...
nilq/baby-python
python
from .BaseNeuralBatch import BaseNeuralBatch from ..nu import v1 from .. import Ports import numpy as np class CubicBatch(BaseNeuralBatch): def __init__( self, name, parent, cell_pos, shape, unit_distance, nu_type=v1, ...
nilq/baby-python
python
from datetime import datetime import discord from discord.ext import commands class cat_debug(commands.Cog, name="Debug commands"): """Documentation""" def __init__(self, bot): self.bot = bot @commands.command() async def tell_me_about_yourself(self, ctx): print( f"[{dat...
nilq/baby-python
python
'''This module computes ''' import argparse import csv import io import os.path from datetime import datetime from urllib.request import urlopen from stockjournal.operator import gmean csv_header = "Date,Open,High,Low,Close,Volume,Adj Close" parser = argparse.ArgumentParser(description='Stock stats tool using data \...
nilq/baby-python
python
# Author: Smit Patel # Date: 25/07/2018 # File: chatbot_trainer.py # Licence: MIT from chatterbot import ChatBot from chatterbot.trainers import ListTrainer import os bot = ChatBot('Bot') bot.set_trainer(ListTrainer) while True: message = input('You:') if message.strip() !=...
nilq/baby-python
python
#!/usr/bin/python3 # ''' ### Desafio de request de url ### Extrair o nono e o quarto campos do arquivo CSV sobre região de influencia das Cidades Ignorar a primeira linha que é o cabechalho do arquivo dados = entrada.read().decode('latin1') Arquivo IBGE esta no formato ISO-8859-1 (aka latin1) Essa linha baixa o arqui...
nilq/baby-python
python
class TennisGame(): def __init__(self, first_player_name="player1", second_player_name="player2"): self.first_player_name = first_player_name self.second_player_name = second_player_name self.first_player_score = 0 self.second_player_score = 0 @property def first_player_sco...
nilq/baby-python
python
# @Time : 2020/11/14 # @Author : Gaole He # @Email : hegaole@ruc.edu.cn # UPDATE: # @Time : 2020/12/3 # @Author : Tianyi Tang # @Email : steventang@ruc.edu.cn # UPDATE # @Time : 2021/4/12 # @Author : Lai Xu # @Email : tsui_lai@163.com """ textbox.evaluator.bleu_evaluator ####################################...
nilq/baby-python
python