content stringlengths 5 1.05M |
|---|
import numpy as np
from scipy.linalg import eigvalsh
"""# Objective Functions
"""
class quadratic_function_fast:
def __init__(self, Psi, Y, alpha=0.0):
self.sizePsi, _ = Psi.shape
self.sizeY = Y.shape[0]
self.Y = Y.copy()
self.alpha = alpha
self.Psi = Psi.copy()
s... |
'''Main code with the analysis for the Methane project'''
import os
import time
import numpy as np
import pandas as pd
import scipy as sc
import matplotlib.pyplot as plt
import methfun as mf # module for this project
import methdata as md
import spectral_analysis as sa
from scipy.stats import ks_2samp
# import stats ... |
"""
Desafio 001
Problema: Crie um programa que escreva "Olá mundo" na tela.
Resolução do problema:
"""
print("Olá, Mundo!!!")
|
import msal
from settings import settings
from office365.graph_client import GraphClient
def acquire_token_msal():
"""
Acquire token via MSAL
"""
authority_url = 'https://login.microsoftonline.com/{0}'.format(settings['tenant'])
app = msal.ConfidentialClientApplication(
authority=authori... |
#!/usr/bin/python
import os
import time
import requests
import json
import uuid
import sys
from pymongo import MongoClient
def db_connect(host='localhost', port=27017):
client = MongoClient("mongodb://%s:%d" % (host, port))
return client.registry
def get_instalation_id():
db = db_connect()
if "docker... |
from pycatenary import cable
from scipy.integrate import solve_bvp
import matplotlib.pyplot as plt
import numpy as np
# Cable length [m]
L = 10
R1x = 0.2 * 5 # Horizontal force at fairlead
R1y = 7 # Vertical force at fairlead
p = 1 # Lineic weight
# Indices
i_x = 0
i_y = 1
i_T = 2
i_theta = 3
# https://docs.scipy.o... |
import datetime
def to_html(keyword_rank, now):
"""
:param keyword_rank: 메일 내용에 추가할 dataframe
:param now: 현재시각
:return: html 포맷으로 된 내용
"""
content = '<html>\n<body>\n'
content += "<h3>"+str("무신사 스토어 {} 검색어 랭킹".format(now))+"</h3>\n"
content += "<table>\n<tr>\n<th>순위</th>\n<th>키워드</th>\n... |
import random
answer = random.randint(1, 100)
print('猜数字游戏,大小范围为1~100')
counter = 0
while True:
counter += 1
number = int(input('请输入:'))
if(number > answer):
print('大了点')
elif(number < answer):
print('小了点')
else:
print('恭喜你猜对了')
break
print('你共猜了%d次' % counter)
if(co... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append("../")
import argparse
import random
import tensorflow as tf
from models.transformer import Transformer
from deeploglizer.common.preprocess import FeatureExtractor
from deeploglizer.common.dataloader import load_sessions
from deeploglizer.common... |
from .model_pgn import PGNModel
from .utils import decode_labels, inv_preprocess, prepare_label, save, load
from .ops import conv2d, max_pool, linear
from .image_reader import ImageReader
from .image_reader_pgn import ImageReaderPGN |
#!/usr/bin/env python3.7
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 30 17:37:18 2018
@author: ejreidelbach
:DESCRIPTION:
:REQUIRES:
:TODO:
"""
#==============================================================================
# Package Import
#==================================================================... |
"""
All ACM related deployment classes and functions should go here.
"""
import os
import logging
import tempfile
import shutil
import requests
from ocs_ci.framework import config
from ocs_ci.ocs import constants
from ocs_ci.ocs.exceptions import (
CommandFailed,
DRPrimaryNotFoundException,
)
from ocs_ci.ocs.... |
from panda3d.core import NodePath
from panda3d.core import Point3
from panda3d.core import LineSegs
from wecs import panda3d as wp3d
from wecs import mechanics
from wecs.aspects import Aspect
from wecs.panda3d import aspects
from mapedit.helpers import draw_grid
from mapedit import mapedit
from mapedit.cursor import c... |
from test_base import MainTestCase
from main.views import home, show_submission
from odk_viewer.views import survey_responses
from django.core.urlresolvers import reverse
from guardian.shortcuts import assign
class TestFormShowSubmission(MainTestCase):
def setUp(self):
MainTestCase.setUp(self)
sel... |
from autogluon.tabular.models.lgb.lgb_model import LGBModel
def test_lightgbm_binary(fit_helper):
fit_args = dict(
hyperparameters={LGBModel: {}},
)
dataset_name = 'adult'
fit_helper.fit_and_validate_dataset(dataset_name=dataset_name, fit_args=fit_args)
def test_lightgbm_multiclass(fit_help... |
import http.server
import socketserver
import threading
def runHttpServer(host, port, directory):
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=directory, **kwargs)
server = socketserver.TCPServer((host, port), Handler)
threading.... |
"""
Paths to Academia.edu Sections for BeautifulSoup Parsing
"""
# Professor/Author Info
PROF_NAME_PATH = ".InlineList-item"
PROF_AFFILIATION_PATH = ".Affiliation-text--affiliation"
PROF_RESEARCH_INTERESTS_PATH = ".Affiliation-text--researchInterests"
PROF_PORTRAIT_PATH = ".profile-avatar"
PROF_BIO_PATH = ".js-profile... |
from abc import ABC, abstractmethod
from banco import Banco
from cliente import Cliente
class Conta(ABC):
def __init__(self, agencia, numero_conta, saldo) -> None:
self.agencia = agencia
self.numero_conta = numero_conta
self.saldo = saldo
@abstractmethod
def sacar(self, valor):... |
from django.contrib import admin
from learning_logs.models import Topic, Entry # 导入创建的模型类
# Register your models here.
admin.site.register(Topic) # 让Django通过管理网站注册自定义创建的模型
admin.site.register(Entry) |
from __future__ import unicode_literals
import frappe
def execute():
frappe.reload_doc('stock', 'doctype', 'quality_inspection_parameter')
# get all distinct parameters from QI readigs table
reading_params = frappe.db.get_all("Quality Inspection Reading", fields=["distinct specification"])
reading_params = [d.spe... |
class Solution:
def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
"""
board =
[["E","E","E","E","E"],
["E","E","M","E","E"],
["E","E","E","E","E"],
["E","E","E","E","E"]], click = [3,0]
Output:
[["B","1"... |
#
# Copyright (c) 2018-2020 Charles Godwin <magnum@godwin.ca>
#
# SPDX-License-Identifier: BSD-3-Clause
#
import argparse
import time
import traceback
import json
from os.path import abspath
try:
from magnum import magnum
except:
import magnum
# import magnum
# from magnum import magnum, __version__
# from m... |
import sympy as sym
from mockdown.model import ViewLoader, ViewBuilder as V
class TestViewLoader:
def test_loading_ints(self) -> None:
loader = ViewLoader(number_type=sym.Integer)
view = loader.load_dict({
'name': 'root',
'rect': [0, 0, 100, 100],
'children': [... |
import pyinputplus
import datetime
start_datem = pyinputplus.inputDate(
'Start date (YYYY-MM-DD): ', formats=['%Y-%m-%d'])
end_datem = pyinputplus.inputDate(
'End date: (YYYY-MM-DD): ', formats=['%Y-%m-%d'])
start_year = start_datem.year
start_month = start_datem.month
start_day = start_datem.day
start_epoch =... |
import os
import sys
import logging
from argparse import Namespace
from dataclasses import dataclass, field
from typing import Optional
from fairseq.data.mimic3.mimic3_dataset import MIMIC3_Dataset
from fairseq.data.text_compressor import TextCompressionLevel
from fairseq.dataclass import FairseqDataclass
from fairseq... |
import json
import logging
import pickle
import random
import time
from pathlib import Path
from typing import Any, Dict, Generator, List, Optional, Tuple
import jax
import jax.numpy as jnp
import numpy as np
from jaxtalk.data import BasicDataProvider
from jaxtalk.losses import CaptionLoss
from jaxtalk.models import ... |
'''
Author: Makson Vinicio
Algoritmos de busca
'''
class Search:
def binary_seach(self, lista, element):
left, right = 0, len(lista) - 1
while left <= right:
middle = (left + right) // 2
if lista[middle] == element:
return middle
elif lista[midd... |
from __future__ import unicode_literals
import unittest
import datetime
import urlparse
import mock
from billy_client import BillyAPI
from billy_client import BillyError
from billy_client import NotFoundError
from billy_client.api import DuplicateExternalIDError
from billy_client.api import Company
from billy_client.... |
#!/usr/bin/env python
import numpy as np
import rospy
from geometry_msgs.msg import PoseStamped
from styx_msgs.msg import Lane, Waypoint
from scipy.spatial import KDTree
from std_msgs.msg import Int32
import math
'''
This node will publish waypoints from the car's current position to some `x` distance ahead.
As men... |
def binary_search(numbers, number_to_find, low, high):
if low > high:
return False
mid = int((low + high) / 2)
print(numbers[mid])
if numbers[mid] == number_to_find:
return True
elif numbers[mid] > number_to_find:
return binary_search(numbers, number_to_find, low, mid - 1)
else:
return bina... |
from __future__ import print_function
import numpy as np
from sklearn.metrics import accuracy_score
import os
import sys
import argparse
file_path = os.path.dirname(os.path.realpath(__file__))
lib_path2 = os.path.abspath(os.path.join(file_path, '..', '..', 'common'))
sys.path.append(lib_path2)
import candle
addit... |
import numpy as np
from ddm import BoundConstant, Drift, Fittable, Model, NoiseConstant
from src.models.ddms.pyddmTwoStage import TwoStagePyDDM
class TwoStageWithin(TwoStagePyDDM):
def __init__(self, dt=0.01, dx=0.01, T_dur=3, agentVars=None, label=None):
"""[summary]
Parameters
--------... |
"""
Gebauer Weibull Paraemeters
===========================
These are the tree-specific parameters of Gebauer et al. (2008) for the
4-parameter Weibull function for sap velocity distribution in the sapwood.
References
----------
Gebauer, T., Horna, V., and Leuschner, C.: Variability in radial sap flux
density patte... |
from amino import List, Map
special_codes = Map({
b'\x80\xffX': 'c-@',
b'\x80kb': 'bs',
9: 'tab',
b'\x80kB': 's-tab',
10: 'c-j',
11: 'c-k',
12: 'fe',
13: 'cr',
27: 'esc',
32: 'space',
60: 'lt',
92: 'bslash',
124: 'bar',
b'\x0b': 'c-k',
b'\x80kD': 'del',
b... |
import os
from .Base import Base
from sccloud.tools import run_de_analysis
class DeAnalysis(Base):
"""
Perform DE analysis.
Usage:
sccloud de_analysis [options] <input_h5ad_file> <output_spreadsheet>
sccloud de_analysis -h
Arguments:
input_h5ad_file Single cell data with clustering calculated. DE r... |
from django.shortcuts import render
from .models import Post
posts = [
{
'catname': 'Samsung',
'catcontact': 'MOBILE: 24 HOURS, 7 DAYS A WEEK'
},
{
'catname': 'Toshiba ',
'catcontact': 'call 1-800-GO-TOSHIBA (1-800-468-6744)'
},
{
'catname': 'Panasonic',
... |
import sys
import time
import requests
def run():
# Source URL
url = 'https://corona.lmao.ninja/v2/'
# Set URL endpoint
if len(sys.argv) == 1:
url += 'all'
print('===== COVID19 GLOBAL DATA =====')
else:
country = sys.argv[1]
print(f'==== COVID19 IN {country.upper()}... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
#!/usr/bin/env python3
# Copyright 2019 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Used to generate an external link format JSON file for the given tast data file.
In order to use provide the name of the data ... |
import pytest
from datetime import datetime, timedelta
import yaml
import numpy as np
import os
from copy import deepcopy
from wavy.insitumod import insitu_class as ic
from wavy.filtermod import apply_land_mask
sd = "2021-8-2 01"
ed = "2021-8-3 12"
#ico = ic(nID,sensor,sd,ed)
#test_dict = deepcopy(ico.vars())
#@pyt... |
#! python2.7
from soundrts import clientmain
clientmain.main()
|
import sys
import os
from PyQt5.Qt import QMimeData, QUrl, QApplication, QClipboard
from PyQt5.QtCore import QTimer
app = QApplication(sys.argv)
def main(argv):
directory = os.getcwd()
listFiles = sys.argv[1:]
files = []
for str in listFiles:
files.append("file://" + directory + "/" + str)
... |
# Definition for binary tree with next pointer.
# class TreeLinkNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
# self.next = None
class Solution:
# @param root, a tree link node
# @return nothing
def connect(self, root):
if n... |
import copy
from django.shortcuts import render
import pickle, base64
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from django_redis import get_redis_connection
from .serializers import C... |
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 25 08:59:36 2020
@author: Ham
A sample one-liner to do a listop on a list of command-line args
"""
python -c "import sys; print(sum(map(int, sys.argv[1:])))" 3 4 5 |
from typing import List
from xsdata.codegen.mixins import ContainerInterface
from xsdata.codegen.mixins import RelativeHandlerInterface
from xsdata.codegen.models import Attr
from xsdata.codegen.models import AttrType
from xsdata.codegen.models import Class
from xsdata.codegen.models import get_restriction_choice
from... |
# Copyright (C) 2017 Verizon. All Rights Reserved.
#
# File: _envelopes.py
# Author: John Hickey, Phil Chandler
# Date: 2017-02-17
#
# 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 th... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2017 sqlmap developers (http://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""
from lib.core.data import logger
from lib.core.dicts import DBMS_DICT
from lib.core.enums import DBMS
from lib.core.settings import IS_WIN
def checkDependencies():
missing_li... |
import tensorflow as tf
import numpy as np
from sklearn import cross_validation
from data_utils import load_CIFAR10
from extract import create_graph, iterate_mini_batches, batch_pool3_features
from datetime import datetime
import matplotlib.pyplot as plt
from tsne import tsne
import os
import sys
import input_data_sk... |
import cv2
import imutils
from PixelRatio import get_pixel_per_metric
from imutils import contours
ppm = get_pixel_per_metric("capture.png", 100)
cord = []
frame = cv2.imread("capture.png")
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
""" Python library for operations with Spotify Web API and database """
from .database.sqlite3db import Sqlite3db
from .spotify.client import Client, chunk_playlist
def news(database_f, original_playlist_id):
""" Accumulate song from source playlist in local database and based
on... |
# coding=utf-8
# Copyright 2020 The Google Research 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 applicab... |
"""This module includes everything that is needed to
submit flags to the game server."""
import time
import asyncio
import logging
import codecs
from helperlib.logging import scope_logger
from ctfpwn.shared import TooMuchConnectionsException
log = logging.getLogger(__name__)
LOG_LEVEL_STAT = logging.INFO + 1
logging... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-09 07:47
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0003_certification_skill'),
]
operations = [
migrations.AddField(
... |
# relpath.py
from webpie import WPApp, WPHandler
class MyHandler(WPHandler):
def hello(self, request, relpath):
return "Hello %s!\n" % (relpath,) # 1
WPApp(MyHandler).run_server(8080)
|
import re
import logging
import os
import gzip
import pandas
import Expression
from ..misc import Math
########################################################################################################################
class ExpressionManager(Expression.ExpressionManager):
def __init__(self, folder, pattern=... |
import gym
import numpy as np
from envs.deep_cure_env import DeepCure, random_base_infect_rate, random_lifetime, ForeignCountry
import matplotlib.pyplot as plt
from plotting import plot
from stable_baselines3 import DQN, A2C
import torch as th
from stable_baselines3.common.callbacks import EvalCallback
def l... |
NOT_AUTHENTICATED = "Not authenticated"
NO_PUBLICKEY = "JWK public Attribute for authorization token not found"
NOT_VERIFIED = "Not verified"
SCOPE_NOT_MATCHED = "Scope not matched"
NOT_VALIDATED_CLAIMS = "Validation Error for Claims"
|
# Do NOT edit this file!
# It was generated by IdlC class idl.json.python.ProxyAsnVisitor.
#
# Section generated from "/home/nb/builds/MEGA/px2-3.0.0-3.0.9-branch-20140613-none-release-none-pdu-raritan/fwcomponents/mkdist/tmp/px2_final/libisys/src/idl/DiagLogSettings.idl"
#
import raritan.rpc
from raritan.rpc import ... |
# Generated by Django 2.2.12 on 2020-06-22 18:37
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lametro', '0004_add_subject_classification'),
]
operations = [
migrations.AlterField(
model_name='lametrosubject',
... |
import unittest
from archie.projectmodel.entities.ProjectLayout import ProjectLayout
from archie.projectmodel.entities.ProjectServices import ProjectServices
from archie.dependencies.behaviours.FindIncludeDependencies import FindIncludeDependencies, ModuleCollection
from archie.dependencies.entities.IncludeDependencyA... |
#!/bin/python3
# -*- coding: utf-8 -*-
"""
This file is part of the TangoMan PyValidator package.
(c) "Matthias Morin" <mat@tangoman.io>
This source file is subject to the MIT license that is bundled
with this source code in the file LICENSE.
"""
from typing import Any
from pyvalidator.constraints.abstract_va... |
import os
import librosa
import numpy as np
import matplotlib.pyplot as plt
import h5py
dataset_path = '/Users/wiktor/Documents/Projects/IRDM/shufl/magnatagatune_dataset/mp3/'
tags_file = 'data/tags'
idToPath_file = 'data/idToPath'
idToPath = {}
stft_window = 2048
hop = stft_window / 4
#create h5py file for storing... |
#!/usr/bin/env python3
import isce
from isceobj.Sensor import createSensor
import shelve
import argparse
import glob
from isceobj.Util import Poly1D
from isceobj.Planet.AstronomicalHandbook import Const
import os
from mroipac.dopiq.DopIQ import DopIQ
#from isceobj.Util.decorators import use_api
import copy
def cmdLi... |
# Copyright (C) 2009 - 2019 Isotropix SAS. All rights reserved.
#
# The information in this file is provided for the exclusive use of
# the software licensees of Isotropix. Contents of this file may not
# be distributed, copied or duplicated in any form, in whole or in
# part, without the prior written permission of Is... |
import contextlib
import io
from unittest import TestCase
from unittest.mock import patch
from design_patterns.template_method.fahrenheit_celsius_template import ConverterTemplate
class TestConverterTemplate(TestCase):
@patch("design_patterns.template_method.fahrenheit_celsius.sys")
def test_run(self, mock_s... |
from pathlib import Path
from time import sleep
from airflow.contrib.hooks.aws_hook import AwsHook
from airflow.exceptions import AirflowException
from airflow.utils.decorators import apply_defaults
from dagger.dag_creator.airflow.operators.dagger_base_operator import DaggerBaseOperator
from dagger.dag_creator.airflo... |
#!/usr/bin/python
import sys, httplib, uuid, random,time
httplib.HTTPConnection.debuglevel = 0
KeyspaceName = 'm2m'
tablename = 'sensor'
HAProxyIP = '10.99.0.39'
HAProxyport = '8080'
BaseURL = HAProxyIP+':'+HAProxyport
def executeRESTCall(restMethod, serviceBaseURL, resourceName, content):
connection =... |
#!/usr/bin/env python
import math
import os
import random
import sys
from pprint import pprint
sys.path.append("..")
import cppgen
import cmfc
from exceptions import CmfParseError
from visitor import Visitor
from walker import Walker
MAX_SIZE = 5
OUTPUT_DIR = 'TEST_OUTPUT'
def randuint(max_value):
return str(... |
# Copyright 2014 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.
from collections import defaultdict
from telemetry.core.platform import tracing_category_filter
from telemetry.core.platform import tracing_options
from tel... |
lista = (
'Lapis', 1.50,
'Caderno', 15.75,
'Mochila', 100,
'Caneta', 1.25,
'Notebook', 2500
)
print('-'*50)
print(f'{"Lista de preços":^40}')
print('-'*50)
for pos in range(0, len(lista)):
if pos % 2 == 0:
print(f'{lista[pos]:.<30}', end='')
if pos % 2 != 0:
print(f' R$:{lis... |
"""This module contains classes implementing different Evolutionary algorithms.
"""
__all__ = [
"RVEA",
"NSGAIII",
"BaseEA",
"BaseDecompositionEA",
"PPGA",
"TournamentEA",
"IOPIS_NSGAIII",
"IOPIS_RVEA",
"MOEA_D",
]
from desdeo_emo.EAs.BaseEA import BaseEA, BaseDecompositionEA
from ... |
# Copyright (c) 2013, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import unittest
from frappe.utils import nowdate, add_months
from erpnext.selling.report.pending_so_items_for_purchase_request.pending_so_items_for_purchase_req... |
#!/usr/bin/python
#from Solution_v1_On2 import Solution
from Solution import Solution
obj = Solution()
#A = [5,6,7,8]
A = [59828,77802,75493,91030,57013,95808,52342,62073,31928,33106,94814,48919,78767,44287,63250,88940,52580,39345,5260,30711,66449,14137,55180,55823,35306,75693,52528,77736,3743,21500,67136,21809,39398... |
n = int(input("Enter N: "))
l = []
for i in range(0 , n):
inp = int(input("Enter numbers: "))
l.append(inp)
l.sort()
a = 0
b = 0
for i in range(0 , n):
if i % 2 != 0:
a = a * 10 + l[i]
else:
b = b * 10 + l[i]
c = a + b
print(c)
|
import argparse
import math
import time
import numpy as np
import torch
from torch import nn
from torch import optim
import Corpus as c
from model import make_transformer, make_mos_transformer
parser = argparse.ArgumentParser(description='Transformer-MOS')
parser.add_argument('--data', type=str, default='./data/wiki... |
"""
.. include:: ../README.md
"""
__title__ = "pygdbmi"
__version__ = "0.9.0.2"
__author__ = "Chad Smith"
__copyright__ = "Copyright Chad Smith"
__pdoc__ = {"StringStream": False, "printcolor": False}
|
from .bishop import Bishop
from .king import King
from .knight import Knight
from .pawn import Pawn
from .piece import Piece
from .queen import Queen
from .rook import Rook
from .piece_const import PieceValues
__all__ = ['Bishop', 'King', 'Knight', 'Pawn', 'Piece', 'piece_const', 'Queen', 'Rook']
|
# -*- coding: utf-8 -*-
"""Classes capturing the payloads used when running actions."""
import collections
from typing import Dict, Mapping, Optional
from django.conf import settings
from django.contrib.sessions.backends.base import SessionBase
from django.contrib.sessions.models import Session
action_session_dicti... |
from .tox21 import Tox21 |
# Copyright (c) LinkedIn Corporation. All rights reserved. Licensed under the BSD-2 Clause license.
# See LICENSE in the project root for license information.
def init(application, config):
from . import teams, team, team_summary, team_oncall, team_changes
application.add_route('/api/v0/teams', teams)
app... |
# WHERE IS BOB !?! EDABIT SOLUTION:
def find_bob(names):
# creating a for-loop to iterate through the list of names.
for i in range(len(nums)):
# creating a nested if-statement to check for the name "Bob".
if nums[i] == "Bob":
# returning the index of the name if it is found in the lis... |
S = str(input('Qual o seu sexo:F/M')).strip().upper()
while S not in 'MF':
print(f'{S} não é um sexo válido. Certifique-se de responder apenas com F ou M')
S = str(input('Qual o seu sexo:F/M')).strip().upper()
print('Sexo registrado!')
|
__copyright__ = "Copyright (c) 2020-2021 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import subprocess
from typing import Dict, List, Optional
import spacy
from jina import DocumentArray, Executor, requests
from jina_commons.batching import get_docs_batch_generator
_EXCLUDE_COMPONENTS = [
'... |
from flask import render_template, request, redirect, url_for, abort
from flask_login import login_required, current_user
from . forms import UpdateProfile, UpdatePitch, CommentForm
from app.models import User, Pitch, Comment
from . import main
from .. import db
@main.route('/')
def index():
# profile = profile
... |
from keycloak_admin_aio.types import RoleRepresentation
from ..... import KeycloakResource
class ClientScopesScopeMappingsRealm(KeycloakResource):
"""Realm scope mappings for a client scope by id.
.. code:: python
from keycloak_admin_aio import KeycloakAdmin, RoleRepresentation
kc: Keycloa... |
# IMPORTS
import pygame
# THE CLASS
class Ball():
def __init__(self, x, y, radius, color, velocity, direction_x, direction_y):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.velocity = velocity
self.direction_x = direction_x
self.direction_y = direction_y
self.display = pygame.Su... |
"""Common Exceptions for digirock functions and classes.
"""
class Error(Exception):
"""Base class for excceptions in this module."""
pass
class WorkflowError(Error):
"""Exception raised for errors where the defined workflow has not been followed
correctly.
Attributes:
e... |
from tinydb import TinyDB
class Database:
"""Model for database, encapsulates a TinyDB object and the created objects.
Attributes:
location (str): The local path for the TinyDB JSON file.
players (dict): The Player objects created from the database.
tournaments (dict): The tournament ... |
import json
import os
from typing import Union, Dict
from urllib.request import urlopen, Request
from .common import ReleaseFile, EnvironmentInformation
def make_post(release: ReleaseFile):
GITHUB_API_TOKEN = os.getenv("DBT_GITHUB_API_TOKEN")
data: Dict[str, Union[str, bool]] = {
"tag_name": f"v{rele... |
# Generated by Django 3.0.7 on 2021-03-09 23:13
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('stockmarket', '0017_auto_20210307_1803'),
]
operations = [
migrations.AddField... |
# -*- coding: utf-8 -*-
"""
"""
from setuptools import setup, find_packages
with open('requirements.txt') as fd:
requirements = fd.readlines()
with open('test-requirements.txt') as fd:
test_requirements = fd.readlines()
setup(
name='remarkable-friend',
packages=find_packages(),
setup_requires=[]... |
#
# PySNMP MIB module HH3C-SAN-AGG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-SAN-AGG-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:16:46 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
from __future__ import print_function
import healpy as hp
from lenspyx import lensing
import numpy as np
def test_t():
lmax = 200
nside = 256
cls_unl = np.ones(lmax + 1, dtype=float)
tunl = hp.synalm(cls_unl, new=True)
dlm = np.zeros_like(tunl)
hp.almxfl(dlm, np.sqrt(np.arange(lmax + 1) * np.ar... |
from .sheet import IRow, ISheet
from .datasheet import IDataRow, IDataSheet, DataRowBase, DataSheet, PartialDataSheet
from .multisheet import IMultiRow, IMultiSheet, MultiRow, MultiSheet
from .language import Language
from .header import Header
from .column import Column
from .excollection import ExCollection
|
# https://leetcode.com/explore/interview/card/top-interview-questions-easy/99/others/721/
# https://leetcode.com/problems/valid-parentheses/description/
# Valid Parentheses
#
# Given a string containing just the characters '(', ')', '{', '}',
# '[' and ']', determine if the input string is valid.
import unittest
cl... |
#!/usr/bin/env python3
from setuptools import setup
import re
import os
def get_version():
VERSION_RE = re.compile(r'''VERSION\s+=\s+['"]([0-9.]+)['"]''')
with open(os.path.join(os.path.dirname(__file__), 'moverscore.py'), encoding='utf-8') as fin:
return VERSION_RE.search(fin.read()).group(1)
setup(... |
"""
Copyright 2013 Rackspace
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
dist... |
"""
Transmission Preprocessing
--------------------------
preprocessing functions for The Transmission component
"""
import os.path
from pandas import read_csv
import numpy as np
def preprocess (preprocessor, **kwargs):
"""preprocess wind power data
Parameters
----------
preprocessor: p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.