content stringlengths 0 1.05M | origin stringclasses 2
values | type stringclasses 2
values |
|---|---|---|
import os
import sys
import time
import gc
import copy
import random
import numpy as np
import pandas as pd
import torch.optim as optim
import torch.nn.functional as F
import torch.nn as nn
from torch.autograd import Variable
from image_util import *
from data_util import *
from env import *
from sum_tree import *
im... | nilq/baby-python | python |
from py_queryable import Model
from py_queryable import Column, PrimaryKey, ForeignKey
class StubModel(Model):
__table_name__ = u'test_table'
test_int_column = Column(int, 'int_column')
class StubModel2(Model):
__table_name__ = u'test_table'
test_int_column = Column(int)
class StubPrimary(Model):
... | nilq/baby-python | python |
from mmcv.utils import Registry,build_from_cfg
TRANSFORMER = Registry('Transformer')
POSITIONAL_ENCODING = Registry('Position encoding')
def build_transformer(cfg,default_args=None):
"""Builder for Transfomer."""
return build_from_cfg(cfg,TRANSFORMER,default_args)
def build_positional_encoding(cfg,default_ar... | nilq/baby-python | python |
from sports.nba.nba_team import NBA_Team
class HoustonRockets(NBA_Team):
"""
NBA Golden State Warriors Static Information
"""
full_name = "Houston Rockets"
name = "Rockets"
team_id = 1610612745
def __init__(self):
"""
"""
super().__init__()
| nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2019-02-17 09:46
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0043_backend_filteredlanguage'),
]
operations = [
migrations.AddFi... | nilq/baby-python | python |
import sys
import secrets
from toolbox._common import PlaybookRun
class OCMAddon:
"""
Commands for managing OCM addons
"""
@staticmethod
def install(ocm_refresh_token, ocm_cluster_id, ocm_url, ocm_addon_id, wait_for_ready_state=False):
"""
Installs an OCM addon
Args:
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-03-31 08:21
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('first_app', '0005_inventory'),
]
operations = [
... | nilq/baby-python | python |
import random
from shop import db
from shop.models import Menu, Computers
class Computer:
computers = 1
def __init__(self):
self.name = "Model: MacBook {}".format(self.computers)
self.price = random.randint(20000, 30000)
self.currency = '₽'
self.disk_size = "Disk size:{} Gb".f... | nilq/baby-python | python |
import math
from collections import OrderedDict
from typing import Optional, Dict, List, Union
import numpy
import shapely.geometry
from OpenGL.GL import GL_RGB8
from pyrr import Vector3
from rasterio import features
from rasterio import transform
from rasterstats import zonal_stats
from shapely.geometry import Polygo... | nilq/baby-python | python |
# Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved.
from gevent import monkey; monkey.patch_all()
from nose.tools import assert_raises
import mock
from . import scheduler as _
from config import config_value
from job import Job
from digits.utils import subclass, override
class TestScheduler():
... | nilq/baby-python | python |
from pathlib import Path
from flask_wtf import FlaskForm
from wtforms import SelectMultipleField, SubmitField
from wtforms.validators import DataRequired
path = Path(".")
forecast = sorted(path.glob("data/forecast_*.json"), reverse=True)
choices = [(p, p) for p in forecast]
class YearSelectForm(FlaskForm):
year ... | nilq/baby-python | python |
"""
1. Clarification
2. Possible solutions
- Brute force
- HashMap
3. Coding
4. Tests
"""
# T=O(n^2), S=O(1)
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
if len(nums) < 2: return [-1, -1]
for i in range(len(nums)):
for j in range(i + 1, len(nums)... | nilq/baby-python | python |
import enum
from typing import Dict
class PropertyType(enum.Enum):
HOUSE = 0
FLAT = 1
BUNGALOW = 2
class BuiltForm(enum.Enum):
MID_TERRACE = 0
SEMI_DETACHED = 1
DETACHED = 2
END_TERRACE = 3
class OccupantType(enum.Enum):
OWNER_OCCUPIED = 0
RENTED_PRIVATE = 1
RENTED_SOCIAL =... | nilq/baby-python | python |
import pdb
import logging
import numpy as np
import sys
sys.path.append('..')
import MRATools as mt
def determine_radius(k, h):
if k==0:
raise ValueError("Ensemble size must be stricly positive")
s = np.floor(np.sqrt(k))
if s % 2==0:
sf = s-1
else:
sf = s
if k==sf**2... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""Code for creating diagrams."""
| nilq/baby-python | python |
from .confirmationwindow import ConfirmationWindow
from .menu import Menu
from .popupwindow import PopupWindow
from .scrollselector import ScrollSelector
from .filemenu import FileMenu
__all__ = ["PopupWindow","ScrollSelector",
"ConfirmationWindow","Menu",
"FileMenu"]
| nilq/baby-python | python |
from typing import Optional
import torch
from anndata import AnnData
from scvi.model import SCVI
use_gpu = torch.cuda.is_available()
def unsupervised_training_one_epoch(
adata: AnnData,
run_setup_anndata: bool = True,
batch_key: Optional[str] = None,
labels_key: Optional[str] = None,
):
if run_... | nilq/baby-python | python |
from jmanager.utils.print_utils import get_progress_text
PROGRESS_TEXT = "test |========================= | 50.0%"
class TestPrintUtils:
def test_get_progress_text(self):
assert get_progress_text(msg="test", iteration=1, total=2) == PROGRESS_TEXT
| nilq/baby-python | python |
import numpy as np
def get_pieces_count(state):
count = 0
for s in state:
if s.isalpha():
count += 1
return count
def is_kill_move(state_prev, state_next):
return get_pieces_count(state_prev) - get_pieces_count(state_next)
def create_position_labels():
labels_array = []
l... | nilq/baby-python | python |
import numpy as np
import theano
import theano.tensor as T
import util
def vanilla(params, gradients, opts):
return [(param, param - opts.learning_rate * gradient)
for param, gradient in zip(params, gradients)]
def momentum(params, gradients, opts):
assert opts.momentum >= 0.0 and opts.momentum <... | nilq/baby-python | python |
distancia = float(input('Qual é a distancia da sua viagem?' ))
print('voce esta prestes a começa uma viagem de {}km.'.format(distancia))
preço = distancia * 0.50 if distancia <= 200 else distancia * 0.45
print('É o preço da sua passagem sera de R${:2f}'.format(preço))
opcao4 = ''
while opcao4!= 'S' and opcao4 != 'N':
... | nilq/baby-python | python |
# ### 1.5 function that post process the ccs results
import numpy as np
import pandas as pd
# define a function that could calculate the overall annual emission and lock emission
def bau_ccs_post (df):
coal_annual_existing_emission = df.loc[:,('coal_power_annual_emission_existing')].values
coal_annual_n... | nilq/baby-python | python |
from bokeh.models import HoverTool, ColumnDataSource
from bokeh.plotting import figure, output_file, show
from bokeh.models.markers import marker_types
import bokeh.layouts
import datetime
import numpy as np
import DownloadData
age, year_week, data = DownloadData.incidence()
np_data = np.array(data)
np_data[np_data ... | nilq/baby-python | python |
#!/usr/bin/env python
#
# Copyright 2014 Hewlett-Packard Development Company, L.P.
#
# 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... | nilq/baby-python | python |
#!/usr/bin/env python3
"""
Author : Ken Youens-Clark <kyclark@gmail.com>
Date : 2020-11-11
Purpose: Find patterns in files
"""
import argparse
import re
from typing import List, NamedTuple, TextIO
class Args(NamedTuple):
""" Command-line arguments """
pattern_file: TextIO
search_files: List[TextIO]
... | nilq/baby-python | python |
#!/usr/bin/env python3
from __future__ import division, absolute_import, print_function, unicode_literals
import subprocess
import re
import time
import sys
import argparse
import yaml
from timeparse import timeparse
def call(args):
return '\n'.join(subprocess.check_output(args).decode().splitlines())
def get_a... | nilq/baby-python | python |
from durabledict.base import DurableDict
from durabledict.encoding import NoOpEncoding
class MemoryDict(DurableDict):
'''
Does not actually persist any data to a persistant storage. Instead, keeps
everything in memory. This is really only useful for use in tests
'''
def __init__(self, autosync... | nilq/baby-python | python |
# Copyright (c) The InferLO authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 - see LICENSE.
import random
from copy import copy
from functools import reduce
from typing import List, Optional
import numpy as np
from .factor import Factor, product_over_
from .graphical_model impo... | nilq/baby-python | python |
import itertools
from collections import defaultdict, OrderedDict, Counter, namedtuple, deque
# defaultdict can define default_factory where
# accessing a key which does not exist, creates it with a default value
# and the default value is returned
# commonly used to append to lists in dictionaries
dd1 = defaultdict... | nilq/baby-python | python |
#!/usr/bin/python3
from evdev import InputDevice, categorize, ecodes
import configparser, os
config = configparser.ConfigParser()
config.read(os.path.dirname(os.path.realpath(__file__))+'/config.ini')
def sysrun(command):
os.system(command+ " &")
dev = InputDevice(config["DEVICE"]["path"])
dev.grab()
for event in d... | nilq/baby-python | python |
from .colored import (
info,
error,
fatal
)
from .get_env_var import get_env_var
from .sync_to_async import sync_to_async
__ALL__ = (
'info',
'error',
'fatal',
'get_env_var',
'sync_to_async'
)
| nilq/baby-python | python |
from .doc import AssemblyDocCommand
from .helpers import instruction_set
from .helpers import support_set
from .completion import completionListener
from .context import ContextManager
__all__ = ["AssemblyDocCommand", "instruction_set","support_set", "completionListener", "ContextManager"]
| nilq/baby-python | python |
#!/usr/bin/python
# Filename: ex_for.py
for i in range(0, 5):
print("{0}: hello".format(i))
print('The for loop is over')
| nilq/baby-python | python |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# ============================================================================
# Erfr - One-time pad encryption tool
# Extractor script
# Copyright (C) 2018 by Ralf Kilian
# Distributed under the MIT License (https://opensource.org/licenses/MIT)
#
# Website: http://www.ur... | nilq/baby-python | python |
import logging
g_logger = None
def get_logger():
return g_logger
def configure_logging(name: str, level: int = logging.DEBUG):
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=level)
global g_logger
g_logger = logging.getLogger(name=name)
g_logger.debug(... | nilq/baby-python | python |
import numpy as np
import torch
import torch.nn.functional as F
from PIL import Image
from scipy import linalg
import torchvision
from torchvision import datasets, transforms
from Tools import FLAGS
def get_dataset(train, subset):
transf = transforms.Compose(
[transforms.ToTensor(), transforms.Normaliz... | nilq/baby-python | python |
from collections.abc import Container
class MyContainer(Container):
def __init__(self, value):
self.data = value
def __contains__(self, value):
return value in self.data
| nilq/baby-python | python |
# names, grades, attributes, sentences
names = ['Tom', 'Fred', 'Harry', 'Hermione', 'Ron', 'Sarah', 'Ele', 'Mike', 'Peter']
subjects = ['Maths','Science','English', 'Arts', 'Music', 'German', 'French', 'PE']
grade_adjective = {
1: ['terrible', 'horrible'],
2: ['below average', 'mediocre'],
3: ['Average', 'A... | nilq/baby-python | python |
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from oauth2_provider.decorators import protected_resource
import json
from datetime import datetime
from django.utils import timezone
from sqlshare_rest.util.db import get_backend
from sqlshare_rest.models import Dataset, User, Qu... | nilq/baby-python | python |
# Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sys import argv
import bottle
from bottle import default_app, request, route, response, get
from pymongo import MongoClient
import json
import api
bottle.debug(True)
def enable_cors(fn):
def _enable_cors(*args, **kwargs):
# set CORS headers
resp... | nilq/baby-python | python |
class Pelicula:
# Constructor de clase
def __init__(self, titulo, duracion, lanzamiento):
self.titulo = titulo
self.duracion = duracion
self.lanzamiento = lanzamiento
print("Se ha creado la pelicula", self.titulo)
# Redefinimos el metodo String
def __str__(self):
... | nilq/baby-python | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from random import randint
import time,sys
braille = ['⣽','⢿','⣻','⡿','⣾','⣟','⣯','⣷']
z = len(braille)
for x in range(10):
r = (randint(0,z-1))
sys.stdout.write("Working " + braille[r] + " " + str(x*10) + "% done" )
sys.stdout.flush()
time.sleep(1)
sys.stdout.write("... | nilq/baby-python | python |
# Generated by Django 3.0.4 on 2020-03-30 20:18
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('base', '0002_auto_20200330_1310'),
]
operations = [
migrations.RenameField(
model_name='product',
old_name='descrtiption',
... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Title : 字符串工具类
@File : string_utils.py
@Author : vincent
@Time : 2020/9/15 11:14 上午
@Version : 1.0
'''
import os
def is_null(obj):
if obj is None:
return True
if len(obj) == 0:
return True
def list_2_str(str_list):
r_str = '... | nilq/baby-python | python |
# Generated by Django 2.2.10 on 2020-02-27 14:37
from django.db import migrations, models
def nullify_courserun_expiration_dates(apps, schema_editor):
"""
Unset all of the expiration dates set automatically by the previous code.
We are moving to empty expiration dates by default and only explicitly setti... | nilq/baby-python | python |
# Generated by Django 3.0.4 on 2020-03-11 21:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kegs', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='beer',
name='description',
fie... | nilq/baby-python | python |
# Generated by Django 3.1.14 on 2022-03-24 11:25
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('feedback', '0030_auto_20220324_0947'),
]
operations = [
migrations.AddField(
model_name='report',
name='eid',
... | nilq/baby-python | python |
from http import HTTPStatus
from django.urls import resolve, reverse
from mock import patch
from barriers.views.public_barriers import PublicBarrierDetail
from core.tests import MarketAccessTestCase
class PublicBarrierViewTestCase(MarketAccessTestCase):
def test_public_barrier_url_resolves_to_correct_view(self)... | nilq/baby-python | python |
from __future__ import absolute_import
from __future__ import unicode_literals
import multiprocessing
import os
import sys
import mock
import pytest
import pre_commit.constants as C
from pre_commit.languages import helpers
from pre_commit.prefix import Prefix
from pre_commit.util import CalledProcessError
from testi... | nilq/baby-python | python |
import requests
import os
import shutil
from constants import chromedriverPath
# Constants
chromedriverUrl = 'https://chromedriver.storage.googleapis.com/89.0.4389.23/chromedriver_win32.zip'
chromedriverFile = 'chromedriver.zip'
def downloadFile(url, name):
r = requests.get(url, allow_redirects=True)
... | nilq/baby-python | python |
import turtle
###################################################
# range = antal gange
# rigth or left = grader til højre eller venstre
# forward or backward = længde på streg + retning fremad/tilbage
# kan man tegne flere samtidig? hvordan
###################################################
<<<<<<< HEAD
for n in ran... | nilq/baby-python | python |
# __init__.py
from cogs.add import add
from cogs.add import add_all
from cogs.apply import apply
from cogs.clear import clear
from cogs.connect import connect
from cogs.delete import delete
from cogs.diff import diff
from cogs.fetch import fetch
from cogs.ignore import ignore
from cogs.init import init
from cogs.ls imp... | nilq/baby-python | python |
class ActivationFrame():
def __init__(self, owner):
self.owner = owner
self.static_link = None
self.dynamic_link = None
self.params = []
self.local_vars = []
self.static_vars = []
self.external_vars = []
self.temp_vars = []
self.previous_PC = ... | nilq/baby-python | python |
#4. Crie um código em Python que receba uma lista de nomes informados pelo usuário com tamanho indefinido (a lista deve ser encerrada quando o usuário digitar 0) e, na sequência, receba um nome para que seja verificado se este consta na lista ou não. Observação: ignorar diferenças entre maiúsculas e minúsculas.
nomes =... | nilq/baby-python | python |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("BSC Indicator"),
"items": [
{
"type": "doctype",
"name": "BSC Initiative Log",
"description":_("BSC Initiative Log"),
"onboard": 1,
"dependencies": ["BSC Initiative"],
},
{
... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
空白模板
"""
###### 欢迎使用脚本任务,首先让我们熟悉脚本任务的一些使用规则 ######
# 详细教程请在AI Studio文档(https://ai.baidu.com/ai-doc/AISTUDIO/Ik3e3g4lt)中进行查看.
# 脚本任务使用流程:
# 1.编写代码/上传本地代码文件
# 2.调整数据集路径以及输出文件路径
# 3.填写启动命令和备注
# 4.提交任务选择运行方式(单机单卡/单机四卡/双机四卡)
# 5.项目详情页查看任务进度及日志
# 注意事项:
# 1.输出结果的体积上限为20GB,超过上限可能导致下载输出失败.
# 2.脚本任务... | nilq/baby-python | python |
# Generated by Django 2.1.7 on 2019-06-03 05:56
import datetime
from django.db import migrations, models
from django.utils.timezone import utc
class Migration(migrations.Migration):
dependencies = [
('blog', '0015_auto_20190601_2202'),
]
operations = [
migrations.AlterField(
... | nilq/baby-python | python |
from flask_babel import lazy_gettext as _
from .model import (
Session,
CirculationEvent,
ExternalIntegration,
get_one,
create
)
class LocalAnalyticsProvider(object):
NAME = _("Local Analytics")
DESCRIPTION = _("Store analytics events in the 'circulationevents' database table.")
# A g... | nilq/baby-python | python |
import shutil, ssl, json
import requests, zipfile, gzip, io
import pandas as pd
from tbsdq import utilities as dqutils
from tbsdq import configuration as dqconfig
from topN import configuration as topnconfig
""" Non-Spatial dataset analysis on the open data registry """
def fetch_and_parse_catalogue(zip_url, expecte... | nilq/baby-python | python |
from django.contrib.auth.models import Permission
class TestPermissionsMixin:
def _clean_permissions(self):
self.user.user_permissions.clear()
self._clean_perm_cache()
def _set_permissions(self, perms):
self.user.user_permissions.add(
*Permission.objects.filter(codename__... | nilq/baby-python | python |
# -*- coding: utf-8 -*-
"""
github3.repos.commit
====================
This module contains the RepoCommit class alone
"""
from __future__ import unicode_literals
from . import status
from .. import git, models, users
from .comment import RepoComment
class RepoCommit(models.BaseCommit):
"""The :class:`RepoCommi... | nilq/baby-python | python |
from pymusicterm.util.time import milliseconds_to_minutes, milliseconds_to_seconds
from py_cui.widgets import Widget
class LoadingBarWidget(Widget):
BAR_COMPLETED_CHAR=u'\u2588'
def __init__(self,id,title,grid,row,column,row_span,column_span,padx,pady,logger) -> None:
""" Initializer for Loading... | nilq/baby-python | python |
import json
from typing import List, Dict, Union
import bleach
allowed_items = {
"section", "subsection", "link"
}
allowed_sub_items = {
"title",
"url",
"metadata",
"desc",
"commentary"
}
def clean_submission(upload_post: str) -> List[Union[str, Dict[str, str]]]:
output = []
for reso... | nilq/baby-python | python |
import psycopg2 as pg
from psycopg2.extras import DictCursor
from getpass import getpass
##############
# Connecting #
##############
cx = pg.connect(
host='localhost', database='abq',
user=input('Username: '),
password=getpass('Password: '),
cursor_factory=DictCursor
)
cur = cx.cursor()
##################... | nilq/baby-python | python |
def train(model, link_predictor, emb, edge_index, pos_train_edge, batch_size, optimizer):
"""
Runs offline training for model, link_predictor and node embeddings given the message
edges and supervision edges.
1. Updates node embeddings given the edge index (i.e. the message passing edges)
2. Compute... | nilq/baby-python | python |
from .base import TemplateView
class Index(TemplateView):
template_name = 'feats/index.html'
| nilq/baby-python | python |
from github import GitHub
username = "github_username"
db_path_account = "C:/GitHub.Accounts.sqlite3"
db_path_api = "C:/GitHub.Apis.sqlite3"
g = GitHub.GitHub(db_path_account, db_path_api, username)
g.repo.create('repository_name', description='this is repository description.', homepage='http://homepage.com')
| nilq/baby-python | python |
#!/usr/bin/env python2.7
import argparse
import sys
import rospy
import tf
from gazebo_msgs.srv import GetLinkState, GetLinkStateRequest
parser = argparse.ArgumentParser()
parser.add_argument("object_name", help="Name of the object")
parser.add_argument("link_name", help="Link of the object")
parser.add_argument("wor... | nilq/baby-python | python |
import json
from datetime import date
from unittest.mock import MagicMock, patch
from django.contrib.auth import get_user_model
from django.core.management import call_command
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APIClient
f... | nilq/baby-python | python |
from flask import Flask, request, Response
import json
import numpy as np
import gpt_gen
import gpt_gen_thread
import sys
import time
import logging
import torch
from Config import config_predict
from datetime import datetime
ConfigPredict = config_predict()
batchGenerating=ConfigPredict.batchGenerating
path_configs = ... | nilq/baby-python | python |
import pickle
class Carro:
def __init__(self, modelo, cor):
self.modelo = modelo
self.cor = cor
def __repr__(self):
return f'Carro(modelo="{self.modelo}", cor="{self.cor}")'
carro_1 = Carro('Celta', 'Prata')
data = {
'a': 'Eduardo',
'b': 'Banans',
'c': [1, 2, 3, 4],
... | nilq/baby-python | python |
"""
1579. Remove Max Number of Edges to Keep Graph Fully Traversable
Hard
Alice and Bob have an undirected graph of n nodes and 3 types of edges:
Type 1: Can be traversed by Alice only.
Type 2: Can be traversed by Bob only.
Type 3: Can by traversed by both Alice and Bob.
Given an array edges where edges[i] = [typei, ... | nilq/baby-python | python |
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(here, 'README.rst')) as f:
README = f.read()
requires = [
'cornice',
'gevent',
'pyramid_exclog',
'setuptools',
'couchdb',
'couchapp',
'pycrypto',
'openpro... | nilq/baby-python | python |
from rest_framework import serializers
from backend.models import Shortener
# Lead Serializer
class ShortenerSerializer(serializers.ModelSerializer):
class Meta:
model = Shortener
fields = '__all__'
read_only_fields = ['id', 'responseURL', 'date']
| nilq/baby-python | python |
"""For entities that have specs."""
from gemd.entity.has_dependencies import HasDependencies
from gemd.entity.object.has_template import HasTemplate
from gemd.entity.template.base_template import BaseTemplate
from gemd.entity.link_by_uid import LinkByUID
from abc import abstractmethod
from typing import Optional, Unio... | nilq/baby-python | python |
from otree.api import Currency as c, currency_range
from . import pages
from ._builtin import Bot
from .models import Constants
import csv
class PlayerBot(Bot):
def play_round(self):
with open('trial_set_FR.csv', newline='', encoding='cp1252') as csvfile:
csv_reader = csv... | nilq/baby-python | python |
###########DO NOT DELETE#########################
#cat /proc/sys/vm/overcommit_memory
#echo 1 | sudo tee /proc/sys/vm/overcommit_memory
#################################################
from tifffile import imsave
import numpy as np
import cv2
import os
import datetime
from PIL import Image
norm = np.zeros((480,848... | nilq/baby-python | python |
from . import executor
from . import phone
from . import snoopphone | nilq/baby-python | python |
"""Added ml_models table
Revision ID: 7e60a33f42bb
Revises: 11aa784195ef
Create Date: 2021-04-16 02:25:10.719706
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "7e60a33f42bb"
down_revision = "11aa784195ef"
branch_labels = None
depends_on = None
def upgrade()... | nilq/baby-python | python |
import os, sys
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'
test_dir = os.path.dirname(__file__)
sys.path.insert(0, test_dir)
from django.test.simple import run_tests as django_test_runner
from django.conf import settings
def runtests():
failures = django_test_runner(['localedb'], verbosity=1, interactive=Tr... | nilq/baby-python | python |
# Working with Date And Time.
import datetime
from datetime import date
# Get today's date from the date class.
today = date.today()
print ("Today's date is ", today)
myDate = datetime.date(2018,6,9)
print(myDate)
print(myDate.year)
print(myDate.month)
print(myDate.day)
#Day-name,Month-name,Day-name,Year
pr... | nilq/baby-python | python |
#!/usr/bin/env python
"""
Merges global.yml and config.yml to create various local.yml for each room assistant peer node. It then
sends the configuration file to peer, and restarts the room assistant service.
See README.md file for details.
"""
import math
import os
import time
import yaml
def mergeDicts(dict1, dict... | nilq/baby-python | python |
n,t=map(int,input().split())
x=[]
mp=10**6
for i in range(n):
x.append([*map(int,input().split())])
mp=min(mp,x[i][1])
left,right=-mp,10**7
while abs(left-right)>=0.00000001:
mid=(left+right)/2
hour=0
for i in x:
hour+=i[0]/(i[1]+mid)
if hour>=t: left=mid
else: right=mid
print(left) | nilq/baby-python | python |
from django.apps import AppConfig
class StudentportalConfig(AppConfig):
name = 'studentportal'
| nilq/baby-python | python |
import os
import qrcode
from ckeditor.fields import RichTextField
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.exceptions import ValidationError
from django.db import models
from mptt.models import MPTTModel, TreeForeignKey
from . import constants
User = get_user_m... | nilq/baby-python | python |
import numpy as np
from tools.metadata import get_hero_dict
import operator
import pandas as pd
import plotly.graph_objs as go
import plotly.plotly as py
def winrate_statistics(dataset_df, mmr_info):
x_data, y_data = dataset_df
wins = np.zeros(114)
games = np.zeros(114)
winrate = np.zeros(114)
... | nilq/baby-python | python |
# First, lets get a list of all files in the data directory
import time
import sys
from tensorflow import keras
import tensorflow as tf
import pathlib
import json
from tensorflow.keras.callbacks import TensorBoard, ModelCheckpoint
from tensorflow.keras.layers import Conv3D, MaxPooling3D, BatchNormalization, GlobalAv... | nilq/baby-python | python |
from Gaussiandistribution import Gaussian
gaussian_one = Gaussian(22, 2)
print(gaussian_one.mean) | nilq/baby-python | python |
from math import floor
def find_position(value):
position = floor(value / 100)
if value % 100 == 0:
position = position - 1
return position
def center_of_square(coordinate, dimension):
return coordinate + dimension / 2
| nilq/baby-python | python |
#
# Script to do an Oracle restore given an optional date range of the copy
# An existing restore job is required, copy version of that job will be updated if applicable
# If no date range is provided the latest copy will be used
# Backup job name for the copy to use can also be provided
# Set the cancel parameter = tr... | nilq/baby-python | python |
# Copyright 2019 The Bazel Authors. 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 la... | nilq/baby-python | python |
def create_app():
from flask import Flask
from localtalk.views import init_views
app = Flask(__name__)
# init views
init_views(app)
return app
def create_server():
from localtalk.server import Server
server = Server()
return server
| nilq/baby-python | python |
import asyncio
from datetime import datetime
import logging
import aiohttp
import requests
import certifi
TIMEOUT_FOR_PAR_REQS = 60*5
TIMEOUT_FOR_SEQ_REQS = 60
Logger = logging.getLogger(__name__)
class InvalidClientResponse:
def __init__(self):
self.status = None
async def fetch(uri, session, body=F... | nilq/baby-python | python |
from django.db import models
from covid_data.models.base import ModeloBase
class Sector(ModeloBase):
"""Identifica el tipo de institución del Sistema Nacional de Salud
que brindó la atención.
"""
clave = models.IntegerField(unique=True)
descripcion = models.CharField(max_length=63)
def __repr... | nilq/baby-python | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.response.AlipayResponse import AlipayResponse
class AlipayUserStepcounterQueryResponse(AlipayResponse):
def __init__(self):
super(AlipayUserStepcounterQueryResponse, self).__init__()
self._count = None
... | nilq/baby-python | python |
#!/usr/bin/env python
import sys, os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import messagebird
# ACCESS_KEY = ''
# PHONE_NUMBER = ''
try:
ACCESS_KEY
except NameError:
print('You need to set an ACCESS_KEY constant in this file')
sys.exit(1)
try:
PHONE_NUMBER
except NameError:
print... | nilq/baby-python | python |
while 0 < 1:
mec = input("Valor da Medardoria: ")
icns = float(mec) * 17/100
irpf = float(mec) * 15/100
csll = float(mec) * 7.6/100
cofins = float(mec) * 3/100
pis = float(mec) * 1.65/100
me = float(mec) - (icns + irpf + cofins + pis + csll)
print("<<<<<<<<<<<RESLTADO>>>>>>>>>>"... | nilq/baby-python | python |
from ._fastfood import Fastfood
__all__ = ['Fastfood']
| nilq/baby-python | python |
from django.shortcuts import render,redirect
from django.http import HttpResponse
from django.conf import *
from .models import User
import json
# Create your views here.
def login(request):
return render(request,'account/login.html')
def dologin(request):
username=request.POST['username']
pwd=request.... | nilq/baby-python | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.