text stringlengths 2 999k |
|---|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distr... |
def clockwise_spiral:
print clockwise_spiral([[1, 2, 3, 4, 5],
[6, 7, 8, 9, 10],
[11, 12, 13, 14, 15],
[16, 17, 18, 19, 20]])
|
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import functools
import multiprocessing as mp
import os
import time
import numpy as np
from lvis import LVIS
from pycocotools import mask as maskUtils
def annToRLE(ann, img_size):
h, w = img_size
segm = ann['segmentation']
if type(se... |
import sys
# from visualize.visual import *
import h5py
import json
import random
import cv2
import numpy as np
import os
from skimage.transform import resize
from skimage.filters import gaussian
import matplotlib.pyplot as plt
from scipy import misc
font=cv2.FONT_HERSHEY_SIMPLEX
false_results_dir = "vqa-mfb/mfb_coat... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
example.py
~~~~~~~~~
A simple command line application to run flask apps.
:copyright: 2019 Miller
:license: BSD-3-Clause
"""
# Known bugs that can't be fixed here:
# - synopsis() cannot be prevented from clobbering existing
# loaded modules.
... |
from math import log
import pytest
from charge.chargers import CDPCharger, DPCharger, ILPCharger, MeanCharger, MedianCharger, ModeCharger, \
SymmetricILPCharger, SymmetricDPCharger, SymmetricCDPCharger
def test_mean_charger(mock_repository, ref_graph):
charger = MeanCharger(mock_repository, 2)
charger.c... |
import keras.backend as K
from keras.engine.topology import Layer
from keras import initializations
from keras import regularizers
from keras import constraints
import numpy as np
import theano.tensor as T
class Attention(Layer):
def __init__(self, W_regularizer=None, b_regularizer=None,
W_constra... |
from vm.lua_state import LuaState
def main():
ls = LuaState()
ls.load('./lua/table.luac')
ls.call(0, 0)
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
from loadData import gauss, loadAndPrepareInput
from scipy import signal
from generateTestData import loadTestData
from plot import plotProjections2D, plotError2D
from scipy.optimize import curve_fit
def growthRate(X, x, bins, y, angle, convFu... |
from schema_registry.client import errors, schema # noqa
from schema_registry.client.client import AsyncSchemaRegistryClient, SchemaRegistryClient # noqa
__all__ = ["SchemaRegistryClient", "AsyncSchemaRegistryClient"]
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# #############################################################################
# Copyright (c) 2008, Kevin Horton
# All rights reserved.
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... |
import os
def recursive_listdir(folderpath):
ret = []
for x in os.listdir(folderpath):
fpath = os.path.join(folderpath, x)
if os.path.isfile(fpath):
ret.append(fpath)
else:
ret.extend(recursive_listdir(fpath))
return ret
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class AlipayAccount(object):
def __init__(self):
self._alipay_user_id = None
self._available_amount = None
self._freeze_amount = None
self._total_amount = ... |
# Generated by Django 3.2.5 on 2021-12-11 17:26
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('bitcoin', '0003_rename_prices_historic_prices'),
]
operations = [
migrations.AlterModelOptions(
name='historic',
options={'o... |
from rest_auth.serializers import TokenSerializer
def test_serialize(token_factory):
"""
Test serializing a token.
"""
token = token_factory()
serializer = TokenSerializer(token)
expected = {
'key': token.key,
}
assert serializer.data == expected
|
""" This module contains data structures for the Skills level of STP.
"""
from abc import ABC, abstractmethod
from typing import Dict, List, Type, TypeVar
import stp.role as role
class ISkill(ABC):
""" Interface for Skills. """
@abstractmethod
def tick(self) -> None:
...
SkillT = TypeVar("Ski... |
#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
'''
Copyright 2014-2015 Teppo Perä
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... |
# 在社交媒体网站上有 n 个用户。给你一个整数数组 ages ,其中 ages[i] 是第 i 个用户的年龄。
#
# 如果下述任意一个条件为真,那么用户 x 将不会向用户 y(x != y)发送好友请求:
#
#
# age[y] <= 0.5 * age[x] + 7
# age[y] > age[x]
# age[y] > 100 && age[x] < 100
#
#
# 否则,x 将会向 y 发送一条好友请求。
#
# 注意,如果 x 向 y 发送一条好友请求,y 不必也向 x 发送一条好友请求。另外,用户不会向自己发送好友请求。
#
# 返回在该社交媒体网站上产生的好友请求... |
import flask
import pandas as pd
import io
from flask import request, jsonify, render_template, send_from_directory
import warnings
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
####################################################
# Flask Config
app = flask.Flask(_... |
# Gritto (2081200) | Forest of the Priest (240010501)
MANON_PREV_MAP = 240020400
GRIFFEY_PREV_MAP = 240020100
selection = sm.sendNext("Where would you like to warp to?\r\n\r\n#L0##bManon\r\n#L1#Griffey#l#n")
if selection == 0:
sm.warp(MANON_PREV_MAP, 4)
elif selection == 1:
sm.warp(GRIFFEY_PREV_MAP, 6) |
# ext/sqlsoup.py
# Copyright (C) 2005-2011 the SQLAlchemy authors and contributors <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
Introduction
============
SqlSoup provides a convenient way to access existing dat... |
from typing import List, Optional
import aiosqlite
from deafwave.util.db_wrapper import DBWrapper
from deafwave.util.ints import uint32
from deafwave.wallet.util.wallet_types import WalletType
from deafwave.wallet.wallet_info import WalletInfo
class WalletUserStore:
"""
WalletUserStore keeps track of all us... |
import tensorflow as tf
import numpy as np
TILE_SIZE = 224
""" Implements smooth L1 on each dimension. Erases loss for negative pixel locations. """
def smooth_L1(box_labels, box_preds, class_labels):
difference = tf.subtract(box_preds, box_labels)
result = tf.where(tf.abs(difference) < 1, tf.multiply(0.5, tf.square... |
# coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import os
import pytest
import platform
import functools
import itertools
from azure.core.exceptions import HttpResponseError, ClientAuthenticationError... |
# coding=utf-8
from flask import Flask,render_template,redirect,url_for
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField
from wtforms.validators import DataRequired
app = Flask(__name__)
# 配置数据库
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://roo... |
#-*- encoding: utf-8 -*-
import time
import argparse
import numpy as np
import tkinter as tk
from tkinter.ttk import Label
from kws_ps_pl import BRAM, PSPLTalk, InputDataToBram
from multiprocessing import Process
class timeRecorder(object):
def __init__(self):
self.total_time = 0.
self.counter = 0
... |
#!/usr/bin/env python
from setuptools import setup
setup()
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
#
# PySNMP MIB module ACC-NC-ALARM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ACC-NC-ALARM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:11:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
"""
Database module
This module exposes a number of tools that can be used on a database
and on addresses within the database. There are a number of namespaces
that allow one to query information about the database as a whole, or to
read/write to an address within the database.
The base argument type for many of the ... |
# -*- coding: utf-8 -*-
"""
test
~~~~
Flask-Cors tests module
"""
from ..base_test import FlaskCorsTestCase
from flask import Flask, Response
from flask_cors import *
from flask_cors.core import *
class ResponseHeadersOverrideTestCaseIntegration(FlaskCorsTestCase):
def setUp(self):
self.app ... |
from rest_framework import serializers
from .models import Rating
class RatingSerializer(serializers.ModelSerializer):
rater = serializers.SerializerMethodField(read_only=True)
agent = serializers.SerializerMethodField(read_only=True)
class Meta:
model = Rating
exclude = ["updated_at", "... |
import unittest
from unittest import mock
from pythonforandroid.build import run_pymodules_install
class TestBuildBasic(unittest.TestCase):
def test_run_pymodules_install_optional_project_dir(self):
"""
Makes sure the `run_pymodules_install()` doesn't crash when the
`project_dir` optiona... |
#!/usr/bin/python3
def test_queue():
#using a list to create queue
q = []
print ("Now is a empty queue", q)
q.append("a")
print ("Add a new item in the list", q)
q.append("b")
print ("Add a new item in the list", q)
q.append("c")
print ("Add a new item in the list", q)
LEN = len... |
#!/usr/bin/env python3
"""Test exercise, details: https://github.com/silversum/test"""
import gzip
from typing import TextIO
from pprint import pprint
def chunks(file_obj: TextIO):
"""
:param file_obj: text file or file-like object opened for reading
:return: parsed data dictionaries as an iterator object... |
import threading
import time
import numpy as np
import rospy
from std_msgs.msg import Int16, Int8
from robust_serial import write_order, Order
from robust_serial.threads import CommandThread, ListenerThread
from robust_serial.utils import open_serial_port, CustomQueue
from constants import BAUDRATE, N_MESSAGES_ALLOWE... |
import torch.multiprocessing as multiprocessing
import sys
from options.train_options import TrainOptions
import data
from trainers import create_trainer
from util.iter_counter import IterationCounter
from util.visualizer import Visualizer
from torch.multiprocessing import Queue
from data.data_utils import init_paralle... |
#!/usr/bin/env python
from .Modular2DEnv import Modular2D
__all__ = [Modular2D]
|
"""
https://github.com/svenkreiss/socialforce
Field of view computation.
"""
import numpy as np
class FieldOfView(object):
"""Compute field of view prefactors.
The field of view angle twophi is given in degrees.
out_of_view_factor is C in the paper.
"""
def __init__(self, twophi=200.0, out_of_vie... |
from miao_backend.exceptions import BusinessException
from urllib import parse
from apscheduler.triggers.cron import CronTrigger
from pytz import timezone
from yuemiao.models import SubInfoModel
from yuemiao.sub_vac.sub_vac import SubscribeVaccine, requestOrderList
from .miao_api.request import requestZMYY
from yuemia... |
# Generated by Django 4.0.1 on 2022-04-20 21:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('orders', '0002_alter_customerorder_city_alter_customerorder_country_and_more'),
]
operations = [
migrations.AlterField(
model_na... |
from __future__ import print_function
import argparse
import os
import pickle
import random
import numpy as np
import csv
import paddle
from model import RN, CNN_MLP
# Training settings
parser = argparse.ArgumentParser(description='Paddle Relational-Network sort-of-CLVR Example')
parser.add_argument('--model', type... |
"""Add filled_contributor_form to user
Revision ID: 723394ace6b5
Revises: 27a2782784d0
Create Date: 2021-04-11 11:48:11.170484
"""
import geoalchemy2
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "723394ace6b5"
down_revision = "27a2782784d0"
branch_labels = None
d... |
"""This module contains a class which stores data created in the interaction
with mocalum.
"""
import time
from . import metadata
import numpy as np
from numpy.linalg import inv as inv
import xarray as xr
from tqdm import tqdm
from .utils import sliding_window_slicing, bbox_pts_from_array, bbox_pts_from_cfg
class Data... |
'''
De-Lemmatise Word List
Given JSON files nouns.json and verbs.json with simple, flat lists of words,
create appropriate variants.
The relevant PoS transformations are:
- NNS: noun (plural)
- VBD: verb (past tense)
- VBG: verb (present participle)
- VBN: verb (past participle)
- VBZ: verb (3rd p... |
import erfa
from astropy import units as u
from astropy.coordinates.solar_system import PLAN94_BODY_NAME_TO_PLANET_INDEX
from ..constants import J2000
from ..frames import Planes
from .states import RVState
def get_mean_elements(body, epoch=J2000):
"""Get ecliptic mean elements of body.
Parameters
-----... |
"""
opentrons_shared_data.pipette.dev_types: types for pipette config that
require typing_extensions.
This module should only be imported if typing.TYPE_CHECKING is True.
"""
from typing import Dict, List, NewType, Union
from typing_extensions import Literal, TypedDict
LabwareUri = NewType('LabwareUri', str)
# Expl... |
# Copyright DataStax, 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 writing, softwa... |
from urllib import urlencode
from django.test import TestCase
from django.core.urlresolvers import reverse
class DefaultTestCase(TestCase):
def test_challenge(self):
response = self.client.get(
'%s?%s' % (reverse('challenge'), urlencode({
'hub.challenge': 'challenge',
... |
NAME = "training_pipeline"
def training_pipeline(
pipeline_params: dict,
compile_params: dict,
model_params: dict,
source_params: dict,
training_params: dict,
data_processing_pipeline_params:
dict = None,
versioner_params: dict = None,
processor_params: dict = None,
sink_params... |
#!/usr/bin/env python
"""
Copyright 2019, Zixin Luo & Yao Yao, HKUST.
CNN layer wrapper.
Please be noted that the center and scale paramter are disabled by default for all BN / GN layers
"""
from __future__ import print_function
import os
import sys
import numpy as np
import tensorflow as tf
from mvsnet.cnn_wrapper... |
import re
import string
from typing import Any, Dict
from django.http import HttpRequest, HttpResponse
from zerver.decorator import api_key_only_webhook_view
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import UnexpectedWebhookE... |
# Generated by Django 3.1.3 on 2021-05-29 10:23
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Exp_Main', '0011_auto_20210517_1944'),
]
operations = [
migrations.AlterField(
model_name='liquid'... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Compare two or more pivxlds to each other.
To use, create a class that implements get_tests(), and pas... |
import hashlib
from openpyxl.descriptors import (Bool, Integer, String)
from openpyxl.descriptors.excel import Base64Binary
from openpyxl.descriptors.serialisable import Serialisable
from openpyxl.worksheet.protection import (
hash_password,
_Protected
)
class ChartsheetProtection(Serialisable, _Protected):... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, xavier_init
from mmcv.cnn.bricks import NonLocal2d
from .builder import MODULE_UTIL
class Bottleneck(nn.Module):
def __init__(self,
in_channels,
mid_channels,
dila... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2021 Cloudera, 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/LIC... |
from cont_handler import Container ,addip
from gluon import current
from helper import get_context_path, get_docker_daemon_address, \
get_nginx_server_address, log_exception , config
from images import getImageProfile
from log_handler import logger
import docker
import os
import random
import remote_vm_task as remo... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
import json
with open('graph.json') as json_file:
data = json.load(json_file)
print(f"data length: {len(data)}")
for room in data:
if data[room]['title'] != 'A misty room':
print(f"room: {room}, title: {data[room]['title']}") |
# Copyright (c) 2019 PaddlePaddle 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 appli... |
#!/usr/bin/env python
"""Example of running a policy server. Copy this file for your use case.
To try this out, in two separate shells run:
$ python cartpole_server.py
$ python cartpole_client.py --inference-mode=local|remote
"""
import argparse
import os
import ray
from ray.rllib.agents.dqn import DQNTraine... |
from commands2 import CommandBase
from wpilib import SmartDashboard
from wpimath.geometry import Rotation2d, Pose2d, Transform2d
from subsystems.shootersubsystem import ShooterSubsystem
import constants
from util.angleoptimize import optimizeAngle
from util.convenientmath import rotationFromTranslation
class AimShoo... |
from io import BytesIO
from PIL import Image, ImageFont, ImageDraw
from discord import File
from bot import Command, categories
from bot.regex import pat_usertag
from bot.utils import download
furl = 'https://github.com/sophilabs/macgifer/raw/master/static/font/impact.ttf'
class Meme(Command):
__author__ = 'mak... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
File: parser.py
Author: huxuan
Email: i(at)huxuan.org
Description: Simplified parser for m3u8 file.
"""
from urllib.request import urlopen
import os.path
from .constants import patterns
def parse_content_to_lines(content):
"""Universal interface to split content ... |
# Day 8 - The Json Module
import socket
import json
import time # 12
def ip_address():
global server_ip
serv_ip = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
serv_ip.connect(("8.8.8.8", 80))
server_ip = serv_ip.getsockname()[0]
serv_ip.close()
return server_ip
########################
s... |
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
import simplejson
import random
# YOU'll NEED TO KEEP THIS SERVER UP AND RUNNING AT ALL TIMES ON YOUR SERVER COMPUTER IN YOUR COMPANY
# you can test this script with postman, chrome, curl, and a terminal
# but in order to make it work for r... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import os
import contextlib
from detectron2.data import DatasetCatalog, MetadataCatalog
from fvcore.common.timer import Timer
from fvcore.common.file_io import PathManager
import io
import logging
from detectron2.data.datasets.cityscapes import load... |
import xml.etree.ElementTree as ET
from os import getcwd
sets=[('2007', 'train'), ('2007', 'val'), ('2007', 'test')]
wd = getcwd()
# classes = ["aeroplane", "bicycle", "bird", "boat", "bottle", "bus", "car", "cat", "chair", "cow", "diningtable", "dog", "horse", "motorbike", "person", "pottedplant", "sheep", "sofa", "... |
from selenium import webdriver
from selenium.common.exceptions import StaleElementReferenceException, ElementNotInteractableException, \
ElementClickInterceptedException, NoSuchElementException, NoSuchWindowException
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name='Task',
fields=[
('id', models.AutoField(verbose... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 5, transform = "RelativeDifference", sigma = 0.0, exog_count = 20, ar_order = 0); |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Author: Adrian Böckenkamp
# License: BSD (https://opensource.org/licenses/BSD-3-Clause)
# Date: 13/03/2018
import string
import random
import os
import itertools
import errno
#: Separator for communication (topic, services) and tf (frame) names
ROS_NAME_SEP = '/'
... |
# Copyright 2020 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class EnvironmentListProtectionSourcesEnum(object):
"""Implementation of the 'environment_ListProtectionSources' enum.
TODO: type enum description here.
Attributes:
K_VMWARE: TODO: type description here.
KSQL: TODO: type description ... |
"""
# ============================================================================= #
| Project: Adaptive Controller Example
| Title: Python Controller File for Running the adaptive controller simulation
| Author: Moses C. Nah
| Email: [Moses] mosesnah@mit.edu
| Creation Date: Saturda... |
"""
Separated File containing all different models implemented
Creation Date: May 2020
Creator: GranScudetto
"""
from tensorflow.keras.layers import Input, Conv2D, BatchNormalization, Activation, Dense
from tensorflow.keras.layers import MaxPool2D, Concatenate, Flatten
from tensorflow.keras import Model
def model_1(... |
from rlpyt.utils.launching.affinity import encode_affinity
from rlpyt.utils.launching.exp_launcher import run_experiments
from rlpyt.utils.launching.variant import VariantLevel, make_variants
script = "rlpyt/experiments/scripts/mujoco/qpg/train/mujoco_sac_serial.py"
affinity_code = encode_affinity(
n_cpu_core=2,
... |
# -*- coding: utf-8 -*-
# pylint: disable=unused-argument
"""Tests for the `CifBaseParser`."""
from aiida_codtools.calculations.cif_filter import CifFilterCalculation
def test_cif_filter(aiida_profile_clean, fixture_localhost, fixture_calc_job_node, generate_parser):
"""Test a default `cif_filter` calculation."""... |
from netapp.netapp_object import NetAppObject
class FwUpdateStatusInfo(NetAppObject):
"""
List of disks that are pending updates, but not
able to be updated.
"""
_update_completion = None
@property
def update_completion(self):
"""
Estimate for background firmware downlo... |
from __future__ import annotations
from bip32utils import BIP32_HARDEN, BIP32Key
from mnemonic import Mnemonic
from .raw import RawKey
__all__ = ["MnemonicKey", "LUNA_COIN_TYPE"]
LUNA_COIN_TYPE = 330
class MnemonicKey(RawKey):
"""A MnemonicKey derives a private key using a BIP39 mnemonic seed phrase, and prov... |
# **************************************************************************** #
# #
# ::: :::::::: #
# Config.py :+: :+: :+: ... |
# -*- coding: utf-8 -*-
# Import python libs
from __future__ import absolute_import, print_function, unicode_literals
import os
import salt.modules.environ as envmodule
import salt.modules.reg
# Import salt libs
import salt.states.environ as envstate
import salt.utils.platform
# Import Salt Testing libs
from tests... |
# Copyright 2016 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 law or agreed to in writing,... |
#
# Copyright (c) 2021 Citrix Systems, 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... |
CLASS_TEMPLATE = """\
class {}(Model):
{}
\tclass Meta:
\t\tdatabase = db
modelList['{}'] = {}
""" |
"""
requests_kerberos.exceptions
~~~~~~~~~~~~~~~~~~~
This module contains the set of exceptions.
"""
from requests.exceptions import RequestException
class MutualAuthenticationError(RequestException):
"""Mutual Authentication Error"""
|
import os, json
path = ".github/workflows/eo-language-tests/tests/"
tests = []
for dir in next(os.walk(path + "."))[1]:
with open(path + dir + "/test.json", 'r') as test_data_file:
test_data = json.load(test_data_file)
test_data["directory"] = str(dir)
if (test_data["type"] == "runtime" and test_data["a... |
from pyramid.response import Response
from pyramid.view import view_config
from pyramid.renderers import render
@view_config(route_name='wer-kann-mitmachen')
def wer_kann_mitmachen_view(request):
set_language(request)
lan = get_language(request)
result = render('templates/' + str(lan) + '/mitmachen/wer-ka... |
# Time: O(N)
# Space: O(N)
class Solution:
cache = {0: 0, 1: 1, 2: 1}
def tribonacci(self, n: int) -> int:
if n in self.cache:
return self.cache[n]
self.cache[n] = self.tribonacci(n-1) + self.tribonacci(n-2) + self.tribonacci(n-3)
return self.cache[n]
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 1999-2017, Juniper Networks Inc.
# 2014, Jeremy Schulman
#
# All rights reserved.
#
# License: Apache 2.0
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... |
from django.contrib import admin
from .models import Location, Section
class EntryLocation(admin.ModelAdmin):
list_display = (
'title',
'city',
'country',
)
class EntrySection(admin.ModelAdmin):
list_display = (
'title',
'user',
'section_type',
'loca... |
import flask
import hashlib
import logging
logger = logging.getLogger("app.func")
def redirect_login():
return flask.redirect(flask.url_for('login'))
def get_gravatar_url(email):
base_url = "https://www.gravatar.com/avatar/"
email_hash = hashlib.md5(email.lower()).hexdigest()
style = 'retro'
full_url = "{}{... |
# MIT License
# Copyright (c) 2016 Aashiq Ahmed, Shuai Chen, Meha Deora, Douglas Hu
# 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 limitation the rig... |
__version__ = '0.1.0'
from .gui import *
from .parse_cif import *
from .plot_cif import *
|
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from api.views import CustomUserViewSet
app_name = 'api'
router = DefaultRouter()
router.register('users', CustomUserViewSet, base_name='users')
urlpatterns = [
path('', include(router.urls)),
]
|
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='py-threads-client',
version='0.0.3',
des... |
from schemdraw import Drawing
from schemdraw import elements as elm
from src.utils import numerize
from .input import Input
def draw_void():
drawing = Drawing()
drawing += (transistor := elm.transistors.JFetP().right().reverse())
drawing += elm.SourceV().at(transistor.drain).up().label('Vdd').reverse()... |
"""Module containing majory of calulation functions and their helpers."""
from datetime import datetime
from datetime import timedelta
from collections import defaultdict
from . import default_parse_fmt
from . import log_function_entry_and_exit
@log_function_entry_and_exit
def parse_row(row, field_names, datetime_pa... |
from gpiozero import Button
button = Button(2)
button.wait_for_press()
print('ayoye calisse') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.