id int64 0 10k | text stringlengths 186 4k | length int64 128 1.02k |
|---|---|---|
100 | import os
import kerinou.views
from flask import Flask
app = Flask(__name__)
app.config.from_object('kerinou.default_settings')
app.config.from_envvar('KERINOU_SETTINGS')
if not app.debug:
import logging
from logging.handlers import TimedRotatingFileHandler
# https://docs.python.org/3.6/library/logging.ha... | 256 |
101 | from flask import Flask
from .view_classes import BasicView
from nose.tools import eq_
app = Flask("common")
app.config["SERVER_NAME"] = "test.test"
BasicView.register(app, subdomain="basic")
client = app.test_client()
def test_index_subdomain():
resp = client.get("/basic/", base_url="http://basic.test.test")
... | 1,000 |
102 | import os
def check_env(env_var_name):
"""
Check and return the type of an environment variable.
supported types:
None
Integer
String
@param env_var_name: environment variable name
@return: string of the type name.
"""
try:
val = os.getenv(env_var_name)
... | 233 |
103 | # coding: utf-8
from collections import defaultdict
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def findMode(self, root):
"""
:type root: TreeNode
:... | 551 |
104 | import Const
import RunClassCommon
OPT900P_costs = [0.0593, 0.0653, 0.0584, 0.0659, 0.0076, 0.0117, 0.0076, 0.0287]
OPTMem_costs = [0.1001, 0.4416, 0.0997, 0.4429, 0.0057, 0.0093, 0.0060, 0.0177]
experiment_list = [
{
'Experiment': Const.EXT_CP,
'Setup': 'Intel900P_ECP_ClusterAbs_LeadAbs_Scan',
... | 401 |
105 | import typing
from . import app
from quart import request
from ujson import dumps
from flask_babel import get_locale
from .models import TranslationUnits
@app.template_filter("get_unit")
def _get_unit_filter(unit):
return app.translations.get_unit(request.locale, unit)
@app.template_filter("format")
def _format... | 496 |
106 | import ttarray.raw as raw
from .. import random_array,check_raw_ttslice_dense,calc_chi,DENSE_SHAPE
import numpy.linalg as la
import pytest
import copy
import itertools
# SHAPE_RECLUSTER=[
# ((2,3),[((),),((),(),()),((),())]),
# ((2,24,3),[((24,),),((1,),(24,)),((3,),(4,),(2,)),((2,),(2,),(2,),(3,)),((24,),(1,),(1,)),(... | 733 |
107 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 29 08:48:46 2020
@author: lukas and martina
"""
####
# This script imports the literature from Zotero. All items with the tag "*****" are called (see readme).
# Afterwards the literature information is saved in JSON format for later use
####
# Use ... | 303 |
108 | # -*- coding: utf-8 -*-
"""
Microsoft-Windows-MCCS-EngineShared
GUID : bf460fc6-45c5-4119-add3-e361a6e7d5ac
"""
from construct import Int8sl, Int8ul, Int16ul, Int16sl, Int32sl, Int32ul, Int64sl, Int64ul, Bytes, Double, Float32l, Struct
from etl.utils import WString, CString, SystemTime, Guid
from etl.dtyp import Sid
fr... | 531 |
109 | from rest_framework import serializers
from sakila.models import Film
from sakila.models_views import CustomerList
class FilmSerializer(serializers.ModelSerializer):
class Meta:
model = Film
fields = '__all__'
# fields = ('title', 'description', 'release_year', 'language', 'original_langu... | 167 |
110 | # 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 ... | 520 |
111 | import neuroglancer
import numpy as np
import sys
import tifffile
import h5py
# RUN SCRIPT: python3 -i visualng.py
# General settings
ip = 'localhost' # or public IP of the machine for sharable display
port = 13333 # change to an unused port number
neuroglancer.set_server_bind_address(bind_address=ip, bind_por... | 724 |
112 | import _plotly_utils.basevalidators
class TicktextsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self,
plotly_name='ticktextsrc',
parent_name='scatter3d.marker.colorbar',
**kwargs
):
super(TicktextsrcValidator, self).__init__(
plotly... | 250 |
113 | #=========================================================================
# Python wrapper to create a power curve for a particular design
#=========================================================================
#=========================================================================
# Import modules
#==... | 678 |
114 | import _plotly_utils.basevalidators
class XanchorValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(self, plotly_name="xanchor", parent_name="layout.image", **kwargs):
super(XanchorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... | 239 |
115 | # Program to transpose a matrix using a nested loop
X = [[12, 7],
[4, 5],
[3, 8]]
result = [[0, 0, 0],
[0, 0, 0]]
# iterate through rows
for i in range(len(X)):
# iterate through columns
for j in range(len(X[0])):
result[j][i] = X[i][j]
for r in result:
print(r)
| 140 |
116 | # -*- coding: utf-8 -*-
import os
from flask import Flask, request, jsonify
import FaceProcessing
from faces import save_embedding
# Initialize the Flask application
app = Flask(__name__)
# route http posts to this method
BASEDIR = os.getenv('RUNTIME_BASEDIR',os.path.abspath(os.path.dirname(__file__)))
@app.route('/ap... | 326 |
117 | #Desafio 012 -> Faça um algoritmo que leia o preço de um produto
# e mostre seu novo preço,com 5% de desconto
preco = float(input('Quanto custa o produto?'))
desconto = preco / 20
pdesconto = preco - desconto
print('Com um desconto de 5%, o novo valor do produto passa a ser R${}'.format(pdesconto))
#Outr... | 190 |
118 | # Copyright (c) 2012 OpenStack Foundation.
#
# 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... | 530 |
119 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2012-2019 SoftBank Robotics. All rights reserved.
# Use of this source code is governed by a BSD-style license (see the COPYING file).
""" Test QiSrc Grep """
from __future__ import absolute_import
from __future__ import unicode_literals
from __future__ impo... | 773 |
120 | def polishNotation(exp: list):
# Este algoritmo resuelve expresiones matemáticas en notación polaca inversa
# La expresión matemática se ingresa en un arreglo
# Se utiliza una pila para la solución de las operaciones hasta completarlas todas
# Retorna la solución de la operación enviada
stack = []
for i in... | 633 |
121 | import time
from sqlalchemy import BIGINT, BOOLEAN, INT, Column, String, Table
from sqlalchemy.sql.expression import select
from mayday.db.tables import BaseModel
from mayday.objects.user import User
class UsersModel(BaseModel):
def __init__(self, engine, metadata, role='reader'):
table = Table(
... | 956 |
122 | # -*- coding: utf-8 -*-
import os
import shutil
import unittest
import optparse
import anadama2.document
class TestPweaveDocument(unittest.TestCase):
def test_filter_zero_rows(self):
doc = anadama2.document.PweaveDocument()
names=["s1","s2","s3"]
data=[[0,0,1],[0,0,0],[1,0,0]]
f... | 986 |
123 | # Copyright 2013-2015 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "LICENSE.txt" file ... | 745 |
124 | """
This is a collection of tags and filters for :class:`~integreat_cms.cms.models.push_notifications.push_notification.PushNotification`
objects.
"""
from django import template
register = template.Library()
@register.simple_tag
def get_translation(push_notification, language_slug):
"""
This tag returns the... | 264 |
125 | import base64
from django.contrib.auth.models import AnonymousUser
from django.conf import settings
from django.utils.crypto import constant_time_compare
from rest_framework import authentication
from rest_framework import exceptions
class SettingsAuthentication(authentication.BaseAuthentication):
def authenticate... | 400 |
126 | import gc
import torch
from .utils import *
# === Import model-related objects ===
from comvex.coatnet import CoAtNetConfig, CoAtNetWithLinearClassifier
# === Instantiate your Model ===
# - For specializations
specializations = [attr for attr in dir(CoAtNetConfig) if attr.startswith("CoAtNet")]
specializations = spec... | 815 |
127 | import logging
import controller
def main():
logging.info("Running example")
formated_input = controller.format_input("hello")
proccessed_data = controller.procces_data(formated_input)
formatted_output = controller.format_output(proccessed_data)
logging.info("Done and done")
if __name__ == "__ma... | 172 |
128 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
from django.http import QueryDict
from django.utils.encoding import smart_str
class UnpjaxMiddleware(object):
"""
Removes the `_pjax` parameter from query string
"""
def process_request(self, ... | 273 |
129 | # -*- coding: utf-8 -*-
# *******************************************************
# ____ _ _
# / ___|___ _ __ ___ ___| |_ _ __ ___ | |
# | | / _ \| '_ ` _ \ / _ \ __| | '_ ` _ \| |
# | |__| (_) | | | | | | __/ |_ _| | | | | | |
# \____\___/|_| |_| |_|\___|\__(_)_| |_| |_|_|... | 237 |
130 | import os
import yaml
import argparse
from datetime import datetime
import torch
import random
import metaworld
from garage.experiment.deterministic import set_seed
from src.env import make_env
from src.algorithm import SAC
from src.agent import Agent
def run(args):
set_seed(args.seed)
with open(args.config)... | 853 |
131 | #### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_durgur_pyne.iff"
result.attribute_template_id = 9
res... | 155 |
132 | import plotly.plotly as py
from plotly.graph_objs import *
from datetime import datetime
import src.lib.debug as debug
import paho.mqtt.client as mqtt
stream1 = Stream(
token='8bwbzgze6l',
maxpoints=50000,
)
stream2 = Stream(
token='d2gchv6j41',
maxpoints=50000,
)
trace1 = Scatter(
x=[],
y=[],
stream... | 997 |
133 | """
WSGI config for StoreApp project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "StoreApp.settings")
from django.core... | 129 |
134 | # TODO: Copy all of your 03-Colors.py program and put it below this comment.
# TODO One way to do so is:
# TODO 1. Inside 03-Colors.py, do:
# TODO -- Control-A (to SELECT the entire contents of the file, then
# TODO -- Control-C (to COPY that entire selection)
# TODO 2. Inside thi... | 233 |
135 | from sklearn import svm
import numpy as np
import time
start_time = time.time()
X_train = []
Y_train = []
X_test = []
Y_test = []
#reading non violent video features
for i in range(1,130):
try:
file_name = 'violent_features_NON_VIOLENT/nonvio_'+str(i)+'.txt'
file_obj = open(file_name,'r')
vi... | 804 |
136 | # Copyright (C) 2018-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
from openvino.tools.mo.ops.cumsum import CumSum
from openvino.tools.mo.front.extractor import FrontExtractorOp
from openvino.tools.mo.front.onnx.extractors.utils import onnx_attr
class CumSumFrontExtractor(FrontExtractorOp):
op = '... | 238 |
137 | # std
import logging
from typing import List, Optional
# project
from . import LogHandler
from ..parsers.block_parser import BlockParser
from .condition_checkers import BlockConditionChecker
from .condition_checkers.found_blocks import FoundBlocks
from .daily_stats.stats_manager import StatsManager
from src.notifier i... | 556 |
138 | # Pyrogram - Telegram MTProto API Client Library for Python
# Copyright (C) 2017-2021 Dan <https://github.com/delivrance>
#
# This file is part of Pyrogram.
#
# Pyrogram is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free... | 797 |
139 | #!/usr/bin/env python
import angr
import claripy
base_address = 0x00100000
success_address = 0x0010111d
failure_address = 0x00101100
flag_length = 15
project = angr.Project("./a.out",main_opts = {"base_addr":base_address})
flag_chars = [ claripy.BVS(f"flag_char{i}",8) for i in range(flag_length) ]
flag = claripy.Co... | 358 |
140 | import pytest
import selenium.webdriver
import json
@pytest.fixture(scope='function')
def config():
with open('config.json') as config_file:
config = json.load(config_file)
assert config['browser'] in ['Firefox', 'Chrome', 'Headless Chrome']
assert isinstance(config['implicit_wait'], int)
as... | 365 |
141 | import napari
import numpy as np
im_data = np.zeros((50, 50, 50))
im_data[30:40, 25:35, 25:35] = 1
viewer = napari.view_image(im_data, colormap='magenta', rendering='iso')
viewer.add_image(im_data, colormap='green', rendering='iso', translate=(30, 0, 0))
points_data = [
[50, 30, 30],
[25, 30, 30],
[75, 30... | 180 |
142 | # main.py -- Chapter 4 - Test Harness Example
##################################################################################
# Title : Test Harness Example
# Filename : main.py
# Author : JWB
# Origin Date : 01/07/2019
# Version : 1.0.0
#... | 640 |
143 | # mysite/routing.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import speaker.routing
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
speaker.routing.webs... | 130 |
144 | '''
Created by auto_sdk on 2015.08.26
'''
from top.api.base import RestApi
class OpenAccountCreateRequest(RestApi):
def __init__(self,domain='gw.api.taobao.com',port=80):
RestApi.__init__(self,domain, port)
self.param_list = None
def getapiname(self):
return 'taobao.open.account.create'
| 131 |
145 | from typing import List
from qcodes import Instrument
from qcodes.utils import validators
import numpy as np
import time
class DummyChannel(Instrument):
def __init__(self, name: str, *args, **kwargs):
super().__init__(name, *args, **kwargs)
self.add_parameter('ch0',
set... | 952 |
146 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-04-10 18:13
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('IoT_MaintOps', '0009_auto_20180410_1041'),
]
oper... | 439 |
147 | """
Elabore um programa que calcule o valor a ser pago por um produto,
considerando o seu preço normal e condição de pagamento:
À vista dinheiro/cheque: 10% de desconto
Á vista no cartão: 5% de desconto
Em até 2x no cartão: preço normal
3x ou mais no cartão: 20% de juros
É só isso
... | 574 |
148 | """This module defines the `picharsso draw gradient` command.
Refer to https://kelvindecosta.github.io/picharsso/commands/draw/gradient/.
"""
import click
from ...draw import new_drawer
from ...draw.gradient import DEFAULT_CHARSET
@click.command("gradient", options_metavar="[options]")
@click.option(
"-s",
... | 284 |
149 | """A WebSocket handler for Treadmill state.
"""
import os
import logging
import yaml
from treadmill import schema
_LOGGER = logging.getLogger(__name__)
class IdentityGroupAPI(object):
"""Handler for /identity-groups topic."""
def __init__(self):
"""init"""
@schema.schema({'$ref': 'websoc... | 672 |
150 | #!/usr/bin/env python
import os,sys
spec = 'VODUpload.podspec'
if len(sys.argv) == 0:
print('please input version')
else:
version = sys.argv[1]
with open(spec) as f:
lines = f.readlines()
for i in range(len(lines)):
if lines[i].find('s.version =') != -1:
... | 405 |
151 | valores = []
while True:
valores.append(int(input("Digite um valor: ").strip()))
while True:
resposta = str(input("\nDeseja continuar? "
"Digite [S]im ou [N]ão.\nSua resposta: ").strip().upper()[0])
if resposta != 'S' and resposta != 'N':
print("\nRespost... | 507 |
152 | from xml.dom import minidom
from xml.sax.saxutils import unescape
import os
import click
@click.command()
@click.argument('source')
@click.argument('destination')
@click.option('--blend_func', '-b', required=False, type=str, default='mean',
help="Mathematical function to be used for blending overlapping... | 1,013 |
153 | # Copyright 2020 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... | 600 |
154 | #!/usr/bin/env python
# Copyright (c) 2017, United States Government, as represented by the
# Administrator of the National Aeronautics and Space Administration.
#
# All rights reserved.
#
# The Astrobee platform is licensed under the Apache License, Version 2.0
# (the "License"); you may not use this file except in co... | 900 |
155 | # Copyright (C) 2021-2022 Intel Corporation
# SPDX-License-Identifier: Apache-2.0
#
import pytest
from ote_sdk.configuration.default_model_parameters import DefaultModelParameters
from ote_sdk.tests.constants.ote_sdk_components import OteSdkComponent
from ote_sdk.tests.constants.requirements import Requirements
@py... | 457 |
156 | import importlib
import pytest
from docs_src.tutorial.fastapi.app_testing.tutorial001 import main as app_mod
from docs_src.tutorial.fastapi.app_testing.tutorial001 import test_main_002 as test_mod
@pytest.fixture(name="prepare", autouse=True)
def prepare_fixture(clear_sqlmodel):
# Trigger side effects of regist... | 175 |
157 | #!/usr/bin/env python
# -*- coding: latin-1 -*-
#
# see http://docs.python.org/dist/dist.html
#
"""
Copyright (c) 2009 John Markus Bjoerndalen <jmb@cs.uit.no>,
Brian Vinter <vinter@diku.dk>, Rune M. Friborg <runef@diku.dk>.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this sof... | 725 |
158 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import yaml
class ConfYaml(object):
def __init__(self, confname):
with open('./etc/imagescraper.default.conf.yaml', 'r') as stream:
try:
self.__default_data = yaml.load(stream, Loader=yaml.FullLoader)
except yaml.YAMLEr... | 686 |
159 | # Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import numpy as np
from tvm import te
import logging
import sys, time, subprocess
import json
import os
def schedule(attrs):
cfg, s, output = attrs.auto_config, attrs.scheduler, attrs.outputs[0]
th_vals, rd_vals = [attrs.get_extent(x) for x... | 335 |
160 | import os
from .base import *
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
| 150 |
161 | import numpy as np
from hmf.cosmology import growth_factor
from astropy.cosmology import Planck13
import pytest
@pytest.fixture(scope="module")
def gf():
return growth_factor.GrowthFactor(Planck13)
@pytest.fixture(scope="module")
def genf():
return growth_factor.GenMFGrowth(Planck13, zmax=10.0)
@pytest.ma... | 802 |
162 | import hashlib
def get_md5_hash():
_api_key = '00000000-0000-0000-0000-000000000000'
_secret = '1234567890ABCDEF'
_routing_id = '1464524676'
routing_key_data = str(_api_key) + str(_routing_id) + str(_secret)
digest_string = hashlib.md5(routing_key_data.encode('utf-8')).hexdigest()
print("Dige... | 166 |
163 | #!/usr/bin/env python3
import configparser
import logging
import os
import pathlib
from daisho.client import daisho_cli
from daisho.helpers import daisho_help
from daisho.server import daisho_db
HOME = os.getenv("HOME")
DAISHO_HOME = HOME + "/.config/daisho/"
CONFIG = DAISHO_HOME + "daisho.conf"
HISTORY = DAISHO_HOM... | 622 |
164 | #!/usr/bin/env python
import sys
import os
from ccg import *
TRANSFORM = sys.argv[1]
transform = trans.__dict__[TRANSFORM]
FILTER = ''
if len(sys.argv) == 3:
FILTER = sys.argv[2]
if FILTER in ['dev', 'train', 'test']:
FILTER = bank.__dict__[FILTER]
for deriv in bank.visit(transform, bank.iter('../data/CCGb... | 149 |
165 | #!/usr/bin/env python
# coding: utf-8
# Copyright (c) Vidar Tonaas Fauske
# Distributed under the terms of the Modified BSD License.
def _jupyter_nbextension_paths():
return [{
'section': 'notebook',
'src': 'nbextension/static',
'dest': 'jupyter-combobox',
'require': 'jupyter-combo... | 155 |
166 | # -------------------------------------------------------------------
# Copyright 2021 Virtex 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.... | 170 |
167 | from leia import SentimentIntensityAnalyzer
import re
class AcessoPLN(object):
def __init__(self):
self.leia = SentimentIntensityAnalyzer()
def sentiment_analysis(self, text):
leia_score = self.leia.polarity_scores(text)
if leia_score['compound'] >= 0.05:
result = True
... | 779 |
168 | from django_tex.environment import environment
def latex_safe(value):
"""
Filter that replace latex forbidden character by safe character
"""
return str(value).replace('_', '\_').replace('$', '\$').replace('&', '\&').replace('#', '\#').replace('{', '\{').replace('}','\}')
def my_environment(**options... | 157 |
169 | import logging
logging.basicConfig(level=logging.INFO,
format=u'%(filename)s [LINE:%(lineno)d] #%(levelname)-8s [%(asctime)s] %(message)s',
handlers=[
logging.FileHandler("debug.log"),
logging.StreamHandler()
... | 219 |
170 | # Title: 줄 세우기
# Link: https://www.acmicpc.net/problem/2252
import sys
import queue
import heapq
sys.setrecursionlimit(10 ** 6)
def read_list_int():
return list(map(int, sys.stdin.readline().strip().split(' ')))
def read_single_int():
return int(sys.stdin.readline().strip())
def get_line... | 619 |
171 | # Generated by Django 3.0.12 on 2021-03-01 21:14
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('countries', '0018_auto_20210301_1447'),
]
operations = [
migrations.CreateModel(
name='BorderC... | 536 |
172 | from .AbstractReducer import AbstractReducer
import numpy as np
import warnings
from lpproj import LocalityPreservingProjection
class LPP(AbstractReducer):
def __init__(self, d: int = 2, random_state: int = 0, **kwargs):
super().__init__(d, random_state)
warnings.warn("Setting random seed does not... | 444 |
173 | # python std modules
# third party modules
from setuptools import find_packages
from setuptools import setup
long_description = """small modules and tools useful for many projects
"""
setup(name="mytb",
version="0.1.1",
description="my toolbox for everyday python projects",
long_description=long_de... | 900 |
174 | """
OBJ :
1 - Tipos de Números
2 - Funções e Operações
3 - Aritmética
4 - Operadores
-------------------------------------
1) tipos:
O python possui Vários tipos os Mais comuns são:
- int --> Números Interios, positivos ou Negativos: 1,2,-7
- float --> Números Francionários, positivos ou n... | 388 |
175 | import pytest
from . import db
from .db import database
from tagtrain import data
def test_unknown_owner(database):
with pytest.raises(data.Group.DoesNotExist):
data.by_owner.remove_group('non-existent', db.GROUP_NAME)
def test_unknown_group(database):
with pytest.raises(data.Group.DoesNotExist):
... | 260 |
176 | from .base import ErConnector, DataHelper
from .company import Company
class Contact(DataHelper):
def __init__(self, contact_id, data=None):
self.contact_id = contact_id
if not data:
# Fetch from remote
self.refresh()
else:
# Allows it to be populated ... | 558 |
177 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.13 on 2018-06-07 05:55
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_userprofile'),
]
operations = [
... | 844 |
178 | from .backend_qt import (
backend_version, SPECIAL_KEYS,
# Public API
cursord, _create_qApp, _BackendQT, TimerQT, MainWindow, FigureCanvasQT,
FigureManagerQT, ToolbarQt, NavigationToolbar2QT, SubplotToolQt,
SaveFigureQt, ConfigureSubplotsQt, SetCursorQt, RubberbandQt,
HelpQt, ToolCopyToCli... | 231 |
179 | # Generated by Django 3.0.7 on 2020-06-17 07:26
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='User',
f... | 690 |
180 | """A handler designed for use with Ignite which stores the value of some object,
possibly after applying some transformation"""
import traceback
import torch
from ignite.engine import Engine
class ObjectLogger(object):
"""A handler which grabs and stores some object, possibly with a
transformation"""
... | 513 |
181 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.14 on 2018-09-10 14:05
from __future__ import unicode_literals
from __future__ import absolute_import
from django.db import migrations
from corehq.sql_db.operations import RawSQLMigration
migrator = RawSQLMigration(('custom', 'icds_reports', 'migrations', 'sql_templa... | 173 |
182 | def userContextToApplicationContext(valueToBeChanged: '', incomingDir: str=''):
if incomingDir == 'right':
if valueToBeChanged == 'straight':
return 'right'
if valueToBeChanged == 'right':
return 'down'
if valueToBeChanged == 'left':
return 'up'
if... | 848 |
183 | # Copyright 2017, OpenCensus Authors
#
# 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 w... | 311 |
184 | import subprocess
import logging
log = logging.getLogger(__name__)
# Active window functions
def get_pname(id) -> str:
p = subprocess.Popen(["ps -o cmd= {}".format(id)], stdout=subprocess.PIPE, shell=True)
return p.communicate()[0].decode('utf-8').strip()
def get_active_application_name() -> str:
p = sub... | 563 |
185 | import os
import re
import sqlite3
from ast import parse
from configparser import SafeConfigParser
def ZData(FullFile, IniFiles):
# INI Loading
Config = None
if len(IniFiles) > 0:
print("Loading INI Settings")
Config = SafeConfigParser()
InisFound = Config.read(IniFiles)
fo... | 752 |
186 | import os
from pathlib import Path
import shutil
import subprocess
import sys
import tempfile
import pytest
testdir = Path(__file__).parent
rootdir = testdir.parent
path_16 = testdir.joinpath('utf16.txt')
path_8 = testdir.joinpath('utf8.txt')
@pytest.fixture(scope='function')
def tmp_out():
tempdir = tempfile.... | 717 |
187 | # Generated by generate_protobuf.sh.
# Contains all messages in *_pb2_grpc.py in a single module.
from .data_set_messages_pb2_grpc import *
from .data_set_service_pb2_grpc import *
from .entity_messages_pb2_grpc import *
from .entity_service_pb2_grpc import *
from .internal_entity_service_pb2_grpc import *
from .relat... | 234 |
188 | from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
import numpy as np
from keras.models import load_model
from PIL i... | 406 |
189 | from common.evaluators.classification_evaluator import ClassificationEvaluator
from common.evaluators.relevance_transfer_evaluator import RelevanceTransferEvaluator
class EvaluatorFactory(object):
"""
Get the corresponding Evaluator class for a particular dataset.
"""
evaluator_map = {
'Reuter... | 568 |
190 | # -*- coding: utf-8 -*-
'''
Support for Eix
'''
from __future__ import absolute_import
# Import salt libs
import salt.utils
def __virtual__():
'''
Only work on Gentoo systems with eix installed
'''
if __grains__['os'] == 'Gentoo' and salt.utils.which('eix'):
return 'eix'
return (False, 'T... | 706 |
191 | # Generated by Django 2.2.2 on 2019-07-30 13:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('users', '0005_user_gain_votes'),
]
operations = [
migrations.AddField(
model_name='user',
name='brithday',
... | 184 |
192 | # -*- coding: utf-8 -*-
#
# 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, software
... | 305 |
193 | #
# __init__.py
# crest-python
#
# Copyright (C) 2017 Rue Yokaze
# Distributed under the MIT License.
#
from crest.events._abstract_midi_event import AbstractMidiEvent
from crest.events._channel_pressure_event import ChannelPressureEvent
from crest.events._control_event import ControlEvent
from crest.events._ex... | 363 |
194 | from typing import TYPE_CHECKING
try:
from nextcord.ext import commands
except ModuleNotFoundError:
from disnake.ext import commands
from bot_base.wraps import Meta
if TYPE_CHECKING:
from bot_base import BotBase
class BotContext(commands.Context, Meta):
def __init__(self, *args, **kwargs):
... | 183 |
195 | """
evaluation_config_batch.py
Author: Olivier Vadiavaloo
Description:
This file implements an EvaluationConfig sub-class. In contrast to EvaluationConfigNormal,
this class keeps track of the maximum scores of batches of games played by the strategy provided
by the synthesizer and returns the average of the maximum s... | 939 |
196 | import cmath
from lark import Lark, InlineTransformer
grammar = Lark(
r"""
start : expr
?expr : sum
?sum : sum "+" mul -> add
| sum "-" mul -> sub
| mul
?mul : mul "*" pow -> mul
| mul "/" pow -> div
| pow
?pow : unary "^" pow -> pow
|... | 930 |
197 | # -*- coding: utf-8 -*-
"""
Created on Thu Apr 18 11:07:47 2019
@author: edoardottt
"""
import sqlite3
from datetime import datetime
def save(missili,bombe,nemici):
conn = sqlite3.connect('result.db')
timenow = datetime.now()
c = conn.cursor()
c.execute("INSERT INTO match... | 523 |
198 | import sys
import os
abspath = '/'.join(os.path.abspath(__file__).split('/')[:-1]) + '/'
under_abspath = '/'.join(os.path.abspath(__file__).split('/')[:-2])
sys.path.insert(0, under_abspath)
from environment import splendor
from print_board import PrintBoard
from model import Model
from copy import deepcopy
env = s... | 888 |
199 | # Generated by Django 2.2.7 on 2019-11-24 13:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0004_auto_20191123_1734'),
]
operations = [
migrations.AddField(
model_name='stock',
name='product_pic',
... | 190 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.