text stringlengths 2 999k |
|---|
# Under MIT License, see LICENSE.txt
class Field():
def __init__(self, ball):
self.ball = ball
def move_ball(self, position, delta):
self.ball.set_position(position, delta)
|
#!/usr/bin/env python
# setup
# Setup script for installing nomen
##########################################################################
## Imports
##########################################################################
import os
import re
import codecs
from setuptools import setup
from setuptools import find... |
from confd_gnmi_adapter import GnmiServerAdapter
class GnmiNetconfServerAdapter(GnmiServerAdapter):
@classmethod
def get_adapter(cls):
pass
def set(self, prefix, path, val):
pass
def get_subscription_handler(self, subscription_list):
pass
def capabilities(self):
... |
# Copyright 2021 The LightSeq Team
# Copyright Facebook Fairseq
# We use layers from Facebook Fairseq as our baseline
import math
import uuid
from typing import Dict, Optional, Tuple, List
import torch
import torch.nn.functional as F
from torch import Tensor, nn
from torch.nn import Parameter, LayerNorm, Dropout, L... |
# Copyright 2021 IBM Corporation
#
# 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 writi... |
#!/usr/bin/env python3
import sys
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right # type: ignore
from collections import Counter, defaultdict, deque # type: ignore
from fractions import gcd # type: ignore
from heapq import heapify, heappop, heappush, heappushpop, heapreplace, ... |
"""Unit test for KNX time objects."""
import unittest
from xknx.dpt import DPTTime, DPTWeekday
from xknx.exceptions import ConversionError
class TestDPTTime(unittest.TestCase):
"""Test class for KNX time objects."""
#
# TEST NORMAL TIME
#
def test_from_knx(self):
"""Test parsing of DPTTi... |
# Copyright (c) 2019-present, The Johann Authors. All Rights Reserved.
# Use of this source code is governed by a BSD-3-clause license that can
# be found in the LICENSE file. See the AUTHORS file for names of contributors.
"""Johann, lightweight and flexible scenario orchestration"""
__version__ = "0.3.0-alpha"
|
from o3seespy.base_model import OpenSeesObject
class LayerBase(OpenSeesObject):
op_base_type = "layer"
class Straight(LayerBase):
"""
The Straight Layer Class
The layer command is used to generate a number of fibers along a line or a circular arc.
"""
op_type = 'straight'
def __ini... |
# BirdWeather edits by @timsterc
# Other edits by @CaiusX and @mcguirepr89
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
os.environ['CUDA_VISIBLE_DEVICES'] = ''
try:
import tflite_runtime.interpreter as tflite
except:
from tensorflow import lite as tflite
import argparse
import operator
import librosa
im... |
import json
import os
os.environ["system_file"] = "./tests/testing_data/system.yaml"
from typing import Dict, Text, Any, List
import pytest
import responses
from mongoengine import connect, disconnect
from rasa_sdk import Tracker
from rasa_sdk.executor import CollectingDispatcher
from kairon.action_server.data_object... |
from datetime import date
ano = int(input('ANO de nascimento : '))
ano_hoje = date.today().year
cont = ano_hoje - ano
if cont > 20 :
print(' Quem nasceu em {} tem {} anos em {} . '.format(ano, cont, ano_hoje))
print(' Sua classificação é MASTER. ')
elif cont == 20 :
print(' Quem nasceu em {} tem ... |
from distutils.core import setup
setup(
name='upprint',
packages=['upprint'],
version='0.1',
description='Modified version of pprint with better Unicode output',
author='Michiel Sikma',
author_email='michiel@sikma.org',
url='https://github.com/msikma/upprint',
download_url='https://gith... |
from pathlib import Path
from copy import deepcopy
import pytest
from gretel_synthetics.config import BaseConfig
import gretel_synthetics.tokenizers as tok
class SimpleConfig(BaseConfig):
"""Used for simple tokenization tests
"""
def get_generator_class(self):
return None
def get_training... |
#!/usr/bin/env python
# encoding: utf-8
"""
Test problem demonstrating 3D hot-sphere rising in an stabilized atmosphere
in Cartesian coordinates
This problem evolves the 3D Euler equations using an F-wave
method, with gravitational source term modifications.
The primary variables are:
density (rho), x,y, a... |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... |
import asyncio
import base64
import threading
import cv2
import numpy as np
from flask_socketio import SocketIO, emit
from flask import Flask, render_template
import multiprocessing
class Streamer():
def __init__(self) -> None:
"""Constructor
"""
@staticmethod
async def stream_s... |
# coding=utf-8
"""
@author: magician
@date: 2018/9/14
"""
import datetime
from flask_sqlalchemy import SQLAlchemy
from flask import Flask, jsonify, request
from sqlalchemy.exc import IntegrityError
from marshmallow import Schema, fields, ValidationError, pre_load
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_... |
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import unittest, frappe, pyotp
from werkzeug.wrappers import Request
from werkzeug.test import EnvironBuilder
from frappe.auth import HTTPRequest
from frappe.utils import cint
fro... |
from conans import ConanFile, tools, AutoToolsBuildEnvironment
from conans.errors import ConanInvalidConfiguration
from contextlib import contextmanager
import os
import shutil
class SwigConan(ConanFile):
name = "swig_installer"
version = "4.0.1"
description = "SWIG is a software development tool that con... |
"""
WSGI config for pv project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` setti... |
"""This example demonstrates the usage of ZOOptSearch.
It also checks that it is usable with a separate scheduler.
"""
import time
from ray import tune
from ray.tune.suggest.zoopt import ZOOptSearch
from ray.tune.schedulers import AsyncHyperBandScheduler
from zoopt import ValueType # noqa: F401
def evaluation_fn(s... |
import urllib
import jose.jwt
import time
import random
import sys
import requests
from flask import Flask, request, redirect, make_response, jsonify
import subprocess
# seconds until the token expires
TOKEN_EXPIRES = 2
# A mocked out oauth server, which serves all the endpoints needed by the oauth type.
class MockO... |
# 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... |
# boot.py -- runs on boot-up
import pyb
pyb.LED(3).on() # indicate we are waiting for switch press
pyb.delay(2000) # wait for user to maybe press the switch
switch_value = pyb.Switch()() # sample the switch at end of delay
pyb.LED(3).off() # indicate that we finished w... |
from Cimpl import *
image = load_image(choose_file())
def flip_vertical(image: image) -> Image:
vertical_image = copy(image)
for x in range(get_width(image)):
for y in range(get_height(image)):
flipped_color = get_color(image, -x, y)
set_color(vertical_image, x,... |
import BlockCorr
import numpy as np
N = 100
D = 1000
np.random.seed(0)
### WITHOUT CLUSTERS ###
foo = np.random.rand(N, D)
foo_corr = BlockCorr.PearsonTriu(foo)
membs = range(N)
dists = BlockCorr.Loss(foo_corr, foo_corr, membs, True)
print "Identity clustering"
print "--- output ", dists
print "+++ must be (0.0, 0... |
import boto3
import json
import logging
from crhelper import CfnResource
logger = logging.getLogger(__name__)
helper = CfnResource(
json_logging=False, log_level='DEBUG', boto_level='CRITICAL')
try:
sc = boto3.client("servicecatalog")
except Exception as e:
helper.init_failure(e)
def get_parameters(even... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2017 LE GOFF Vincent
# 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
# ... |
# coding=utf-8
import os
import sys
from dateutil import parser
from datetime import datetime
from pytz import timezone
import re
import datetime
import dateutil.parser
from datetime import timedelta
def modify_test_data(initial_data):
# set user name
# initial_data['procuringEntity']['name'] = u'Товариство ... |
#!/usr/bin/env python3
# SPDX-License-Identifier: Apache-2.0
##
# Copyright (C) 2021 Jihoon Lee <jhoon.it.lee@samsung.com>
#
# @file genModelsRecurrent_v2.py
# @date 19 October 2021
# @brief Generate recurrent model tcs
# @author Jihoon lee <jhoon.it.lee@samsung.com>
from recorder_v2 import record_v2, inspect_file
fro... |
import json
import pathlib
import urllib.request
def main():
# https://gist.github.com/kawanet/a880c83f06d6baf742e45ac9ac52af96
url = 'https://gist.githubusercontent.com/kawanet/a880c83f06d6baf742e45ac9ac52af96/raw' \
'/b4fbc9a730394eb977277e73cc37b60955463f21/material-colors.json'
json... |
# %% Import packages
from eeyore.samplers import HMC
from bnn_mcmc_examples.examples.mlp.pima.setting1.dataloaders import training_dataloader
from bnn_mcmc_examples.examples.mlp.pima.setting1.model import model
# %% Setup HMC sampler
sampler = HMC(model, theta0=model.prior.sample(), dataloader=training_dataloader, ... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.7 on 2016-08-04 05:09
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('tournament', '0048_auto_20160803_0311'),
]
operations = [
migrations.AddField(
... |
##############################################
# #
# Ferdinand 0.40, Ian Thompson, LLNL #
# #
# gnd,endf,fresco,azure,hyrma #
# #
#####################################... |
""" Generic script for monitoring counts from a counter """
import numpy as np
import time
import pyqtgraph as pg
from pylabnet.gui.pyqt.external_gui import Window
from pylabnet.utils.logging.logger import LogClient
from pylabnet.scripts.pause_script import PauseService
from pylabnet.network.core.generic_server import... |
# Generated by Django 2.1.15 on 2020-02-16 11:10
# flake8: noqa
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_max_length'),
]
operations = [
migrations.CreateModel(
name... |
## Message passing over a discrete BN ##
## Library created by Pablo Martínez Olmos, University Carlos III Madrid ##
## olmos@tsc.uc3m.es ##
## Last modification 15/11/2016 ##
import numpy as np
## Messages are stored in the logaritmic domain ##
## Global constants (to control numerical issues)
inf_log=100 #To impo... |
from six import text_type
from rest_framework import HTTP_HEADER_ENCODING, exceptions
from django.core.exceptions import PermissionDenied
from django.utils.translation import ugettext_lazy as _
from atlassian_connect_django.models.connect import AtlassianUser
from atlassian_connect_django import helpers
from .models i... |
#!/usr/bin/env python
import uuid
from construct import Container
class SMAPI_Request(object):
'''
Implentation of a ICUV Request
'''
def __init__(self, function_name, target_identifier,
authenticated_userid=b"", password=b"", additional_parameters=b""):
self._function_n... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010-2016 PPMessage.
# Guijin Ding, dingguijin@gmail.com
#
from ppmessage.core.constant import IOS_FAKE_TOKEN
from ppmessage.core.constant import CONVERSATION_TYPE
from ppmessage.core.constant import MESSAGE_SUBTYPE
from ppmessage.core.constant import MESSAGE_STATUS
from ppmes... |
#!/usr/bin/env python
#
# author: syl20bnr (2013)
# goal: Focus the nth window in the current workspace (limited to 10 firsts)
#
# Example of usage in i3 config:
#
# bindsym $mod+0 exec focus_win.py -n 0
# bindsym $mod+1 exec focus_win.py -n 1
# ... ...
# bindsym $mod+8 exec focus_win.py -n 8
# binds... |
import os
print os.path |
import datetime
from jasonpi.normalizers import facebook_profile, google_profile
def test_facebook_profile():
"""
Test that facebook_profile computes
a correct profile received from facebook oauth.
"""
data = {
'email': 'some@email.com',
'first_name': 'Alfred',
'last_name'... |
# x_6_8
#
#
class StockError(Exception):
pass
class NumberError(Exception):
pass
order_count = input('きび団子を何個注文しますか?:')
card_number = input('カード番号を入力してください?(例、0000-0000-0000-0000):')
try:
if int(order_count) > 100:
raise StockError
if card_number != '1111-1111-1111-1111':
raise Num... |
# Copyright (c) 2016-2017, Neil Booth
#
# All rights reserved.
#
# See the file "LICENCE" for information about the copyright
# and warranty status of this software.
'''Class for handling asynchronous connections to a blockchain
daemon.'''
import asyncio
import itertools
import json
import time
import aiohttp
from a... |
# Generated by Django 2.2.4 on 2020-06-21 18:32
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='task',
fields=[
('id', mode... |
"""
The :mod:`sportsbet.datasets` module provides the
tools to download and transform sports betting data.
"""
from ._base import load
from ._soccer._combined import SoccerDataLoader
from ._soccer._fd import FDSoccerDataLoader
from ._soccer._fte import FTESoccerDataLoader
from ._soccer._dummy import DummySoccerDataLoa... |
import logging
import os
import urllib
from markupsafe import escape
import paste.httpexceptions
from six import string_types, text_type
from sqlalchemy import false, true
from galaxy import datatypes, model, util, web
from galaxy import managers
from galaxy.datatypes.display_applications.util import decode_dataset_u... |
#===============================================================================
# Copyright 2020-2021 Intel Corporation
#
# 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.apa... |
'''
Created by auto_sdk on 2020.08.19
'''
from dingtalk.api.base import RestApi
class OapiAtsChannelAccountAddRequest(RestApi):
def __init__(self,url=None):
RestApi.__init__(self,url)
self.biz_code = None
self.channel_user_identify = None
self.userid = None
def getHttpMethod(self):
return 'POST'
def geta... |
#!/usr/bin/python3
"""
Unit Test for api v1 Flask App
"""
import inspect
import pep8
import web_flask
import unittest
from os import stat
web_flask = __import__('web_flask.2-c_route', globals(), locals(), ['*'])
class TestCRouteDocs(unittest.TestCase):
"""Class for testing Hello Route docs"""
all_funcs = ins... |
from genologics.lims import Lims
from genologics.config import BASEURI, USERNAME, PASSWORD
from multiqc.utils import report, config
from multiqc.modules.base_module import BaseMultiqcModule
from multiqc.plots import table
from collections import OrderedDict
import logging
import re
class MultiQC_clarity_metadata(Ba... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
with open("README.rst", "rt") as inf:
readme = inf.read()
ver_dic = {}
with open("cgen/version.py") as version_file:
version_file_contents = version_file.read()
exec(compile(version_file_contents, "cgen/version.py", 'exec'), ver_dic)... |
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework 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
... |
import cv2
import numpy as np
import time
'''
TEST FILE using 1000, 1000 output image.
Actual code will have an output image of 200,200, which also means a different homography
'''
#recalculated homography
# homography_front = np.array([[3.12570133882145e-05, 0.000286172662353515, -0.680179732686621],
# [0.0... |
from flask_wtf import Form
from wtforms import TextField, PasswordField
from wtforms.validators import (Required, Length, Email, ValidationError,
EqualTo)
from app.models import User
class Unique(object):
'''
Custom validator to check an object's attribute
is unique. For e... |
# Call Domain api here |
#! /usr/bin/env python3
#
# makesedonac.py
#
# Compile sedonac.jar
#
# Author: Brian Frank
# Creation: 7 Dec 07
#
from __future__ import print_function
import os
import env
import compilejar
depends = [env.sedonaJar]
srcDir = os.path.join(env.src, "sedonac", "src")
jarFile = env.sedonacJar
package... |
from edsa_packages import recursion, sorting
#Recursion tests
def test_sum_array():
'''
Make sure sum_array works
'''
assert recursion.sum_array([8, 3, 2, 7, 4]) == 24, 'incorrect'
assert recursion.sum_array([5, 7, 8, 8, 6, 3, 4]) == 41, 'incorrect'
assert recursion.sum_array([25, 14, 2, 3, 5]... |
# Copyright 2013 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" file acc... |
import datetime
from http import HTTPStatus
from locust import HttpUser, task, between
# This test can be run after installing locust through the cli as "locust --host=http://<deployed_host>:<port>"
# Then url http://localhost:8089/ should be access to start the test.
# Can also be run using no UI mode as "locust --no... |
import json
import sys
from os import path
header_comment = '# %%\n'
def nb2py(notebook):
result = []
cells = notebook['cells']
for cell in cells:
cell_type = cell['cell_type']
if cell_type == 'markdown':
result.append('%s"""\n%s\n"""'%
(header_comm... |
import numpy as np
import time
import matplotlib.pyplot as plt
from pymc3 import Model, Normal, HalfNormal, find_MAP
from scipy import optimize
start_time = time.time()
# Initialize random number generator
np.random.seed(123)
# True parameter values
alpha, sigma = 1, 1
beta = [1, 2.5]
# Size of dataset
size = 100
... |
import sys
input_file = open(sys.argv[1])
input_lines = input_file.readlines()
total_wrapping = 0
total_ribbon = 0
for line in input_lines:
l, w, h = line.split("x")
l = int(l)
w = int(w)
h = int(h)
dimensions = [l, w, h]
min_1 = min(dimensions)
dimensions.remove(min_1)
min_2 = min(... |
import io
import json
import gzip
from base64 import b64decode
from http.cookies import SimpleCookie
import chardet
import rfc3986
import graphene
import yaml
from requests.structures import CaseInsensitiveDict
from requests.cookies import RequestsCookieJar
from starlette.datastructures import MutableHeaders
from sta... |
# Copyright 2018
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# ... |
from __future__ import unicode_literals
import datetime
import decimal
from collections import defaultdict
from django.contrib.auth import get_permission_codename
from django.core.exceptions import FieldDoesNotExist
from django.core.urlresolvers import NoReverseMatch, reverse
from django.db import models
from django.... |
# -*- coding: utf-8 -*-
import collections
import functools
import os
import struct
import sys
import types as pytypes
import uuid
import weakref
from copy import deepcopy
from numba import _dispatcher
from numba.core import utils, types, errors, typing, serialize, config, compiler, sigutils
from numba.core.compiler... |
#!/bin/env python
import sys
import unittest
from unittest.mock import Mock
from unittest.mock import patch
from textwrap import dedent
ats_mock = Mock()
with patch.dict('sys.modules',
{'ats' : ats_mock}, autospec=True):
import genie.parsergen
from genie.parsergen import oper_fill
from genie.parse... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Author: Li Yuanming
Email: yli056@e.ntu.edu.sg
Date: 1/27/2021
ML model structure definitions.
"""
import abc
import inspect
from enum import Enum
from typing import Optional, Union, Tuple, Dict, OrderedDict
from pydantic import BaseModel, PositiveInt, conint, Positiv... |
"""
Author: Andrew Harris
Python 3.8
"""
import logging
import os
import pandas as pd
from ete3 import Tree
from tqdm import tqdm
############################### Set up logger #################################
def set_logger_level(WORKING_DIR, LOG_LEVEL):
logger = logging.getLogger(__name__)
# Remove existing ... |
#!/usr/bin/env python2.7
# -*- coding: utf-8 -*-
####################################################################################
### Copyright (C) 2015-2019 by ABLIFE
####################################################################################
#########################################################... |
# this file structure follows http://flask.pocoo.org/docs/1.0/patterns/appfactories/
# initializing db in api.models.base instead of in api.__init__.py
# to prevent circular dependencies
from .base import db
from .Email import Email
from .Person import Person
from .VideoInfo import VideoInfo
__all__ = ["db", "Email", ... |
"""
The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).
https://creativecommons.org/licenses/by/4.0/
https://creativecommons.org/licenses/by/4.0/legalcode
Copyright (c) COLONOLNUTTY
"""
from typing import Any, Union
from interactions.base.inter... |
# -*- coding: utf-8 -*-
# Copyright 2016 The TensorFlow 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
#
# Un... |
#!/usr/bin/env python
""" Maps point charges obtained by GPAW and HORTON on the original'
' GROMACS topology initially modified by insertHbyList.py """
## jlh 2018/04/02
import ast
import h5py
import ase.io
from ase.io.cube import read_cube_data
import parmed as pmd
from parmed import gromacs
from insertHby... |
"""
This module contains the formulas for comparing Lab values with matrices
and vectors. The benefit of using NumPy's matrix capabilities is speed. These
calls can be used to efficiently compare large volumes of Lab colors.
"""
import numpy
def delta_e_cie1976(lab_color_vector, lab_color_matrix):
"""
Calcul... |
import os
import webbrowser
import time
import random
import requests
from bs4 import BeautifulSoup
from prettytable import PrettyTable
from time import sleep
cont = 1
print("Welcome to Qp Bank !")
sleep(1)
print("Crafted with love by Mathan.S")
sleep(1)
print("Ensure your connectivity to Amrita Wifi f... |
from __future__ import annotations
from .data_structures import Stack
from .operation import Operation
class HistoryManager:
def __init__(self):
self.undo_stack: Stack[Operation] = Stack()
self.redo_stack: Stack[Operation] = Stack()
def add_operation(self, operation_instance: Operation):
... |
import plotly.graph_objects as go
from mainapp.app_settings import cell_length_meter
def getLineChart(
data,
timestamp,
coordinates,
colorScale,
timeline,
color_range,
dragmode=False,
quick_select_range=True,
calibration_time=None,
show_... |
from __future__ import absolute_import
from sentry.testutils import TestCase
from sentry.api.fields.actor import Actor
from sentry.models import ProjectOwnership, User, Team
from sentry.models.projectownership import resolve_actors
from sentry.ownership.grammar import Rule, Owner, Matcher, dump_schema
class ProjectO... |
import os
import time
# os.system("adb shell monkey -p com.xingin.xhs -c android.intent.category.LAUNCHER 1")
# os.system("sleep 4")
# os.system("adb shell input tap 1000 150")
# os.system("sleep 2")
# os.system("adb shell input text PUCO")
# os.system("sleep 2")
# os.system("adb shell input tap 1000 150")
# os.system... |
import os
import helpers
import numpy
import pytest
import toughio
write_read = lambda output, writer_kws, reader_kws: helpers.write_read(
"output",
output,
toughio.write_output,
toughio.read_output,
writer_kws=writer_kws,
reader_kws=reader_kws,
)
@pytest.mark.parametrize(
"filename, da... |
#Question Link
#https://www.codechef.com/problems/XORAGN
t=int(input())
for a0 in range(t):
n=int(input())
a=list(map(int,input().split()))
res=0
for i in a:
res=res^i #xorring all the values present
print(2*res) #doubling the result obtained
|
import control as ctl
import numpy as np
def damp(sys,display=False):
pole_list = []
m_list = []
wn_list = []
for pole in sys.pole():
pole = pole.astype(complex) # WTF: the python control "damp" function is buggy due to this missing cast !
if ctl.isctime(sys):
pole_continu... |
#
# 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... |
import logging
from abc import abstractmethod
from dataclasses import dataclass, field
from typing import Any, Dict, Iterable, List, Optional, Set, Tuple, Type
from urllib.parse import quote_plus
import pydantic
from sqlalchemy import create_engine, inspect
from sqlalchemy.engine.reflection import Inspector
from sqlal... |
""" Test script for the Unicode implementation.
Written by Marc-Andre Lemburg (mal@lemburg.com).
(c) Copyright CNRI, All Rights Reserved. NO WARRANTY.
"""
import _string
import codecs
import itertools
import operator
import struct
import string
import sys
import unittest
import warnings
from test import support, str... |
#!/usr/bin/env python
# Copyright 2016 Tesora, 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 law ... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team 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 ... |
def lend_money(debts, person, amount):
value = debts.get(person, 0)
quantity = [amount]
if value != 0:
debts[person] = value + quantity
else:
debts[person] = quantity
print(debts)
def amount_owed_by(debts, person):
value = debts.get(person, [0])
out = sum(va... |
from __future__ import print_function
from sklearn import datasets
import matplotlib.pyplot as plt
import numpy as np
from scratchML.supervised_learning import LDA
from scratchML.utils import calculate_covariance_matrix, accuracy_score
from scratchML.utils import normalize, standardize, train_test_split, Plot
from scr... |
from setuptools import find_packages, setup
def get_version():
version = {}
with open("dagster_papertrail/version.py") as fp:
exec(fp.read(), version) # pylint: disable=W0122
return version["__version__"]
if __name__ == "__main__":
setup(
name="dagster-papertrail",
version=... |
# -*- coding: utf-8 -*-
#
# Django Ratelimit documentation build configuration file, created by
# sphinx-quickstart on Fri Jan 4 15:55:31 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file... |
import sys, os, re
from setuptools import setup, Command, find_packages
from setuptools.command.test import test
class CleanCommand(Command):
"""Custom clean command to tidy up the project root."""
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
... |
import logging
import re
import pytest
import yaml
from tests.common.helpers.assertions import pytest_assert
from tests.common.helpers.platform_api import chassis
from platform_api_test_base import PlatformApiTestBase
logger = logging.getLogger(__name__)
pytestmark = [
pytest.mark.disable_loganalyzer, # disab... |
import logging
from typing import Optional, Any
from opentrons import types
from opentrons.calibration_storage import get
from opentrons.calibration_storage.types import TipLengthCalNotFound
from opentrons.hardware_control.dev_types import PipetteDict
from opentrons.protocol_api.labware import Labware, Well
from opent... |
from django.contrib import admin
from .models import CookiePageText, TOSPageText, StatutPageText
# Register your models here.
class CookieAdmin(admin.ModelAdmin):
pass
class TOSPageTextAdmin(admin.ModelAdmin):
pass
class StatutPageTextAdmin(admin.ModelAdmin):
pass
admin.site.register(CookiePageText, Cooki... |
"""
We want to simplify the operations for pandas dataframes assuming we are using timeseries as the main objects.
When we have multiple timeseries, we will:
1) calculate joint index using df_index()
2) reindex each timeseries to the joint index
We then need to worry about multiple columns if there a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.