content stringlengths 5 1.05M |
|---|
# tests/test_provider_apparentlymart_testing.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:28:33 UTC)
def test_provider_import():
import terrascript.provider.apparentlymart.testing
def test_datasource_import():
from terrascript.data.apparentlymart.testing import testing_assertions
f... |
import os
import json
import jinja2
import haip.config as config
async def render(template_filename, *, template_dir=None, **args):
tpl_dir = _get_template_dir(template_dir)
tpl_type = _get_template_type(template_filename)
if tpl_type == 'sql':
for key in args.keys():
args[key] = _sql_e... |
import datetime as dt
from portfolyo.tools import nits
from portfolyo.prices import utils
import pandas as pd
import pytest
@pytest.mark.parametrize("tz", [None, "Europe/Berlin"])
@pytest.mark.parametrize(
("value", "ispeak"),
[
("2020-01-01 01:00", False),
("2020-01-01 07:00", False),
... |
#! /usr/bin/python3
# -*- coding: utf-8 -*-
"""
********
Schedule
********
"""
__author__ = 'Alan Loh'
__copyright__ = 'Copyright 2021, nenupy'
__credits__ = ['Alan Loh']
__maintainer__ = 'Alan'
__email__ = 'alan.loh@obspm.fr'
__status__ = 'Production'
__all__ = [
'_TimeSlots',
'Schedule'
]
fr... |
#!/usr/bin/python
from Crypto import Random
from Crypto.Cipher import AES
from Crypto.Util import Counter # for CTR
BLOCK_SIZE=16
def CBCdecrypt(ciphertext, key):
IV = ciphertext[:BLOCK_SIZE] #previous 16 chars are out IV
aes = AES.new(key, AES.MODE_CBC, IV)
return aes.decrypt(ciphertext[BLOCK_SIZE:]) #d... |
CROPS = {
'1': "Alfalfa",
'2': "Alfalfa seed",
'3': "Apples",
'4': "Apricots",
'5': "Asparagus",
'6': "Barley",
'7': "Beans (dry)",
'8': "Beans (green)",
'9': "Beets (table)",
'10': "Blackberries",
'11': "Blueberries",
'12': "Bluegrass Seed",
'13': "Broccoli",
'14': "Brussel Sprouts",
'15': "Cabbage",
'... |
from pyswip import Prolog, prolog
PROLOG_FILENAME = "DATTA_ANUSHA_qn_3.pl"
class PrologInterface():
def __init__(self):
self.prolog = Prolog()
self.prolog.consult(PROLOG_FILENAME)
self.__retractall()
def __retractall(self):
self.prolog.retractall("selected_meals(X)")
self.prolog.retractall("s... |
#!/usr/bin/env python
"""Asterisk AGI script to enable logging and forwarding to OpenSIPS.
This module handles call routing, recording and logging. It needs to be called
from the asterisk dialplan via the AGI() diaplan application.
Usage
-----
The dialplan needs to first set Set(AGISIGHUP=no), then call
AGI(<path/to/... |
# coding: utf-8
# Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
# -*- coding: utf-8 -*-
from model.groupn import Groupn
import pytest
import random
import string
def random_string(prefix, maxlen):
symbols = string.ascii_letters + string.digits + " "*10 #из каких символов случайно выбираем, чтобы увеличить частоту пробелов, умножили их количество на 10
return prefix + "".jo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
A postal zones seed data loader for cooper.
"""
__version__ = '0.0.1' #: the working version
__release__ = '0.0.1' #: the release version
|
import pywapi
from SenseCells.tts import tts
def weather(city_name, city_code):
weather_com_result = pywapi.get_weather_from_weather_com(city_code)
weather_result = "Weather.com says: It is " + weather_com_result['current_conditions']['text'].lower() + " and " + weather_com_result['current_conditions']['tempe... |
#coding: utf8
from tkinter import *
def bt_click():
bt.place(x=50, y=50)
lb["text"] = "Funcionou tinindo que ta tinindo"
janela = Tk()
lb = Label(janela, text="Fala ae galera!!!")
lb.place(x=100, y=130)
janela["bg"] = "#2196f3"
janela.geometry("300x300+400+100")
bt = (Button(janela, width=20, text="OK", command=... |
"""Translate basic Frictionless Table-Schema table definitions to Deriva.
convert_tableschema(tableschema, schema_name = 'CFDE', skip_system_cols = False)
returns ERM schema as dictionary
"""
from deriva.core.ermrest_model import builtin_types, Table, Column, Key, ForeignKey
schema_tag = 'tag:isrd.isi.edu,2019:tabl... |
from typing import Dict, Iterable
from AoC20.day_7 import Bag, parse, data as data
def count_children(bag: str, bags: Dict[str, Bag]) -> Iterable[int]:
yield 1
for child, cost in bags[bag].children.items():
for _ in range(cost):
yield from count_children(child.name, bags)
print(sum(coun... |
# projects/models.py
from django.db import models
class Project(models.Model):
class Meta:
db_table = 'project'
id = models.AutoField(primary_key=True)
project_name = models.CharField(max_length=1024, null=False)
program = models.ForeignKey('programs.Program', related_name='projects', on_del... |
# Make a nice namespace
from malcolm.core.attribute import Attribute # noqa
from malcolm.core.block import Block # noqa
from malcolm.core.controller import Controller # noqa
from malcolm.core.clientcomms import ClientComms # noqa
from malcolm.core.clientcontroller import ClientController # noqa
from malcolm.core.e... |
# coding=utf-8
# Copyright 2018 The Tensor2Tensor 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... |
from __future__ import annotations
import asyncio
import inspect
from collections import defaultdict
from functools import partial
from typing import TYPE_CHECKING, Any, Awaitable, Callable, Coroutine, Hashable, Literal, TypeVar, Union, overload
from weakref import WeakValueDictionary
from monty.errors import LockedR... |
#!/usr/bin/env python3
import lib
import os
import pprint
import sys
import readline
def test_rpc(chain):
try:
rpc_connection = lib.def_credentials(chain)
dummy = rpc_connection.getbalance() # test connection
return(rpc_connection)
except Exception as e:
print(e)
err... |
from __future__ import unicode_literals
import inspect
import sys
import threading
import pandas # noqa: F401
import spacy
from pyspark.rdd import ignore_unicode_prefix
from pyspark.sql.functions import PandasUDFType
from pyspark.sql.types import *
if sys.version_info.major == 3:
unicode = str
functions_info =... |
from sklearn.preprocessing import MinMaxScaler
import os
import numpy as np
import pickle
import matplotlib.pyplot as plt
import pandas as pd
import theano
from .utils import split_train_test
from .data import MolDataSet,DataLoader
from .bpnet import BpNet
from .utils import Jaccard,Cosine,Peason
from .dbn import DBNM... |
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import (
Group,
User
)
from django.conf import settings
from django.core import serializers
from django.db import transaction
from django.shortcuts import get_object_or_404, redirect, render
from django.http import (
H... |
class RecordPublishedClusterVersion:
"""A version of a published cluster in a mastering project.
This is not a `BaseResource` because it does not have its own API endpoint.
:param data: The JSON entity representing this version.
"""
def __init__(self, data):
self._data = data
@proper... |
#!/usr/bin/python
import sys
import subprocess
__author__ = "Shyam"
var=sys.argv[1]
subprocess.call(["amixer cset numid=3 1 > /dev/null 2> /dev/null"], shell=True)
subprocess.call(["pico2wave -w test.wav var"] , shell=True)
subprocess.call(["aplay test.wav"], shell=True)
|
# Add deeptrack to path
import sys
sys.path.append(".")
import deeptrack as dt
import numpy as np
# Centered particle with random radius
particle = dt.Sphere(
position=(14, 14), radius=lambda: (3 + np.random.rand() * 3) * dt.units.px
)
optics = dt.Fluorescence(output_region=(0, 0, 28, 28))
data = optics(partic... |
from inversefed import consts
import torch
from torchvision import datasets, transforms
class DataLoader:
def __init__(self, data, device):
self.data = data
self.device = device
def get_mean_std(self):
if self.data == 'cifar10':
mean, std = consts.cifar10_mean... |
"""
Regression tests for BERT subgraphs
"""
import os
import numpy as np
import pytest
import onnx
from daceml.onnx import ONNXModel
data_directory = os.path.join(os.path.dirname(__file__), "onnx_files")
@pytest.mark.ort
def test_slice(gpu, sdfg_name):
model = onnx.load(os.path.join(data_directory, "slice.onnx... |
#!/usr/bin/env python
##
# @file
# This file is part of SeisSol.
#
# @author Martin van Driel (driel AT geophysik.uni-muenchen.de, http://www.geophysik.lmu.de/Members/driel)
#
# @section LICENSE
# Copyright (c) SeisSol Group
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
... |
import unittest
import base_test
import json
class GroupTest(base_test.BaseTest):
def setUp(self):
super(GroupTest, self).setUp()
self._org = self.post('/api/orgs', {"name":"group_org", "url":"https://myorg.com"})
def tearDown(self):
self.delete('/api/orgs/%s' % self._org["id"])
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
import os
APP_ROOT = os.path.dirname(os.path.dirname((__file__)))
STATIC = os.path.join(APP_ROOT, 'static')
IMAGES = os.path.join(STATIC, 'images')
SAMPLES = os.path.join(STATIC, 'wav_files')
TEMPLATES = os.path.join(APP_ROOT, 'templates')
|
drc = [(0, 1), (1, 0)]
def dfs(r, c):
if (r, c) in memo:
return memo[r, c]
ret = ''
for dr, dc in drc:
nr, nc = r + dr, c + dc
if nr < H and nc < W and board[nr][nc].isdigit():
cand = dfs(nr, nc)
if len(cand) > len(ret) or (len(cand) == len(ret) and cand > r... |
import numpy as np
import random
import tensorflow as tf
from sklearn.metrics import roc_auc_score
import matplotlib.pyplot as plt
from ROC import *
def window_separate(values, seg_len):
assert seg_len <= len(values)
return np.vstack(values[i:i+seg_len] for i in range(len(values)-seg_len+1))
def assessment_... |
# SPDX-License-Identifier: BSD-3-Clause AND Apache-2.0
# Copyright 2018 Regents of the University of California
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code... |
#!/usr/bin/env python3
import configparser
from ast import literal_eval
def conf_parse(init_loc):
config = configparser.ConfigParser()
config.read(init_loc)
SOMOSPIE_vars = {}
for var in ["START", "CODE", "DATA", "OUTPUT", "COV_FILE", "SM_FILE", "EVAL_FILE"]:
SOMOSPIE_vars[var] = f'"... |
"""Class and methods for handling loading of video files"""
from moviepy.editor import VideoFileClip
import librosa
def append_clips(first, second):
"""Append two different VideoClips objects
Arguments:
----------
first -- loki.VideoClips:
These filenames will go first.
second -- loki.Vide... |
import pygame
import time
def save_screenshot(game):
timestamp = int(time.time())
pygame.image.save(game.screen, str(timestamp) + ".png")
|
from facedetection_module import detectfaces
if __name__=='__main__':
detectfaces(default_draw=True) |
"""This script contains all functions used to import, analyse and plot dynophores results"""
import os
import re
import pickle
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from string import ascii_uppercase
def getmatchingfiles(pattern1, pattern2, list):
"""
Fr... |
# @lc app=leetcode id=560 lang=python3
#
# [560] Subarray Sum Equals K
#
# https://leetcode.com/problems/subarray-sum-equals-k/description/
#
# algorithms
# Medium (43.66%)
# Likes: 9064
# Dislikes: 303
# Total Accepted: 566.3K
# Total Submissions: 1.3M
# Testcase Example: '[1,1,1]\n2'
#
# Given an array of inte... |
import shutil
from pathlib import Path
import json
from typing import Optional
from src.benchmark.utils import (
Params,
SgdConfigParser,
parse_option,
run_command,
run_sgd_multiple,
get_sgd_callback,
clear_options,
dict_to_str,
)
from src.benchmark.parser import get_parser
CLEAR_OPTIO... |
def convert_temperatures(t, source, target):
celsius = 0.0
#convert to celsius
if source == "Kelvin":
celsius = t - 273.15
elif source == "Fahrenheit":
celsius = (t - 32.0) * 5/9
elif source == "Rankine":
celsius = (t - 491.67) * 5/9
elif source == "Delisle":
cels... |
from django.conf.urls import url,include
from .views import GETAPIView
from .views import CREATEAPIView
from .views import UPDATEAPIView
from .views import DELETEAPIView
urlpatterns = [
url('GET/', GETAPIView.as_view()),
url('CREATE/', CREATEAPIView.as_view()),
url('UPDATE/', UPDATEAPIView.as_view()... |
#!/usr/bin/env python3
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
from typing import List
from augly.video.augmenters.ffmpeg.base_augmenter import BaseVidgearFFMPE... |
import requests
import json
from .helper import Helper
class Languages(Helper):
def __init__(self, base_url, org_pk, teams_pk, access_token, _csrf_token, headers, pagination):
super().__init__(base_url, org_pk, teams_pk, access_token, _csrf_token, headers, pagination)
|
from utils import CSVScraper
class VancouverPersonScraper(CSVScraper):
# https://data.vancouver.ca/datacatalogue/councilContactInfo.htm
csv_url = 'ftp://webftp.vancouver.ca/OpenData/csv/ElectedOfficialsContactInformation.csv'
many_posts_per_area = True
|
# pylint: disable=missing-function-docstring, missing-module-docstring, no-value-for-parameter
def f(b:'int'):
print(b)
f()
|
# -*- coding:utf8 -*-
# !/usr/bin/env python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2... |
"""For each user record, add info about the BIFs they've participated in.
NOTE:
This script doesn't create the proper records when someone sends to (or receives from) a team. I updated the
necessary records manually in the biffers.json file after running this script.
"""
import boto3
import sqlite3
import time
from ... |
#!/usr/bin/env python
# Very slow. See compare.pyx
from __future__ import division
import cogent.util.progress_display as UI
from cogent.util.modules import importVersionedModule, ExpectedImportError
__author__ = "Peter Maxwell"
__copyright__ = "Copyright 2007-2012, The Cogent Project"
__credits__ = ["Peter Maxwell"... |
# -*- coding: utf-8 -*-
"""libsqs module
Module interface for dealing with SQS queue and plus some useful dispatching batch jobs impl
https://boto3.amazonaws.com/v1/documentation/api/latest/guide/sqs-example-sending-receiving-msgs.html
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sqs.htm... |
import json
import re
from base64 import b64encode
from io import BytesIO
from django.conf import settings
from django.contrib import messages
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import redirect
from django.urls import reverse
from django.utils.decorators import method_decorator... |
# Generated by Django 2.1.5 on 2019-01-16 23:18
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import metadeploy.api.models
class Migration(migrations.Migration):
dependencies = [("api", "0036_add_help_text")]
operations = [
migrations.AlterModelOptions(
... |
# Adapted from original work by github user marioferpa --> https://github.com/marioferpa/krpcscripts
from matplotlib.colors import ListedColormap
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D, proj3d
import numpy as np
from math import radians, degrees
from Utilities import si_val
# Plot s... |
import rumps
import SSFlaskApp from './flaskapp'
class SSApp(rumps.App):
def __init__(self):
super(SSApp, self).__init__(name="SeizureSavior")
self.flaskApp = SSFlaskApp()
@rumps.clicked("Enable Seizure Saviour")
def startServer(self, sender):
print('Starting Server')
self.... |
"""
overload.py
A simple function overload decorator that mostly works.
It makes an heavy use of annotation and thus may not be as pythonic as it
should.
"""
import inspect
class overload:
functions = dict()
def __init__(self, f):
self.f = f
funsig = inspect.signature(f)
key = '{}_{}... |
from .DQN_agent import *
from .DDPG_agent import *
from .A2C_agent import *
from .CategoricalDQN_agent import *
from .NStepDQN_agent import *
from .QuantileRegressionDQN_agent import *
from .PPO_agent import *
from .OptionCritic_agent import *
from .TD3_agent import *
|
#*****************************
#date:2016-07-26
#author:luolongqiang
#*****************************
import os, sys, time, argparse
import pandas as pd
from multiprocessing import Pool, cpu_count
from EvalFinal import GetFileList, IsSubString, GetCategories
def FilterWithThreshold(args):
input_txt, output_txt = arg... |
class MarkDownElement:
def __init__(self, text=''):
self._text = text
def __str__(self):
return self.text
def __add__(self, other):
return self.text + str(other)
def __radd__(self, other):
return str(other) + self.text
@property
def text(self):
return ... |
import yt
import numpy as np
from matplotlib import pyplot as plt
import wdmerger
ncell_arr = [ 128, 256, 512, 1024, 2048]
nproc_arr = [ 8, 64, 512, 4096, 32768]
time_arr = np.zeros(len(nproc_arr))
idx = 0
for ncell in ncell_arr:
# Open up the standard output for analysis.
dir = "results/n" + str(... |
# See LICENSE for licensing information.
#
# Copyright (c) 2016-2019 Regents of the University of California and The Board
# of Regents for the Oklahoma Agricultural and Mechanical College
# (acting for and on behalf of Oklahoma State University)
# All rights reserved.
#
from math import log
import design
from tech imp... |
print("action one working")
|
import json
import os
import sys
import time
import shutil
import botocore.session
import pytest
import requests
from chalice.cli.factory import CLIFactory
from chalice.utils import record_deployed_values, OSUtils
from chalice.deploy.deployer import ChaliceDeploymentError
CURRENT_DIR = os.path.dirname(os.path.abspa... |
# Created By: Virgil Dupras
# Created On: 2009-05-09
# Copyright 2015 Hardcoded Software (http://www.hardcoded.net)
#
# This software is licensed under the "GPLv3" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.gnu.org/licenses/gpl-... |
import pyautogui as p, webbrowser
from win10toast import ToastNotifier
from datetime import datetime
from time import sleep
from os import startfile, getlogin
import pandas as pd
# todo click on google meet mute and camera off button
def zoom_meeting(meeting_id:str, password:str):
"""Joins zoom meeting wi... |
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\situations\ambient\walkby_tandem_sledding_situation.py
# Compiled at: 2020-08-10 22:22:36
# Size of ... |
import numpy as np
from sklearn.metrics import roc_auc_score
# old shape: nFrame * nJoint => new shape: k * (2 * half_seg_len) * nJoint
def segmentseq(input_data, half_seg_len, batchsize = 0, overlapping = True):
if overlapping:
k = input_data.shape[0] // half_seg_len - 1
else:
k = inpu... |
"""
Copyright (c) 2016-2017 Dell Inc. or its subsidiaries. All Rights Reserved.
"""
import fit_path # NOQA: unused import
import unittest
import flogging
from config.redfish1_0_config import config
from modules.redfish_auth impo... |
#!/usr/bin/env python3
"""
The MIT License (MIT)
Copyright (c) 2017 Erik Perillo <erik.perillo@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without l... |
#!/usr/bin/env python
# Copyright (c) 2013 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.
"""Prepare tests that require re-baselining for input to make_expectations.py.
The regularly running perf-AV tests require re-base... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# HubCrypt
#
"""
HubCrypt
~~~~~~~~
HubCrypt is a simple library to encrypt and decrypt messages using
public/private keypairs used on GitHub.com
"""
__title__ = 'hubcrypt'
__version__ = '0.0.0-dev'
__build__ = 0x000000
__author__ = 'Kyle Kelley'
__license__ = 'Apache ... |
from .mitm import MITM
name = "smallMITM"
|
import numpy as np
def sindeg(x_deg):
"""Sine function for argument in degrees.
"""
x_rad = x_deg * np.pi / 180
return np.sin(x_rad)
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import numpy as np
class Mainnet:
def __init__(self):
self.EM_SV_net, self.AB_DIG_Net = self.make_net()
def make_net(self):
import tensorflow as tf
from keras import backend as K
from keras.models import Model
from keras.layers import Input, Dense, Lambda, LSTM, Repeat... |
import logging
from twisted.internet import defer, reactor
from twisted.internet.defer import CancelledError
from twisted.trial import unittest
from stompest.async.util import InFlightOperations
from stompest.error import StompCancelledError
logging.basicConfig(level=logging.DEBUG)
LOG_CATEGORY = __name__
class In... |
"""
User ACL
========
"""
_schema = {
# Medlemsnummer
'id': {'type': 'integer',
'readonly': True
},
'acl': {'type': 'dict',
'readonly': False,
'schema': {'groups': {'type': 'list',... |
class D0CLI(Exception):
def __init__(self, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
if not hasattr(self, 'message'):
self.message = args[0] if args else None
class Unauthorized(D0CLI):
pass
class Conflict(D0CLI):
pass
class NotFound(IndexError, D0CL... |
#!/usr/bin/env python3
import os
import shutil
from os.path import expanduser
#fazer o backup dos arquivos originail
#apagar os arquivos originais
#copy the i3 config file
resource_folder = './resource'
source = resource_folder + '/config'
home = expanduser("~")
destination = home + '/.config/i3'
shutil.copytree... |
from enum import Enum
__NAMESPACE__ = "http://www.opengis.net/ows/2.0"
class RangeClosureValue(Enum):
"""
:cvar CLOSED: The specified minimum and maximum values are included
in this range.
:cvar OPEN: The specified minimum and maximum values are NOT
included in this range.
:cvar OPEN_... |
# updated by @nub_a_f
# previously @senku_ishigamiii/ @Uzumaki_Naruto_XD
# that can only check client/owner's limitations
# but now can check anyone's limitations
from . import *
from beastx.events import register
@register(pattern=".limited ?(.*)")
async def _(e):
match = e.pattern_match.group(1)
msg = a... |
# Faça um programa que calcule a soma entre todos os números ímpares que são
# múltiplos de três e que se encontram no intervalo de 1 até 500.
cont = 0
soma = 0
for num in range(1, 501, 2):
if num % 3 == 0:
cont += 1
soma += num
print(f'Em {cont} números ímpares múltiplos de 3, a soma é de {soma}.... |
""" Generate reference for MPC using a trajectory generator.
"""
__author__ = 'Achin Jain'
__email__ = 'achinj@seas.upenn.edu'
import numpy as np
from bayes_race.utils import Spline2D
def ConstantSpeed(x0, v0, track, N, Ts, projidx, scale=0.9):
""" generate a reference trajectory of size 2x(N+1)
first column is... |
from flask import Flask, request
import telepot;import urllib3;import time
import datetime;import difflib; #import re #import mmap
proxy_url = "http://proxy.server:3128"
telepot.api._pools = {
'default': urllib3.ProxyManager(proxy_url=proxy_url, num_pools=3, maxsize=10, retries=False, timeout=10),
}
telepot.api._on... |
# encoding: UTF-8
import requests
from restclient import GET, POST
import json
import threading
import time
class WeixinMessage(object):
expires_time = 0
access_token = None
def __init__(self):
# self.allusers = {'aaron': 'o5iF2091TiNQfN8ay9fnrh7Sph-4',
# 'caodong': 'o5iF... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: thepoy
# @Email: thepoy@163.com
# @File Name: __init__.py
# @Created: 2021-05-21 13:53:40
# @Modified: 2022-01-12 22:00:55
from colorful_logger.logger import get_logger, logger, child_logger, DEBUG, INFO, WARNING, ERROR, FATAL
__all__ = [
"logger",
"g... |
#
# PySNMP MIB module SCA-TUNNEL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SCA-TUNNEL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:53:00 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2... |
"""Utilities to handle unicode text data."""
import unicodedata
def unicode_ci_compare(s1: str, s2: str):
"""
Perform case-insensitive comparison of two identifiers, using the
recommended algorithm from Unicode Technical Report 36, section
2.11.2(B)(2).
"""
return (
unicodedata.normal... |
n1 = int(input(' digite o primeiro valor '))
n2 = int(input(' Digite o segundo valor '))
s = n1 + n2
print(" A soma dos valores {} e {} sera {}" .format(n1, n2, s)) |
import json
from random import choice
import discord
import requests
from deep_translator import GoogleTranslator, single_detection
from discord.ext import commands
from cogs.config import colour, api_key_for_single_detection
from cogs.commands import commands_names as cs
from cogs.database_connector import Database
fr... |
"""Defines simple logging functionality.
Notes
-----
Use `get(module_name)` to acquire a logging object for module `module_name`.
"""
import logging
import logging.config
import settings
logging.config.dictConfig(settings.LOG_CONFIG) # when first imported, check settings to see how how to enable
def get(module_nam... |
from utils.parser import BaseParser
from nltk.tokenize import word_tokenize
from nltk import pos_tag
from sumy.utils import get_stop_words
class PlaintextParser(BaseParser):
"""
Parse simple plain text data.
"""
def __init__(self, sents, pos_tagger=pos_tag, keep_only_n_and_adj=True, remove_stopwords=... |
import os
from collections import defaultdict
import luigi
import ujson
import numpy as np
from numpy.random import RandomState
import pandas as pd
from .config import INPUT_DIR, OUTPUT_DIR
from .input_data import OrdersInput, OrderProductsInput
class _InputCSV(luigi.ExternalTask):
filename = None
@classme... |
import pandas as pd
import logging
def validate_options(left: pd.DataFrame, right: pd.DataFrame, columns: list, keep: str, keep_missing: str) -> bool:
log = logging.getLogger(__name__)
for column in columns:
# Check if column in each file
if column not in left.columns:
raise ValueE... |
class IStructRoot:
pass
|
# Generated by Django 2.1.7 on 2019-02-20 21:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('materials', '0046_auto_20190220_1525'),
]
operations = [
migrations.AddField(
model_name='dataset',
name='crystal_sy... |
import pathlib
import numpy as np
test_data = 0
path = str(pathlib.Path(__file__).parent.resolve())
with open(path+"/data{}.csv".format("_test" if test_data else ""), 'r') as file:
lines = file.read().splitlines()
cavern = np.empty((len(lines), len(lines[1])), dtype=int)
for i in range(len(lines)):
... |
import logging
import voluptuous as vol
from homeassistant.components.light import Light, PLATFORM_SCHEMA
from homeassistant.const import CONF_NAME, CONF_ADDRESS, CONF_DEVICES
import homeassistant.helpers.config_validation as cv
from brownpaperbag.bpbgate import BpbGate
DOMAIN = "brownpaperbag"
DEPENDENCIES=["brownp... |
# Copyright (c) 2019, IRIS-HEP
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the foll... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.