content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from chai import Chai
from arrow import arrow, locales
class ModuleTests(Chai):
def test_get_locale(self):
mock_locales = self.mock(locales, "_locales")
mock_locale_cls = self.mock()
mock_locale = self.mock()
self.... | python |
# -*- coding: utf-8 -*-
# Copyright (C) H.R. Oosterhuis 2021.
# Distributed under the MIT License (see the accompanying README.md and LICENSE files).
import numpy as np
import os.path
import gc
import json
FOLDDATA_WRITE_VERSION = 4
def _add_zero_to_vector(vector):
return np.concatenate([np.zeros(1, dtype=vector.d... | python |
from django.test import TestCase
from django.urls import reverse
from .models import Post
# Create your tests here.
class PostModelTest(TestCase):
def setUp(self):
Post.objects.create(title='Mavzu', text='yangilik matni')
def test_text_content(self):
post = Post.objects.get(id=1)
expe... | python |
from django.shortcuts import render, redirect, get_object_or_404
from .models import BlogPost as blog
from .models import Comment
from .forms import CreateCommentForm, UpdateCommentForm
# Create your views here.
def post_view(request):
qs=blog.objects.all()
context = {
'qs' : qs,
}
return render(request, 'blog/m... | python |
from pyflink.common import ExecutionMode, RestartStrategies
from pyflink.common.serialization import JsonRowDeserializationSchema
from pyflink.common.typeinfo import Types
from pyflink.dataset import ExecutionEnvironment
from pyflink.datastream import StreamExecutionEnvironment, CheckpointingMode, ExternalizedCheckpoin... | python |
import sys
import os
from bs4 import BeautifulSoup
import markdown
"""
将 Markdown 转换为 HTML
"""
class MarkdownToHtml:
headTag = '<head><meta charset="utf-8" /></head>'
def __init__(self,cssFilePath = None):
if cssFilePath != None:
self.genStyle(cssFilePath)
def genStyle(self,cssFile... | python |
import math
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import matplotlib.transforms as mtransforms
from mpl_toolkits.axes_grid.anchored_artists import AnchoredText
def setup_axes(diff=False):
fig = plt.figure()
axes = []
if diff:
gs = gridspec.GridSpec(2, 1, height_rati... | python |
from rest_framework import serializers
from polyclinics.models import Poly
class PolySerializer(serializers.ModelSerializer):
class Meta:
model = Poly
fields = '__all__'
| python |
import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''BuddyPress REST API Privilege Escalation to RCE''',
"description": '''The BuddyPress WordPress plugin was affected by an REST API Privilege Escalation to RCE''',
"severity": "high",
"re... | python |
#!/usr/bin/env python
# Copyright (C) 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | python |
import time
# only required to run python3 examples/cvt_arm.py
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import datasets, transforms
from torch.utils.data import Dataset
import os
import math
import numpy as np
device = torch.device('cuda' if torch.cuda.is... | python |
import os
import requests
from datetime import datetime, timedelta
import gitlab
class Gitlab():
def __init__(self, api_url, **kwargs):
self.gitlab = gitlab.Gitlab(api_url, **kwargs)
def is_gitlab(self):
if os.environ.get('CI', 'false') == 'true':
return True
else:
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---------------------------------------
# Project: PKUYouth Webserver v2
# File: __init__.py
# Created Date: 2020-07-28
# Author: Xinghong Zhong
# ---------------------------------------
# Copyright (c) 2020 PKUYouth
import time
import datetime
import calendar
from func... | python |
import os
import re
import sys
import codecs
from setuptools import setup, find_packages, Command
from setuptools.command.test import test as TestCommand
here = os.path.abspath(os.path.dirname(__file__))
setup_requires = ['pytest', 'tox']
install_requires = ['six', 'tox', 'atomos']
tests_require = ['six', 'pytest-c... | python |
# Unsere Funktion nimmt eine Liste als Parameter
def find_nouns(list_of_words):
nouns = list()
# Das erste Wort ist wahrscheinlich großgeschrieben, fällt aber aus unserer Definition raus
for i in range(1, len(list_of_words)):
current_word = list_of_words[i]
if current_word[0].isupper():
#... | python |
from app import app
from flask import Blueprint, render_template
@app.errorhandler(404)
def not_found_error():
return render_template('errors/404.html'), 404
@app.errorhandler(500)
def internal_error(error):
return render_template('errors/500.html'), 500
| python |
import glob
import numpy as np
import sys
import argparse
def main():
parser = argparse.ArgumentParser(description="Produce report from result files")
parser.add_argument('--path', type=str, default="",
help="Path to the result files (* will be appended)")
args = parser.parse_args()... | python |
# This sample tests the case where a protocol class derives from
# another protocol class.
from typing import Generic, TypeVar, Protocol
Arg = TypeVar("Arg", contravariant=True)
Value = TypeVar("Value")
class Base1(Protocol[Value]):
def method1(self, default: Value) -> Value:
...
class Base2(Base1[Valu... | python |
import collections
from supriya import CalculationRate
from supriya.synthdefs import WidthFirstUGen
class ClearBuf(WidthFirstUGen):
"""
::
>>> clear_buf = supriya.ugens.ClearBuf.ir(
... buffer_id=23,
... )
>>> clear_buf
ClearBuf.ir()
"""
### CLASS V... | python |
from collections import OrderedDict
from itertools import takewhile
from dht.utils import last
class Cluster(object):
def __init__(self, members):
self.hash = hash
self.members = OrderedDict(((self.hash(node), node) for node in members))
def __len__(self):
return sum((len(node) for n... | python |
from typing import Optional
from pydantic import BaseSettings, Json
from ._version import version as __version__ # NOQA
class Settings(BaseSettings):
auth_token_url: str = "https://solarperformanceinsight.us.auth0.com/oauth/token"
auth_jwk_url: str = (
"https://solarperformanceinsight.us.auth0.com/.w... | python |
from rest_framework import viewsets, status
from rest_framework.response import Response
from rest_framework.decorators import action
from backend.api.models import MiembroSprint, Usuario, Rol
from backend.api.serializers import UsuarioSerializer
class UsuarioViewSet(viewsets.ViewSet):
"""
UsuarioViewSet View... | python |
from thenewboston.accounts.manage import create_account
from thenewboston.verify_keys.verify_key import encode_verify_key
def random_encoded_account_number():
signing_key, account_number = create_account()
return encode_verify_key(verify_key=account_number)
| python |
# -*- coding: utf-8 -*-
import streamlit as st
import numpy as np
import pandas as pd
import altair as alt
from io import BytesIO
def to_excel(df):
output = BytesIO()
writer = pd.ExcelWriter(output, engine='xlsxwriter')
df.to_excel(writer, index=True, sheet_name='杜子期血常规数据统计')
workbook = writer.book
... | python |
import asyncio
import logging
import logging.handlers
import time
from contextlib import suppress
from typing import Optional, Union
from ..thread_pool import run_in_new_thread
def _thread_flusher(
handler: logging.handlers.MemoryHandler,
flush_interval: Union[float, int],
loop: asyncio.AbstractEventLoop... | python |
#
# Copyright (c) 2006-2013, Prometheus Research, LLC
#
"""
:mod:`htsql.ctl.regress`
========================
This module implements the `regress` routine.
"""
from .error import ScriptError
from .routine import Argument, Routine
from .option import (InputOption, TrainOption, PurgeOption,
Forc... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
import gym
import shutil
import tempfile
import ray
from ray.rllib.a3c import DEFAULT_CONFIG
from ray.rllib.a3c.a3c_evaluator import A3CEvaluator
from ray.rllib.dqn.dqn_evaluator import adjust_... | python |
# -*- coding: utf-8 -*-
"""
Management of Redis server
==========================
.. versionadded:: 2014.7.0
:depends: - redis Python module
:configuration: See :py:mod:`salt.modules.redis` for setup instructions.
.. code-block:: yaml
key_in_redis:
redis.string:
- value: string data
The redis s... | python |
import cv2
import numpy as np
import matplotlib.pyplot as plt
img = cv2.imread('canyon.png')
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
values = []
for i in range(256):
n = np.where(gray_img == i, 1., 0.).sum()
values.append(n)
plt.bar(range(256), height=values, width=1.)
plt.xlabel('intensity')
plt.yl... | python |
"""
Profile ../profile-datasets-py/div83/023.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div83/023.py"
self["Q"] = numpy.array([ 2.79844200e+00, 3.21561000e+00, 4.08284300e+00,
4.76402700e+00, 4.58551900e+00, 4.69499800e+00,
5.2297... | python |
"""
Outpost URL Configuration
"""
import django
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.views.static import serve
from django.views.i18n import JavaScriptCatalog
from rest_framework.authtoken import views as authtoken
js_info_dict = {
... | python |
import argparse
from flatdb import flatdb_app
from flatdb.app import define_urls
def get_options():
parser = argparse.ArgumentParser()
parser.add_argument('-d', '--debug', action='store_true', default=False)
parser.add_argument('-p', '--port', type=int, default=7532)
parser.add_argument('-b', '--data... | python |
'''
the following import is only necessary because eip is not in this directory
'''
import sys
sys.path.append('..')
'''
The simplest example of reading a tag from a PLC
NOTE: You only need to call .Close() after you are done exchanging
data with the PLC. If you were going to read in a loop or read
more tags, you w... | python |
from __future__ import unicode_literals
import frappe
from frappe.model.utils.rename_field import rename_field
def execute():
frappe.reload_doc("accounts", "doctype", "pricing_rule")
try:
rename_field("Pricing Rule", "price_or_discount", "rate_or_discount")
rename_field("Pricing Rule", "price", "rate")
except... | python |
import logging
import os
import requests
import pickle
import json
from configparser import ConfigParser
logger = logging.getLogger(__name__)
project_dir = os.path.abspath(os.path.dirname(__file__)) + '/'
config = ConfigParser()
config.read(project_dir + '/config.cfg')
def get_or_download_file(filename, k, value, c... | python |
from collections import namedtuple
Point = namedtuple('point', 'x, y')
mouse_pos = Point(100, 200)
print("X Position of Mouse:", mouse_pos.x) | python |
import json
from graphql_relay import to_global_id
from tracker.api.services.auth import (
generate_auth_token,
)
from tracker.api.status_codes import StatusEnum
async def test_create_role_mutation(
client,
setup_project_list_test_retrun_auth_token
):
pm_auth_token = setup_project_list_test_retrun_a... | python |
import pandas as pd
from .taxa_tree import NCBITaxaTree
from ..constants import MICROBE_DIR
MICROBE_DIR_COLS = [
'gram_stain',
'microbiome_location',
'antimicrobial_susceptibility',
'optimal_temperature',
'extreme_environment',
'biofilm_forming',
'optimal_ph',
'animal_pathogen',
's... | python |
import json
import os
from django.apps import apps
DJANGO_TAILWIND_APP_DIR = os.path.dirname(__file__)
def get_app_path(app_name):
app_label = app_name.split(".")[-1]
return apps.get_app_config(app_label).path
def get_tailwind_src_path(app_name):
return os.path.join(get_app_path(app_name), "static_src... | python |
from model_defs import *
from utils import *
from tensorflow.models.rnn.rnn_cell import *
###################################
# Building blocks #
###################################
# takes features and outputs potentials
def potentials_layer(in_layer, mask, config, params, reuse=False, name='Potentia... | python |
import networkx as nx
import numpy as np
import torch
from gym_ds3.envs.core.node import Node
from gym_ds3.envs.utils.helper_dict import OrderedSet
class JobDAG(object):
def __init__(self, job):
self.job = job
self.jobID = self.job.task_list[0].jobID
self.commvol = self.job.comm_vol
... | python |
from typing import List
import torch
from torch.nn import ParameterList, Parameter
from allennlp.common.checks import ConfigurationError
class ScalarMix(torch.nn.Module):
"""
Computes a parameterised scalar mixture of N tensors, `mixture = gamma * sum(s_k * tensor_k)`
where `s = softmax(w)`, with `w` an... | python |
import bpy,bmesh
import time,copy,mathutils,math
from mathutils import noise
Context={
"lasttick":0,
"running":False,
"store":{},
"starttime":-1
}
def timeNow():
t=time.time()
return t
def calcFrameTime():
fps = max(1.0, float(bpy.context.scene.render.fps))
return 1.0/f... | python |
# -*- coding: utf-8 -*-
import os
from .. import StorageTests, get_server_mixin
dav_server = os.environ.get('DAV_SERVER', 'skip')
ServerMixin = get_server_mixin(dav_server)
class DAVStorageTests(ServerMixin, StorageTests):
dav_server = dav_server
| python |
from __future__ import absolute_import, division, print_function
import os
import time
import numpy as np
import seaborn as sns
import tensorflow as tf
import tensorflow_probability as tfp
from matplotlib import pyplot as plt
from tensorflow import keras
from odin import visual as vs
from odin.bay import kl_divergen... | python |
"""Script to convert MultiWOZ 2.2 from SGD format to MultiWOZ format."""
import glob
import json
import os
from absl import app
from absl import flags
from absl import logging
FLAGS = flags.FLAGS
flags.DEFINE_string("multiwoz21_data_dir", None,
"Path of the MultiWOZ 2.1 dataset.")
flags.DEFINE_st... | python |
#SENSOR_DATA_TRANSFER
import socket
import serial
host = "192.168.137.54"
port = 50007
import time
mySocket = socket.socket()
mySocket.bind((host,port))
mySocket.listen(1)
conn, addr = mySocket.accept()
print ("Connection from: " + str(addr))
aD=serial.Serial('/dev/ttyACM0',9600)
while True:
while ... | python |
import time
from typing import Any, Union
from copy import deepcopy
import biorbd_casadi as biorbd
import numpy as np
from scipy import interpolate as sci_interp
from scipy.integrate import solve_ivp
from casadi import vertcat, DM, Function
from matplotlib import pyplot as plt
from ..dynamics.ode_solver import OdeSol... | python |
from django.conf.urls.defaults import *
from django.views.generic.simple import redirect_to
import views
urlpatterns = patterns('',
(r'^$', views.home),
# would like to avoid hardcoding mibbinator here
(r'^(o/\.|\.?)(?P<oid>[0-9.]*)$', redirect_to, { 'url': '/mibbinator/o/%(oid)s' }),
(r'^o/(?P<oid>[0-... | python |
# coding=utf-8
# Copyright 2021 The OneFlow 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 require... | python |
# Generated by Django 3.1 on 2020-10-19 16:38
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0013_auto_20201020_0122'),
]
operations = [
migrations.AlterField(
model_name='restaurant',
name='business_num... | python |
from jax import numpy as jnp
from typing import Callable
def weighted_dot(sigma_i: float, sigma_r: float, sigma_b: float) -> Callable:
"""Defines weighed dot product, i.e. <u, v> with u = [i, j]
Returns function which calculates the product given the weights.
"""
def dot(gram: jnp.ndarray, kernel: jn... | python |
import requests,json
from HelperTools import Debug
import os
sourceStreamInfoListUrl = os.getenv('SourceStream')
GetNotFixedStreamAPIUrl = os.getenv("NotFixedStreamAPI")
# 需要做代理的源流信息
sourceStreamInfoList = {}
def GetSourceStreamInfoList():
if sourceStreamInfoListUrl == None or sourceStreamInfoListUrl == "defa... | python |
import pygame as p
import dartboard
import buttonPanel
import statPanel
from dartboard import PERCENTAGES, LASTBULLSEYE
WIDTH = 800
HEIGHT = 700
BACKGROUND = p.Color("red")
MAX_FPS = 30
def main():
global throwing
p.init()
screen = p.display.set_mode((WIDTH, HEIGHT))
screen.fill(BACKGROUND)
p.dis... | python |
import copy
import inspect
import math
import numpy as np
import random
def create_new_children_through_cppn_mutation(pop, print_log, new_children=None, mutate_network_probs=None,
max_mutation_attempts=1500):
"""Create copies, with modification, of existing individuals in t... | python |
import sys
def solution(A):
difference = sys.maxsize
left = 0
right = sum(A)
for i in range(0, len(A)-1):
left += A[i]
right -= A[i]
if abs(right - left) < difference:
difference = abs(right - left)
return difference
def test_solution():
assert solutio... | python |
import json
def readJsonFromFile(filename):
file = open(filename, 'r')
arr = json.loads(file.read())
file.close()
return arr | python |
from enum import Enum
class TaskState(Enum):
# static states:
# a task can either succeed or fail
VALID = 0x0
INVALID = 0x1
# actionable states
DROP = 0x10
DONE = 0x99
class TaskConfigState(Enum):
VALID = 0x0
INVALID = 0x1
| python |
import os
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/tmp/data', one_hot=True)
# Path to Computation graphs
LOGDIR = './graphs'
# Start session
sess = tf.Session()
# Hyper parameters
LEARNING_RATE = 0.01
BATCH_SIZE = 1000
EPOCHS = 10
# Hid... | python |
#:::::::::::::::::::::::::
#::
#:: ProjectDependencies/check.py
#::_______________________
#::
#:: Author: Clement BERTHAUD
#::
#:: MIT License
#:: Copyright (c) 2018 ProjectDependencies - Clément BERTHAUD
#::
#:: Permission is hereby granted, free of charge, to any person obtaining a copy
#:: of this software and asso... | python |
"""
We presume that Channels is operating over a Redis channel_layer here, and use it
explicitly.
"""
from base64 import b64encode
from json import dumps
def message_to_hash(message):
message_hash = b64encode(dumps(message).encode("utf-8"))
return b"semaphore:" + message_hash
async def get_set_message_sema... | python |
"""
Configuration for the integration issues tests
"""
import pytest
@pytest.fixture(scope="package", autouse=True)
def xfail():
pytest.xfail("Issues tests need refactored")
| python |
import argparse
import json
import logging
import os
import subprocess
import tqdm
import wget
from collections import defaultdict
from datetime import datetime
from pathlib import Path
import numpy as np
import torch
import random
def extracting_log_info(log_files, experiment, logging):
metrics_t2v = defaultdict... | python |
#!/usr/bin/env python
from __future__ import print_function
"""
test_split_regex_and_collate.py
"""
JOBS_PER_TASK = 5
import os
tempdir = os.path.relpath(os.path.abspath(os.path.splitext(__file__)[0])) + "/"
import sys
import re
# add grandparent to search path for testing
grandparent_dir = os.path.abspath(os.p... | python |
from django.views.generic import View
from core.models import Cardapio
from django.shortcuts import render
from core.outros.categoriasCardapio import categoriasCardapio
import json
class CardapioView(View):
def get(self, request, *args, **kwargs):
categoria = request.GET.get('categoria')
item_adi... | python |
import argparse
import logging
import os
from sentiment_analysis.src.managers.survey_replies_manager import SurveyRepliesManager
from utils.data_connection.api_data_manager import APISourcesFetcher
from utils.data_connection.source_manager import Connector
from utils.gcloud.nlp_client import NLPGoogleClient
from utils... | python |
import numpy as np
import os
forcing_filename = os.path.join(os.path.dirname(__file__), 'cmip6_solar.csv')
class Forcing:
forcing = np.loadtxt(forcing_filename, skiprows=7, delimiter=',')
year = forcing[:,0]
solar = forcing[:,1]
| python |
import os
import numpy as np
from play_model import PlayModel
class PlayAgent:
def __init__(self, params):
self.parameters = params
os.environ['TF_CPP_MIN_LOG_LEVEL'] = str(self.parameters['tf_log_level']) #reduce log out for tensorflow
self.model = PlayModel(self.parameters)
... | python |
import pytest
import asyncio
from async_v20.client import OandaClient
@pytest.yield_fixture
@pytest.mark.asyncio
async def client():
oanda_client = OandaClient(rest_host='127.0.0.1', rest_port=8080, rest_scheme='http',
stream_host='127.0.0.1', stream_port=8080, stream_scheme='http',... | python |
"""
Defines the blueprint for the auth
"""
import uuid
import datetime
from flasgger import swag_from
from flask import Blueprint, request
from flask.json import jsonify
from flask_bcrypt import generate_password_hash, check_password_hash
from flask_jwt_extended import (create_access_token, get_jwt_identity)
from rep... | python |
import numpy as np
def main():
nx = 2
ny = 3
nz = 4
def do_it(i):
return [i % nx, (i / nx) % ny, i / (nx * ny)]
def undo_it(x, y, z):
# return z + ny * (y + nx * x)
# return x + nx * (x + ny * y)
# return (x * nx * ny) + (y * ny) + z
# return (z * nx * ny... | python |
import utils
import euclides
def esCarmichael(p):
# p > 0
# Retorna cert si p és un nombre de carmichael, fals altrament
i = 1
while i < p:
if euclides.sonCoprimers(i, p):
if utils.potencia_modular_eficient(i, p-1, p) != 1:
return False
i += 1
if i == p:
... | python |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... | python |
#!/usr/bin/env python
# -*- coding: utf8
from __future__ import print_function, division
from pyksc import dist
import glob
import numpy as np
import os
import plac
import sys
def main(tseries_fpath, in_folder):
ids = []
with open(tseries_fpath) as tseries_file:
for l in tseries_file:
id... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Processor for CRGA models"""
import otbApplication
from decloud.core import system
import pyotb
import unittest
from decloud.production import crga_processor
from decloud.production.inference import inference
from .decloud_unittest import DecloudTest
import datetime
d... | python |
#!/usr/bin/env python
# Copyright (c) 2018 Harold Wang, Ryan L. Collins, and the Talkowski Lab
# Distributed under terms of the MIT License (see LICENSE)
# Contact: Ryan L. Collins <rlcollins@g.harvard.edu>
# gnomAD credits: http://gnomad.broadinstitute.org/
"""
Helper script for workflow to calculates B-allele frequ... | python |
"""Lib module for daq sub units"""
pass
| python |
#!/usr/bin/env python
r"""Aggregate, create, and save 1D and 2D histograms and binned plots.
"""
from . import agg_plot
from . import hist1d
from . import hist2d
AggPlot = agg_plot.AggPlot
Hist1D = hist1d.Hist1D
Hist2D = hist2d.Hist2D
# import pdb # noqa: F401
# import logging
# import numpy as np
# import pandas ... | python |
#-- GAUDI jobOptions generated on Mon Oct 12 10:07:37 2020
#-- Contains event types :
#-- 90000000 - 3737 files - 56787251 events - 2862.54 GBytes
#-- Extra information about the data processing phases:
#-- Processing Pass: '/Real Data/Reco14/Stripping21r1'
#-- StepId : 127013
#-- StepName : Stripping21r1-M... | python |
"""
Customized Django model field subclasses
"""
from django.db import models
from django.db.models import fields
from django.db.models.fields.related import ManyToManyField
class CopyFromFieldMixin(fields.Field):
"""
Mixin to add attrs related to COPY FROM command to model fields.
"""
def __init__(se... | python |
# Aula de estrutura de repetição com variavel de controle
for c in range(0, 6):
print('oi')
print('fim')
for a in range(0, 10, 2): # o primeiro argumento e o segundo é o range de contagem, o terceiro é o metodo da contagem
print(a)
print('fim')
# Outro exemplo
for a in range(10, 0, -1): # Com uma condição d... | python |
from __future__ import print_function
from matplotlib import rc
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})
#rc('text', usetex=True)
# generate data
# list of points
from matplotlib.backends.backend_pd... | python |
import sys
import serial
import pprint
import time
import enum
import queue
from queue import Queue
from os.path import join, dirname, abspath
from qtpy.QtCore import Slot, QTimer, QThread, Signal, QObject, Qt, QMutex
class GcodeStates(enum.Enum):
WAIT_FOR_TIMEOUT = 1
GCODE_SENT = 2
READY_TO_SEND = 3
clas... | python |
from urllib.parse import unquote
from flask import Flask
from flask import Response
from flask import abort
from flask import jsonify
from flask import render_template
from flask import request
from flask import send_file
from werkzeug.exceptions import BadRequest
from bootstrapper.lib import archive_utils
from boots... | python |
# stream.models
# Database models for the Activity Stream Items
#
# Author: Benjamin Bengfort <bbengfort@districtdatalabs.com>
# Created: Wed Feb 04 10:24:36 2015 -0500
#
# Copyright (C) 2016 District Data Labs
# For license information, see LICENSE.txt
#
# ID: models.py [70aac9d] benjamin@bengfort.com $
"""
Databa... | python |
# files.py — Debexpo files handling functions
#
# This file is part of debexpo -
# https://salsa.debian.org/mentors.debian.net-team/debexpo
#
# Copyright © 2019 Baptiste Beauplat <lyknode@cilg.org>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associ... | python |
# -*- coding: utf-8 -*-
class BIT:
def __init__(self, size: int) -> None:
self.size = size
self._bit = [0 for _ in range(self.size + 1)]
def add(self, index: int, value: int) -> None:
while index <= self.size:
self._bit[index] += value
index += index & -index
... | python |
"""Mock input data for unit tests."""
from copy import deepcopy
import uuid
# no dependencies
MOCK_BASE_PATH = "a/b/c"
MOCK_DRS_URI = "drs://fakehost.com/SOME_OBJECT"
MOCK_DRS_URI_INVALID = "dr://fakehost.com/SOME_OBJECT"
MOCK_DRS_URI_LONG = (
"drs://aaaaaaaaaaaaaaaaaaaaaaaaaaaa.aaaaaaaaaaaaaaaaaaaaaa"
"aaaaa... | python |
from sikuli import *
import sys
sys.path.insert(0, '/home/vagrant/Integration-Testing-Framework/sikuli/examples')
from test_helper import TestHelper
import open_flex_from_backup, check_change
helper = TestHelper("run_tests_from_backups")
folder = "/home/vagrant/Integration-Testing-Framework/sikuli/examples/images_for_... | python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2020 CERN.
#
# Invenio-Records-Resources is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.
"""File service tests."""
from io import BytesIO
def test_file_flow(
file_service, location... | python |
# -*- coding:utf-8 -*-
from __future__ import unicode_literals
from future.builtins import object
from contextlib import contextmanager
import sys
import unittest
from redis import Redis
from limpyd.database import (RedisDatabase, DEFAULT_CONNECTION_SETTINGS)
TEST_CONNECTION_SETTINGS = DEFAULT_CONNECTION_SETTINGS.... | python |
from .newton_divided_differences import NewtonDifDiv
from .larange import Larange
from .linear_spline import LinearSpline
from .quadratic_spline import QuadraticSpline
from .cubic_spline import CubicSpline
| python |
/*
* Copyright (c) 2020 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ... | python |
from setuptools import setup, find_packages
setup(
name='arranger',
version='1.1.2',
description="moves each file to its appropriate directory based on the file's extension.",
author='j0eTheRipper',
author_email='j0eTheRipper0010@gmail.com',
url='https://github.com/j0eT... | python |
"""
Copyright 2018 Duo Security
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
disclaimer.
2. Redistribut... | python |
from django.apps import AppConfig
class ProntuariomedicoConfig(AppConfig):
name = 'prontuarioMedico'
| python |
"""
Enables the user to add an "Image" plugin that displays an image
using the HTML <img> tag.
"""
from django.conf import settings
from django.core.exceptions import ValidationError
from django.db import models
from django.utils.translation import gettext
from django.utils.translation import gettext_lazy as _
from cm... | python |
import lark
import copy
import torch
class LogicParser:
""" This class defines the grammar of the STL according to
the EBNF syntax and builds the AST accordingly.
"""
_grammar = """
start: prop
prop: VAR CMP (CONST | VAR) -> atom
| _NOT "(" prop ")" -> op_not
| (prop _... | python |
from dash import Input, Output, callback
from dash import dcc
import dash.html as html
import dash_bootstrap_components as dbc
from pages.constants import TITLE_STYLE, PARAGRAPH_STYLE, IMG_STYLE
from utils.topic_crud import TopicCRUD
import plotly.express as px
df = px.data.iris() # iris is a pandas DataFrame
fig = ... | python |
#!/usr/bin/python
class race:
def __init__(self, t):
self.title = t
#ACCESSORS
def titleReturn(self):
return(self.title) | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.