text stringlengths 1 927k |
|---|
'''
Created on 28 Jun 2015
@author: a
'''
class SettingsConstants(object):
'''
Constants related to settings dialogs
'''
SETTINGS_ITEM_HISTORY_HEADERS = ["Item", "Date", "Action", "Details", "User", "Version", "Build date"] |
import sys
import json
import base64
from pprint import pprint
epoch = ["ENCRYPTION_INITIAL", "ENCRYPTION_0RTT", "ENCRYPTION_UNKNOWN", "ENCRYPTION_1RTT"]
def transform(inf, outf):
start = -1
cid = -1
qtr = {}
qtr["protocolVersion"] = "AAAA"
qtr["events"] = []
packet = {}
sframes = []
r... |
import os
import os.path
import re
import shutil
import mlflow
from mlflow import cli
from mlflow.utils import process
from tests.integration.utils import invoke_cli_runner
import pytest
import json
import hashlib
EXAMPLES_DIR = "examples"
def hash_conda_env(conda_env_path):
# use the same hashing logic as `_ge... |
"""
A triangle is an "almost right triangle" if one of its angles differs from
90 degrees by at most 15 degrees. A triangle is an "almost isosceles
triangle" if two of its angles differ from each other by at most 15
degrees. Prove that all acute triangles are either almost right or almost
isosceles.
Note: if "at most ... |
# Copyright 2018-2022 Streamlit 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 or agreed to in wr... |
def main():
s = input()
if len(set(s)) == 1:
print('Weak')
return
*s, = map(int, list(s))
for i in range(3):
if (
s[i + 1]
!= (s[i] + 1) % 10
):
print('Strong')
return
print('Weak')
main() |
def get_dataset(dataset_name):
if dataset_name == 'cornell':
from .cornell_data import CornellDataset
return CornellDataset
elif dataset_name == 'jacquard':
from .jacquard_data import JacquardDataset
return JacquardDataset
elif dataset_name == 'rs_dir':
from .rs_dir_data... |
import soulstruct.emevd.ds_types as dt
class CHR(dt.Character):
Rickert = 6220
Sif = 1600452
MaleGhost1 = 1600200
MaleGhost2 = 1600201
MaleGhost3 = 1600301
MaleGhost4 = 1600302
FemaleGhost = 1600300
class SPEFFECT(dt.IntEnum):
RingOfTheAlpha = 4704
SifReward = 4807
class FLAG(d... |
"""
Exports the embeddings of a directory of images as numpy arrays.
Following structure:
D:\images:
folder1:
img_0
...
img_74
folder2:
img_0
...
img_74
Output:
embeddings.npy -- Embeddings as np array (with names "... |
# Auto-generated at 2021-09-27T17:12:38.713844+08:00
# from: Justice Basic Service (1.17.0)
# Copyright (c) 2018 - 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
# pylint: disable=duplicate-code
# pylin... |
import datetime
import errno
import os
import time
from collections import defaultdict, deque
import torch
import torch.distributed as dist
class SmoothedValue:
"""Track a series of values and provide access to smoothed values over a
window or the global series average.
"""
def __init__(self, window... |
#
# 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... |
class Node:
def __init__(self, parent, rank=0, size=1):
self.parent = parent
self.rank = rank
self.size = size
def __repr__(self):
return '(parent=%s, rank=%s, size=%s)' % (self.parent, self.rank, self.size)
class Forest:
def __init__(self, num_nodes):
self.nodes = ... |
import time
from typing import Callable
import pandas as pd
from datetime import datetime
from vnpy.event import EventEngine
from vnpy.trader.constant import Exchange, Interval
from vnpy.trader.engine import BaseEngine, MainEngine
from vnpy.trader.object import BarData
from vnpy.trader.utility import get_folder_path
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# morphforge documentation build configuration file, created by
# sphinx-quickstart on Fri Mar 23 14:01:08 2012.
#
# 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
# autoge... |
# Copyright 2008 by Peter Cock. All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
"""Tests for AlignIO module."""
import unittest
import warnings
from io import StringIO
from Bio... |
import dash_bootstrap_components as dbc
from dash import Input, Output, State, html
offcanvas = html.Div(
[
dbc.Button(
"Open scrollable offcanvas",
id="open-offcanvas-scrollable",
n_clicks=0,
),
dbc.Offcanvas(
html.P("The contents on the main... |
log_level = 'INFO'
load_from = None
resume_from = None
dist_params = dict(backend='nccl')
workflow = [('train', 1)]
checkpoint_config = dict(interval=10)
evaluation = dict(
interval=10, metric=['PCKh', 'AUC', 'EPE'], key_indicator='AUC')
optimizer = dict(
type='Adam',
lr=5e-4,
)
optimizer_config = dict(gra... |
__author__ = 'patras'
from domain_searchAndRescue import *
from timer import DURATION
from state import state
def GetCostOfMove(r, l1, l2, dist):
return dist
DURATION.TIME = {
'giveSupportToPerson': 15,
'clearLocation': 5,
'inspectPerson': 20,
'moveEuclidean': GetCostOfMove,
'moveCurved': GetC... |
from dash import Input, Output, callback, html, dcc, State
import dash_bootstrap_components as dbc
import pandas as pd
import numpy as np
import plotly.express as px
import plotly.io as pio
import plotly.graph_objects as go
from urllib.request import urlopen
import json
df_all = pd.read_csv(
"data/Primary-energy... |
"""Define meta information about the pagecap package."""
__title__ = 'pagecap'
__version__ = '0.0.7'
__description__ = ('Capture specified URLs as PNG image files')
__url__ = 'https://github.com/stratofax/pagecap'
__author__ = 'Neil Johnson'
__author_email__ = 'neil@cadent.com'
__license__ = 'MIT'
__copyright__ = 'Cop... |
import logging
import subprocess
from copy import deepcopy
from datetime import datetime
from pathlib import Path
import click
import coloredlogs
LOG_LEVELS = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"]
LOG = logging.getLogger(__name__)
@click.command()
@click.option("-d", "--directory", default=".", help="S... |
from typing import Tuple
from .cogs import Cog, EmptyCog, Player
from .special_cogs import BoostedCog
import numpy as np
class Board:
def __init__(self, height: int = 8, width: int = 12, locked: bool = True) -> None:
self._visualization_board = ''
self.board = np.array([[EmptyCog() for w in range(w... |
# Copyright (c) 2001-2004 Twisted Matrix Laboratories.
# See LICENSE for details.
#
"""
A basic ASN.1 parser to parse private SSH keys.
Maintainer: Paul Swartz
"""
from Crypto.Util import number
def parse(data):
things = []
while data:
t = ord(data[0])
assert (t & 0xc0) == 0, 'not a univer... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import glob
from shutil import copyfile
import hashlib
import json
import sys
import subprocess
import logging
from multiprocessing import Pool
import pdb
import time
import pickle
import argparse
import numpy as np
import pandas as pd
import pydicom as dicom
i... |
# Test for one implementation of the interface
from lexicon.providers.dnspod import Provider
from integration_tests import IntegrationTests
from unittest import TestCase
import pytest
# Hook into testing framework by inheriting unittest.TestCase and reuse
# the tests which *each and every* implementation of the interf... |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def NotImplemented(vim, *args, **kwargs):
'''NotImplemented exception is thrown if the met... |
"""
Special Pythagorean triplet.
A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
a**2 + b**2 = c**2
For example, 3**2 + 4**2 = 9 + 16 = 25 = 5**2.
There exists exactly one Pythagorean triplet for which a + b + c = 1000.
Find the product abc.
"""
from datetime import datetime
from fun... |
import asyncio
import inspect
from typing import Any, Callable, Dict, List, Optional, Sequence, Set, Type, Union
from fastapi import params
from fastapi.dependencies.models import Dependant
from fastapi.dependencies.utils import (
get_body_field,
get_dependant,
get_parameterless_sub_dependant,
solve_de... |
import logging
import time
from relation_engine_bulk_update.loader import RELoader
WS_OBJ_DELIMITER = ":"
def _timestamp_to_epoch(timestamp):
return int(time.mktime(time.strptime(timestamp, "%Y-%m-%dT%H:%M:%S%z")))
def update_ws_object_collections(ws_client, re_api_url, token, params):
"""Update all works... |
import logging
class NullHandler(logging.Handler):
"""
Workaround to support Python 2.6
NullHandler was officially added to the logging package in Python 2.7
"""
def emit(self, record):
pass
class MockHandler(logging.Handler):
def __init__(self, *args, **kwargs):
self.reset(... |
from django.db import models
class Event(models.Model):
name = models.CharField(max_length=255)
date = models.DateField()
description = models.CharField(max_length=255)
class EventRepo:
@staticmethod
def list():
return Event.objects.all()
@staticmethod
def get(id):
retur... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Hashtagcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test rpc http basics
#
from test_framework.test_framework import HashtagcoinTestFramework
from t... |
import RPi.GPIO as GPIO
LED = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED, GPIO.OUT)
pwm = GPIO.PWM(LED, 100)
pwm.start(0)
try:
while True:
pwm.ChangeDutyCycle(50)
except:
pwm.stop()
GPIO.cleanup() |
import os, sys, platform
from os.path import join, dirname, abspath, basename
import unittest
def add_to_path():
"""
Prepends the build directory to the path so that newly built pypyodbc libraries are used, allowing it to be tested
without installing it.
"""
# Put the build directory into the Pytho... |
import os
import hashlib
import hmac
import time
import orjson
import requests
import extra_math
URL = "https://api.valr.com"
VERSION = "/v1"
previous_signatures = set()
# As copied from VALR API example
def gen_signature(api_key_secret, timestamp, verb, path, body=""):
"""
Signs the request payload using... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. 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 cop... |
''' Evaluating Frustum PointNets.
Write evaluation results to KITTI format labels.
and [optionally] write results to pickle files.
Author: Charles R. Qi
Date: September 2017
'''
from __future__ import print_function
import os
import sys
import argparse
import importlib
import numpy as np
import tensorflow as tf
impor... |
"""
Copyright (C) 2017-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.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
import numpy as np
from astropy.io import fits
from scipy.interpolate import RectBivariateSpline
def index_PSF(PSF, x, y):
return PSF[x+y*3]
def get_native_PSF(filt, x, y, the_path):
x = float(np.clip(x, 0, 1014))
y = float(np.clip(y, 0, 1014))
f = fits.open("%sPSFSTD_WFC3IR_%s.fits" % (the_path, fil... |
import argparse
import os, sys
from SensorData import SensorData
# params
parser = argparse.ArgumentParser()
# data paths
parser.add_argument('--filename', required=True, help='path to sens file to read')
parser.add_argument('--output_path', required=True, help='path to output folder')
parser.add_argument('--export_d... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
import logging
import os
from logging.handlers import SMTPHandler, RotatingFileHandler
from flask_mail import Mail
from config import Config
app =... |
import math
from datetime import datetime, timedelta
import sys
from airflow.models import Variable
import pandas as pd
import numpy as np
sys.path.insert(0, '/home/curw/git/DSS-Framework/db_util')
# sys.path.insert(0, '/home/hasitha/PycharmProjects/DSS-Framework/db_util')
from gen_db import CurwFcstAdapter, CurwObsAd... |
#!/bin/env python
import json, os, sys, us, area, re
import data_index
import mapzen.whosonfirst.geojson
import mapzen.whosonfirst.utils
script = os.path.realpath(sys.argv[0])
scripts_dir = os.path.dirname(script)
root_dir = os.path.dirname(scripts_dir)
source_path = "%s/sources/congress_districts_116_pa/congress_di... |
import logging
import cvxpy as cvx
import numpy as np
from numpy.linalg import norm
from tqdm import tqdm
class MaxMarginAbbeel(object):
"""
implementation of (Abbeel & Ng 2004)
two versions: available
1. max-margin (stable, computationally more heavy)
2. projection (simpler)
"""
def ... |
#!/usr/bin/env python
import numpy as np
from numpy import *
import os
import rospy
from ars_sim_obstacles_detector_ros import *
def main():
ars_sim_obstacles_detector_ros = ArsSimObstaclesDetectorRos()
ars_sim_obstacles_detector_ros.init()
ars_sim_obstacles_detector_ros.open()
try:
ars_sim_obs... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import six
try:
from mock import patch
except ImportError:
from unittest.mock import patch
from csvkit.utilities.csvlook import CSVLook, launch_new_instance
from tests.utils import CSVKitTestCase, EmptyFileTests, stdin_as_string
class TestCSVLook(CS... |
from .base import *
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': get_env_variable('DB_NAME'),
'USER': get_env_variable('DB_USER'),
'PASSWORD': get_env_variable('DB_PASSWO... |
#!/usr/bin/python
#
# Copyright 2018-2021 Polyaxon, 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 ... |
import math
import scipy
import csv
class EntropyModel:
def training_to_bigrams(self, training):
"""
Transform a list of training instances into a list of bigrams.
Each training instance X is changed to bXe.
'b' denotes the start symbol.
'e' denotes the end symbol
... |
import json
from urllib.request import urlopen
import atexit
import datetime
import dateutil
import sys
import tda
API_KEY = 'FON1HLNGRN0KOVR6UDTCF4RPEMPYIXOB@AMER.OAUTHAP'
REDIRECT_URI = 'http://localhost:8080/'
TOKEN_PATH = '../access_token'
def save_to_file(data):
"""
Save to file for testing
"""
with... |
import unittest
import pprint
from atlascli.atlasapi import AtlasAPI
class TestAPIMixin(unittest.TestCase):
def setUp(self):
self._api= AtlasAPI()
self._api.authenticate()
def tearDown(self):
pass
def test_get(self):
r = self._api.get("https://httpbin.org/get")
... |
import json
import welly
from welly import Well
import pandas as pd
import lasio
import numpy as np
import os
import matplotlib.pyplot as plt
from src.waveletChoice import *
from src.seismicManipulation import *
def read_inputs(jpath):
"""
read_inputs reads the input json file and stores it information in a d... |
"""Locations where we look for configs, install stuff, etc"""
from __future__ import absolute_import
import os
import os.path
import site
import sys
from distutils import sysconfig
from distutils.command.install import install, SCHEME_KEYS # noqa
from pip.compat import WINDOWS, expanduser
from pip.utils import appd... |
import FWCore.ParameterSet.Config as cms
from Validation.CTPPS.simu_config.base_cff import *
# base profile settings for 2018
profile_base_2018 = profile_base.clone(
ctppsLHCInfo = dict(
beamEnergy = 6500
),
ctppsOpticalFunctions = dict(
opticalFunctions = cms.VPSet(
cms.PSet( xangle = cms.double... |
# 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
#
# Unless required by applica... |
import time
from pathlib import Path
from rest_framework.authtoken.models import Token
from quickstats import models
from django.contrib.auth import get_user_model
from django.test import TestCase, override_settings
from django.urls import reverse
METRICS = Path(__file__).parent / "metrics.prom"
class PrometheusT... |
"""
Return data to an ODBC compliant server. This driver was
developed with Microsoft SQL Server in mind, but theoretically
could be used to return data to any compliant ODBC database
as long as there is a working ODBC driver for it on your
minion platform.
:maintainer: C. R. Oldham (cr@saltstack.com)
:maturity: ... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
import grpc
from containerd.services.content.v1 import content_pb2 as containerd_dot_services_dot_content_dot_v1_dot_content__pb2
from containerd.vendor.google.protobuf import empty_pb2 as containerd_dot_vendor_dot_google_dot_protobuf_dot_empty__pb2... |
from __future__ import print_function, absolute_import
from google.protobuf import text_format
import argparse
import re
import sys
import math
sys.path.insert(0, '/Users/niekai/caffe-ssd/caffe/python')
caffe_flag = True
try:
import caffe
from caffe.proto import caffe_pb2
except ImportError:
caffe_flag = ... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
def GetRGBColor(colorName):
'''
Return the red, green and blue components for a
color as doubles.
'''
rgb = [0.0, 0.0, 0.0] # black
vtk.vtkNamedColors... |
import json
import uuid
from datetime import datetime, timedelta
from unittest.mock import Mock, call
import pytest
import requests_mock
from freezegun import freeze_time
from requests import RequestException
from sqlalchemy.exc import SQLAlchemyError
from celery.exceptions import Retry
from notifications_utils.templa... |
import operator
import re
from typing import Any, Dict, List, Tuple, Union
import frappe
from frappe import _
from frappe.query_builder import Criterion, Field, Order, Table
def like(key: Field, value: str) -> frappe.qb:
"""Wrapper method for `LIKE`
Args:
key (str): field
value (str): criterion
... |
from typing import Pattern
from recognizers_text.utilities import RegExpUtility
from ...resources.spanish_date_time import SpanishDateTime
from ..extractors import DateTimeExtractor
from ..base_set import SetExtractorConfiguration
from ..base_date import BaseDateExtractor
from ..base_time import BaseTimeExtractor
from... |
import requests
import pandas as pd
from bs4 import BeautifulSoup
def get_financial_statements(code):
url = "http://companyinfo.stock.naver.com/v1/company/ajax/cF1001.aspx?cmp_cd=%s&fin_typ=0&freq_typ=Y" % (code)
html = requests.get(url).text
html = html.replace('<th class="bg r01c02 endLine line-bottom"c... |
import _plotly_utils.basevalidators
class HovertextsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="hovertextsrc", parent_name="cone", **kwargs):
super(HovertextsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
'''
WSGI config for navygem project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/howto/deployment/wsgi/
'''
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETT... |
# Torch
import torch
from torch.quantization import (
MinMaxObserver,
PerChannelMinMaxObserver,
MovingAverageMinMaxObserver,
MovingAveragePerChannelMinMaxObserver,
HistogramObserver,
RecordingObserver,
PlaceholderObserver,
NoopObserver,
FakeQuantize,
FixedQParamsFakeQuantize,
... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
# coding=utf8
import argparse
import ast
import asyncio
import logging
import sys
from collections i... |
#!/usr/bin/env python
"""
An example consumer that uses a greenlet pool to accept incoming market
messages. This example offers a high degree of concurrency.
"""
import zlib
# This can be replaced with the built-in json module, if desired.
import simplejson
import gevent
from gevent.pool import Pool
from gevent import... |
#!/usr/bin/env python3
import re
def validate_user(username, minlen):
"""Checks if the received username matches the required conditions."""
if type(username) != str:
raise TypeError("username must be a string")
if minlen < 1:
raise ValueError("minlen must be at least 1")
# Userna... |
import unittest
import json
from time import time
from base64 import b64decode
from credentials.auth.jwt.jwt_signer import JWTSigner
PRIVATE_KEY = '''-----BEGIN RSA PRIVATE KEY-----
MIICWgIBAAKBgGFfgMY+DuO8l0RYrMLhcl6U/NigNIiOVhoo/xnYyoQALpWxBaBR
+iVJiBUYunQjKA33yAiY0AasCfSn1JB6asayQvGGn73xztLjkeCVLT+9e4nJ0A/o
dK8SOKB... |
#Swami skel module for the Swami Control Panel
import time
import dateutil.tz as dtz
import pytz
import datetime as dt
import collections
import esudo.esudo as esudo
from efl.evas import EVAS_HINT_EXPAND, EVAS_HINT_FILL
from efl import elementary
from efl.elementary.button import Button
from efl.elementary.box import... |
# Copyright 2022 Sony Semiconductors Israel, 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.0
#
# Unless required b... |
import json
import time
from threading import Thread
from websocket import create_connection, WebSocketConnectionClosedException
class AbstractWebsocketClient(object):
thread = None
stop = False
sub_params = {}
keep_alive = None
def start(self):
def _go():
self._connect()
... |
#! /usr/bin/python
'''
Write a function to find the longest common prefix string amongst an array of strings.
'''
class Solution:
# @return a string
def longestCommonPrefix(self, strs):
if len(strs) == 0:
return ''
return strs[0][:self.longestPrefix(strs)]
def longestPrefix(sel... |
"""Runner implementation."""
import logging
import os
from typing import TYPE_CHECKING, Any, FrozenSet, Generator, List, Optional, Set
import ansiblelint.file_utils
import ansiblelint.skip_utils
import ansiblelint.utils
from ansiblelint.errors import MatchError
from ansiblelint.rules.LoadingFailureRule import LoadingF... |
# Time complexity: O(n)
# Approach: Summing up triangle from bottom to top in minimum way.
class Solution:
def minimumTotal(self, triangle: List[List[int]]) -> int:
n = len(triangle)
for i in range(n-1, 0, -1):
for j in range(0, len(triangle[i])-1):
triangle[i-1][j] += m... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 19 19:27:45 2018
@author: Jonas Hartmann @ Gilmour group @ EMBL Heidelberg
@descript: Convenient little helpers for ipywidgets hacking.
"""
#------------------------------------------------------------------------------
# IMPORTS
from __future__ import division
im... |
# -*- coding: utf-8 -*-
"""Test support for managed arrays."""
import clr
import Python.Test as Test
import System
import pytest
from collections import UserList
def test_public_array():
"""Test public arrays."""
ob = Test.PublicArrayTest()
items = ob.items
assert len(items) == 5
assert items... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
# Recode by @mrismanaziz
# FROM Man-Userbot <https://github.com/mrismanaziz/Man-Userbot>
# t.me/SharingUserbot & t.me/L... |
dados = []
princ = []
cont = 0
maior = menor = 0
while True:
dados.append(str(input('Nome: ')))
dados.append(float(input('Peso: ')))
if len(princ) == 0:
maior = menor = dados[1]
else:
if dados[1] > maior:
maior = dados[1]
elif dados[1] < menor:
menor = dad... |
import sqlalchemy as sa
from ..utils.base import Model
__all__ = [
'Document'
]
class Document(Model):
title = sa.Column(sa.Unicode(255), nullable=False)
author = sa.Column(sa.Unicode())
file_url = sa.Column(sa.Unicode(), nullable=False, unique=True)
language_id = sa.Column(
sa.Integer... |
import sys
sys.path.insert(0, '..')
from cde_test_common import *
def checker_func():
pass
generic_test_runner(["python", "chdir_relpath_test.py"], checker_func) |
"""
Diffusion on a Cartesian grid
=============================
This example shows how to solve the diffusion equation on a Cartesian grid.
"""
from pde import CartesianGrid, DiffusionPDE, ScalarField
grid = CartesianGrid([[-1, 1], [0, 2]], [30, 16]) # generate grid
state = ScalarField(grid) # generate initial con... |
#Data Types
#String
print("Hello"[4])
"123" # this is actually a string not a number
print("123" + "345")
#integer
print(123+345)
#Float
3.14159
#Boolean
True
False |
import rospy
from geometry_msgs.msg import PointStamped
from bitbots_head_behavior.actions.look_at import AbstractLookAt
class TrackPost(AbstractLookAt):
"""
This action follows the seen post so that the camera always points towards it.
We try to do this so that the post doesnt get lost as easily
"""... |
import asyncio
import importlib.resources
import aioconsole
from playsound import playsound
import niescraper.resources
async def play_alarm():
with importlib.resources.path(niescraper.resources, 'alarm.mp3') as alarm_file:
while asyncio.get_running_loop().is_running():
playsound(alarm_file,... |
#import modules
import pandas # for dataframes
import matplotlib.pyplot as plt # for plotting graphs
import seaborn as sns # for plotting graphs
data=pandas.read_csv('HR_comma_sep.csv')
# Import LabelEncoder
from sklearn import preprocessing
#creating labelEncoder
le = preprocessing.LabelEncoder()
# Converting strin... |
#!/usr/bin/env python
""" main.py
Summay:
RaspberryPi camera streaming application.
"""
from webStreamingApp import webStreaming
def main():
webStreamingApp = webStreaming()
webStreamingApp.run(host='0.0.0.0', threaded=True, debug=True)
if __name__ == '__main__':
main() |
# -*- coding: utf-8 -*-
# Upside Travel, 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 or agreed to... |
import os, re
from pick import Picker, pick
from collections import defaultdict
folder = input("Enter a folder to redate: ")
post_dates = []
post_dict = defaultdict(list)
for folderName, subfolders, filenames in os.walk(folder):
print('Found {0} posts in '.format(len(filenames)) + folderName)
for filename in f... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-12-12 13:23
from __future__ import unicode_literals
from django.db import migrations
def create_project_locale_groups(apps, schema_editor):
"""Create translators groups for every project locale object."""
Group = apps.get_model('auth', 'Group')
... |
def fun(num):
n = [[0 for i in range(num)] for i in range(num)]
k = 1
for i in range(0, int(num/2) + 1):
for j in range(i, num - 1 - i):
n[j][i] = k
k +=1
for j in range(i, num - 1 - i):
n[num - 1 - i][j] = k
k+=1
for j in range(num - 1... |
"""Tests for certbot._internal.plugins.disco."""
import functools
import string
import unittest
import mock
import pkg_resources
import six
import zope.interface
from acme.magic_typing import List # pylint: disable=unused-import, no-name-in-module
from certbot import errors
from certbot import interfaces
from certb... |
import json
import pandas as pd
import numpy as np
import pprint
from sklearn.preprocessing import StandardScaler
from jonatan_settings import data_path, write_final_df, write_dr_results, audio_features
from jonatan_scrape import get_track_data, get_artist_data, get_audio_feature_data
from jonatan_dr import compute_d... |
# Copyright (c) 2021 AccelByte Inc. All Rights Reserved.
# This is licensed software from AccelByte Inc, for limitations
# and restrictions contact your company contract manager.
#
# Code generated. DO NOT EDIT!
# template file: justice_py_sdk_codegen/__main__.py
# pylint: disable=duplicate-code
# pylint: disable=li... |
import py, sys, struct
from rpython.rtyper.tool import rffi_platform
from rpython.rtyper.lltypesystem import lltype
from rpython.rtyper.lltypesystem import rffi
from rpython.tool.udir import udir
from rpython.translator.tool.cbuild import ExternalCompilationInfo
from rpython.translator.platform import platform
from rpy... |
# Copyright 2022 Google LLC
#
# 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, ... |
"""
@auth.requires_membership('admins')
def index():
response.title="Admin portal"
return dict()
"""
response.title=None
@auth.requires_membership('admins')
def dealership_requests():
if not request.args:
verification = "awaiting"
else:
verification=request.args[0]
dealership_requests = db(db.dealership_info... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.