text stringlengths 1 927k |
|---|
# Generated by Django 2.0.10 on 2019-03-02 14:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('notifications', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='notification',
name='comment',
... |
##############################################################################
#
# Copyright (c) 2004 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
# coding=utf-8
# Copyright (c) 2011 - 2017, 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 applic... |
import sys
# sys.path.append(
# '/home/rpl/Documents/rasmus/crazyswarm/ros_ws/src/crazyswarm/scripts/perceived-safety-study'
# )
# sys.path.append(
# '/home/rpl/Documents/rasmus/crazyswarm/ros_ws/src/crazyswarm/scripts/perceived-safety-study/utils'
# )
sys.path.append(
"/home/rpl/Documents/rasmus/crazyswa... |
import torchbearer
from torchbearer import Callback
import torch
import torch.nn.functional as F
from torch.distributions import Beta
from torchbearer.bases import cite
bc = """
@inproceedings{tokozume2018between,
title={Between-class learning for image classification},
author={Tokozume, Yuji and Ushiku, Yoshitak... |
from .bubble import bubble, BubbleOutput |
"""blog_app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-base... |
# coding: utf-8
"""
spoonacular API
The spoonacular Nutrition, Recipe, and Food API allows you to access over 380,000 recipes, thousands of ingredients, 800,000 food products, and 100,000 menu items. Our food ontology and semantic recipe search engine makes it possible to search for recipes using natural lang... |
import unittest
from pyats.topology import loader
from genie.libs.sdk.apis.iosxe.platform.execute import execute_clear_platform_software_fed_active_acl_counters_hardware
class TestExecuteClearPlatformSoftwareFedActiveAclCountersHardware(unittest.TestCase):
@classmethod
def setUpClass(self):
testbed =... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 7 16:00:06 2020
@author: greg6
"""
from pyomo.environ import *
model = ConcreteModel()
model.x = Var()
model.y = Var([1,2,3])
model.foo = Suffix()
model.foo.set_value(model.x, 1.0) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2020-2022 Barcelona Supercomputing Center (BSC), Spain
#
# 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... |
from .log import *
from .format_display import * |
"""Problem 55: Lychrel numbers"""
import unittest
def is_palindrome(n):
return str(n) == str(n)[::-1]
def reverse_and_add(n):
"""Returns n + reversed(n)."""
return n + int(str(n)[::-1])
def is_Lychrel(n):
""""Tests up to 50 iterations."""
count = 1
current = n
while count < 50:
cu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Author: Zheng <zxyful@gmail.com>
# Date: 2020-08-30
# Desc:
from flask import Blueprint
auth_blue = Blueprint('auth', __name__)
from . import views, errors |
# Bastion of Light
medal = 1142478
if sm.canHold(medal):
sm.chatScript("You obtained the <Bastion of Light> medal.")
sm.startQuest(parentID)
sm.completeQuest(parentID) |
import asyncio
import logging
logger = logging.getLogger(__name__)
def compute_user_level(user_xp):
power = 1
while user_xp >= 2 ** power:
power = power + 1
return power
class XPAggregator:
def __init__(self, redis, levels):
self.redis = redis
self.levels = levels
async... |
from enum import Enum
class GisaidSubmission(Enum):
NONE = 0
SUBMITTED = 1
NOT_SUBMITTED = 2
class HasConsensus(Enum):
NONE = 0
HAS_FILE = 1
NO_FILE = 2 |
from typing import Optional
from simplebgc.command_ids import *
INCOMING_COMMAND_NAMES = {
CMD_BOARD_INFO: 'CMD_BOARD_INFO',
CMD_BOARD_INFO_3: 'CMD_BOARD_INFO_3',
CMD_READ_PARAMS_3: 'CMD_READ_PARAMS_3',
CMD_READ_PARAMS_EXT: 'CMD_READ_PARAMS_EXT',
CMD_READ_PARAMS_EXT2: 'CMD_READ_PARAMS_EXT2',
C... |
#
# Copyright (C) 2020 Arm Mbed. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
"""Command to build/compile an Mbed project using CMake."""
import os
import pathlib
import shutil
import click
from mbed_tools.build import build_project, generate_build_system, generate_config, flash_binary
from mbed_tools... |
import datetime
import json
import os
import sys
import paho.mqtt.client as mqtt
import multiprocessing
import grpc
if sys.version_info >= (3, 0):
from http.server import BaseHTTPRequestHandler, HTTPServer
else:
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from pb.gsgateway_pb2
from pb.gsgatew... |
from flask import Flask, flash, redirect, render_template, request, session, abort
app = Flask(__name__)
@app.route("/")
def index():
return "Flask App!"
@app.route("/plants")
def plants():
return render_template('plants.html')
@app.route("/animals")
def animals():
return render_template('animals.html')... |
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
#
# This source code is licensed under the BSD license found in the
# LICENSE file in the root directory of this source tree.
# Copyright 2020 Petuum, Inc. All Rights Reserved.
#
# Redistribution and use in source and binary forms, with or without... |
from django import forms
from .models import Post, Profile
class PostForm(forms.ModelForm):
class Meta:
model = Post
exclude = ['profile','posted_on']
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = [] |
from math import floor
import pytest
import sqlalchemy.exc
from repo_admin.bare_database.model import Role
from repo_admin.bare_database.schema import RepoDatabase, fingerprints_table
from tests.conftest import integration
from tests.helpers import connect_as, insert_one, select_one, insert_many, select_all, files, R... |
from dataset import OcgDataset, MaskedDataError, ExtentError
from sub import SubOcgDataset |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2012-2021 Snowflake Computing Inc. All right reserved.
#
import base64
import hashlib
from datetime import datetime, timedelta
from logging import getLogger
from typing import Optional
import jwt
from cryptography.hazmat.backends import default_backend
f... |
# Generated by Django 2.1.15 on 2020-12-02 21:31
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('core', '0002_tag'),
]
operations = [
migrations.CreateModel(
... |
import pigpio
from datetime import datetime
from rackio import Rackio, RackioStateMachine, State, GroupBinding
app = Rackio()
@app.define_machine('SmartHome', 60)
class SmartHome(RackioStateMachine):
# State Definitions
starting = State('start', initial=True)
running = State('on')
idle = State('off'... |
# coding=utf-8
# Copyright 2017 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, division, print_function, unicode_literals
from textwrap import dedent
from pants.build_graph.build_file_aliases import BuildFileAl... |
# -*- coding: utf-8 -*-
'''
This file is part of PyMbs.
PyMbs is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
PyMbs is distributed ... |
import os
import trimesh
import numpy as np
"""
Creates Gazebo compatible SDF files from downloaded YCB data.
This looks through all the YCB objects you have downloaded in a particular
folder, and creates Gazebo compatible SDF files from a set of templates.
If the object has google_16k meshes downloaded, it will us... |
"""Functionality related to investor profiles for companies."""
default_app_config = 'datahub.investment.investor_profile.apps.InvestorProfileConfig' |
"""
This code is automatically generated. Never edit it manually.
For details of generating the code see `rubi_parsing_guide.md` in `parsetools`.
"""
from sympy.external import import_module
matchpy = import_module("matchpy")
if matchpy:
from matchpy import Pattern, ReplacementRule, CustomConstraint, is_match
... |
import pytest
from flask_unchained import unchained
from ._bundles.graphene_bundle.graphql import types
parent_manager = unchained.get_local_proxy('parent_manager')
child_manager = unchained.get_local_proxy('child_manager')
CREATE_PARENT = '''
mutation createParent($name: String!, $children: [ID] = []) {
cre... |
"""Constants used in corescheduler library."""
#
# Database settings
#
DEFAULT_JOBS_TABLENAME = "scheduler_jobs"
DEFAULT_EXECUTIONS_TABLENAME = "scheduler_execution"
DEFAULT_AUDIT_LOGS_TABLENAME = "scheduler_jobauditlog"
#
# APScheduler Settings
#
DEFAULT_THREAD_POOL_SIZE = 4
DEFAULT_JOB_MAX_INSTANCES = 3
DEFAULT_JOB... |
#real_time_ABRS
# Copyright (c) 2019 Primoz Ravbar UCSB
# Licensed under BSD 2-Clause [see LICENSE for details]
# Written by Primoz Ravbar
import numpy as np
import matplotlib.pyplot as plt
import cv2
import pickle
import msvcrt
from scipy import misc #pip install pillow
import scipy
from scipy import ndimage
from... |
# 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 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from keras import backend as K
import numpy as np
class TripletReluLoss(object):
def __init__(self, p_norm, eps=0.):
self.p_norm = p_norm
self.eps = eps
def _... |
from ..core import maxsum
from ..cli import argparse
class Main:
def __init__(self):
self.args = None
def setArgs(self,args):
self.args = args
def run(self):
parser = argparse.MaxSumArgparse()
args = parser.parse(self.args)
p = maxsum.MaxSum()
p.setInteger... |
from unittest.mock import Mock
from django.core.exceptions import ValidationError
from django.test import TestCase
from ..models import Ban
from ..test import create_test_user
from ..validators import (
validate_email,
validate_email_available,
validate_email_banned,
validate_gmail_email,
validate... |
#!/usr/bin/env python3
import os
from subprocess import call
import argparse
import multiprocessing
def run_unit_tests(octopus_build_dir, use_verbose_output):
octopus_test_dir = octopus_build_dir + "/test"
os.chdir(octopus_test_dir)
ctest_options = []
if use_verbose_output:
ctest_options.appen... |
# django-openid-auth - OpenID integration for django.contrib.auth
#
# Copyright (C) 2009-2013 Canonical Ltd.
#
# 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 ... |
"""ETF Controller"""
__docformat__ = "numpy"
import argparse
import os
from typing import List
import matplotlib.pyplot as plt
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal import feature_flags as gtff
from gamestonk_terminal.helper_funcs import get_flair
from gamestonk_terminal.menu im... |
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import itertools
from random import randrange
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from sklearn.utils import shuffle
from sklearn.naive_bayes import MultinomialNB, BernoulliNB
from sklear... |
# 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: python-cli-command.j2
# justice-basic-service (1.36.3)
# pylint: disable=duplicate-code
... |
# pylint: disable=too-many-lines
import logging
from typing import List, Optional
try:
from typing import Protocol
except ImportError:
from typing_extensions import Protocol
import pytest
from lxml import etree
from lxml.builder import ElementMaker
from sciencebeam_utils.utils.collection import extend_dict
... |
"""
Cisco Intersight
Cisco Intersight is a management platform delivered as a service with embedded analytics for your Cisco and 3rd party IT infrastructure. This platform offers an intelligent level of management that enables IT organizations to analyze, simplify, and automate their environments in more advan... |
import unittest
from checkov.terraform.checks.resource.gcp.GoogleCloudSqlDatabaseRequireSsl import check
from checkov.common.models.enums import CheckResult
class GoogleCloudSqlDatabaseRequireSsl(unittest.TestCase):
def test_failure(self):
resource_conf = {'name': ['google_cluster'], 'monitoring_service... |
from model import Actor, Critic
from config import Config
import torch
from rlcc.act import NetworkActor, StackedActor
from unityagents import UnityEnvironment
import numpy as np
import imageio
import os
from itertools import cycle
configs = []
names = []
#
configs.append(Config())
configs[-1].fc1_units = 400
config... |
from typing import Mapping, Any
from .base_client import BaseClient
class PagedEntryIterator:
def __init__(self, client: 'LoggingClient', body: Mapping[str, Any], request_kwargs: Mapping[str, Any]):
self._client = client
self._body = body
self._request_kwargs = request_kwargs
self.... |
# Copyright 2010 Jacob Kaplan-Moss
# Copyright 2011 Nebula, Inc.
# Copyright 2013 Alessio Ababilov
# Copyright 2013 OpenStack Foundation
# 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
# ... |
import datetime
import csv
import io
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.contrib.messages import get_messages
from users.forms import CustomUserCreationForm, CustomUserChangeForm
User = get_user_model()
class SignupViewTest(Tes... |
from django.urls import path
from . import views
urlpatterns = [
path('signup/', views.SingUp.as_view(), name='signup'),
] |
a, b, c, d, e, f = input()
l = int(a)+int(b)+int(c)
r = int(d)+int(e)+int(f)
if l == r:
"Cчастливый"
else:
"Обычный" |
"""Generated client library for billingbudgets version v1."""
# NOTE: This file is autogenerated and should not be edited by hand.
from __future__ import absolute_import
from apitools.base.py import base_api
from googlecloudsdk.third_party.apis.billingbudgets.v1 import billingbudgets_v1_messages as messages
class B... |
#!/usr/bin/env python
import os
import re
import sys
import struct
import ctypes
from sh4dis import sh4
RED = '\x1B[31m'
NORMAL = '\x1B[0m'
GREEN = '\x1B[32m'
gofer = None
cbuf = None
def disasm_libopcodes(data, addr):
# initialize disassembler, if necessary
global gofer, cbuf
if not gofer:
gofe... |
#
# CanvasRenderMock.py -- for rendering into a ImageViewMock widget
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
from ginga.canvas import render
from ginga.fonts import font_asst
# force registration of all canvas types
import ginga.canvas.types.all #... |
# coding: utf-8
"""
Control-M Services
Provides access to BMC Control-M Services # noqa: E501
OpenAPI spec version: 9.20.30
Contact: customer_support@bmc.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from clients.ctm... |
def parse_ids(d):
vars = ["id", "name", "links"]
z = {v: d[v] for v in vars}
z["grid_id"] = d["external_ids"]["GRID"]["preferred"]
z["link"] = None
if len(z["links"]):
z["link"] = z["links"][0]
z.pop("links")
return z |
#!/usr/bin/python
'''
See comments in download-mrsids.py.
This does step #4: convert MrSID -> JPG
It's designed to run continually, checking for new .sid files.
This lets it run in parallel to a download process (download-mrsids.py)
'''
import glob
import os
import random
import subprocess
import sys
import time
cmd... |
#
# -*- coding: utf-8 -*-
#
# Copyright (c) 2018 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 app... |
from toee import *
from utilities import *
from ed import *
from batch import *
###################################################################
### (18:55 20/04/06) A script written by Glen Wheeler (Ugignadl) for manipulating ToEE files.
### Requested by Cerulean the Blue from Co8.
##
### (13:05 22/04/06)... |
from django.contrib import admin
from .models import Zona, GrupoZona, ZonaEnGrupo
@admin.register(Zona)
class ZonaAdmin(admin.ModelAdmin):
list_display = ['nombre']
list_per_page = 10
@admin.register(GrupoZona)
class GrupoZonaAdmin(admin.ModelAdmin):
list_display = ['nombre', 'published']
list_per_p... |
# -*- coding: utf-8-*-
import os
# Jasper main directory
APP_PATH = os.path.normpath(os.path.join(
os.path.dirname(os.path.abspath(__file__)),
os.pardir, os.pardir, os.pardir))
CONFIG_PATH = os.path.expanduser(os.getenv('IPAWAC_CONFIG'))
PLUGIN_PATH = os.path.normpath(os.path.join(APP_PATH, 'assistant'))
LIB... |
# -*- test-case-name: cowrie.test.utils -*-
# Copyright (c) 2017 Michel Oosterhof <michel@oosterhof.net>
# See the COPYRIGHT file for more information
from os import environ
from twisted.logger import textFileLogObserver
from twisted.python import logfile
from cowrie.core.config import CowrieConfig
class CowrieDa... |
from sympy import (
Add, Abs, Chi, Ci, CosineTransform, Dict, Ei, Eq, FallingFactorial,
FiniteSet, Float, FourierTransform, Function, Indexed, IndexedBase, Integral,
Interval, InverseCosineTransform, InverseFourierTransform,
InverseLaplaceTransform, InverseMellinTransform, InverseSineTransform,
Lamb... |
# Copyright 2014-2017 Insight Software Consortium.
# Copyright 2004-2009 Roman Yakovenko.
# Distributed under the Boost Software License, Version 1.0.
# See http://www.boost.org/LICENSE_1_0.txt
import os
import sys
import unittest
import platform
from . import decl_string_tester
from . import declaration_files_tester... |
# -*- coding: utf-8 -*-
"""Resource files
"""
import os
def resource_filename(resource):
"""
Args:
resource(str): resource path relative to resource directory
Returns:
str: absolute resource path in the file system
"""
return os.path.join(
os.path.abspath(os.path.dirname... |
from shapely.geometry import Polygon
class GeographyBase:
def __init__(self, level : str , coordinates : list, validate : bool):
self.level = level
p = Polygon(coordinates)
if validate:
if not isinstance(coordinates, list):
raise TypeError("Coordinates must be a l... |
from instrumentum import instrumentum |
# This script will accept two numbers from user, then add them and give the result.
# Import modules.
import platform
import os
# Clear the screen as per the OS type.
os_name=platform.system()
if os_name == "Windows":
os.system("cls")
elif os_name == "Linux":
os.system("clear")
else:
print(f"The OS is n... |
#!/usr/bin/env python3
# Copyright (c) 2014-2019 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test resurrection of mined transactions when the blockchain is re-organized."""
from test_framework.bl... |
#!/usr/bin/env python
"""
Bytes-to-human / human-to-bytes converter.
Based on: http://goo.gl/kTQMs
Working with Python 2.x and 3.x.
Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com>
License: MIT
http://code.activestate.com/recipes/578019-bytes-to-human-human-to-bytes-converter/
"""
# see: http://goo.gl/kTQ... |
import os
import numpy as np
import pandas as pd
from sklearn.model_selection import ShuffleSplit
from sklearn.preprocessing import Imputer, StandardScaler
from sklearn.utils import check_random_state
from csrank.constants import LABEL_RANKING
from csrank.util import ranking_ordering_conversion
from ..dataset_reader ... |
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
# Created By: miha@reciprocitylabs.com
# Maintained By: miha@reciprocitylabs.com
from ggrc import models
from ggrc.converters import errors
from integration.ggrc... |
# Licensed to the StackStorm, Inc ('StackStorm') 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 use th... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import helium
import unittest
import os
class TestBinaryInputFile(unittest.TestCase):
datadir = os.getenv('HEDATADIR', os.getenv('HOME', 'c:/') + '/Helium/data')
def test_data_dir(self):
self.assertTrue(os.path.isdir(self.datadir))
def test_in_memory_row_major_fingerprint_storage(self):
... |
# -*- coding: utf-8 -*-
# See http://peak.telecommunity.com/DevCenter/setuptools#namespace-packages
try:
__import__('pkg_resources').declare_namespace(__name__)
except ImportError:
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__) |
import pathlib
import os
import invoke
TOP_LEVEL = [
'shim',
'snafu',
]
CURDIR = pathlib.Path(__file__, '..')
def _run_for_each(ctx, cmd):
for p in TOP_LEVEL:
# Can't use Path.resolve() because it can return a UNC path, which
# ctx.cd() does not accept.
with ctx.cd(os.path.abs... |
from authlib.jose.errors import (
JoseError,
DecodeError, InvalidClaimError,
MissingClaimError, InsecureClaimError,
ExpiredTokenError, InvalidTokenError,
)
__all__ = [
'JWTError', 'DecodeError', 'InvalidClaimError',
'MissingClaimError', 'InsecureClaimError',
'ExpiredTokenError', 'InvalidTok... |
# Generated by Django 2.1.4 on 2018-12-20 03:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('kobo', '0016_kobouser'),
]
operations = [
migrations.RemoveField(
model_name='kobouser',
name='surveys',
),
... |
import os
import time
import os.path as osp
import xml.etree.ElementTree as ET
import numpy as np
from PIL import Image
from functools import partial
from multiprocessing import Pool
from .misc import img_exts, get_classes, _ConstMapper
def load_hrsc(img_dir, ann_dir, classes=None, img_keys=None, obj_keys=None, npro... |
import requests as req
__author__ = "Karim Cheurfi"
API_URL = "https://api.dribbble.com/v1"
AUTH_ENDPOINT = "https://dribbble.com/oauth/authorize"
OAUTH_ENDPOINT = "https://dribbble.com/oauth/token"
SCOPE = ['write', 'public', 'comment', 'upload']
class Jabbbar(object):
def __init__(self, c... |
print("Project Euler Question 4: Largest palindrome product\n\n")
result = 0
def ispalindrome(string):
position = -1
hold_word = ""
for char in string:
hold_word += string[position]
position -= 1
return string == hold_word
for num1 in range(100, 1000):
for num2 in range(100, 1... |
"""Constants for Airly integration."""
ATTR_CAQI = "CAQI"
ATTR_CAQI_ADVICE = "advice"
ATTR_CAQI_DESCRIPTION = "DESCRIPTION"
ATTR_CAQI_LEVEL = "level"
CONF_LANGUAGE = "language"
CONF_USE_NEAREST = "use_nearest"
DEFAULT_LANGUAGE = "en"
DEFAULT_NAME = "Airly"
DEFAULT_SCAN_INTERVAL = 900
DOMAIN = "airly"
MANUFACTURER = "... |
# Lint as: python2, python3
# Copyright 2018 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
#
... |
import tools
from kendo_base import KendoWidget
__pragma__('alias', 'jq', '$')
class DatePicker(KendoWidget, tools.PyDate):
'''
vim: gx over the url:
http://docs.telerik.com/kendo-ui/api/javascript/ui/datepicker#fields-options
'''
format = 'yyyy-MM-dd'
_k_cls = jq().kendoDatePicker.widget
_... |
#!/usr/bin/python
"""A session demonstration app."""
import calendar
from datetime import datetime
import sys
import cherrypy
from cherrypy.lib import sessions
from cherrypy._cpcompat import copyitems
page = """
<html>
<head>
<style type='text/css'>
table { border-collapse: collapse; border: 1px solid #663333; }
th ... |
#Definir exceptions
class UsernameDuplicado(Exception):
pass
class IdadeMenor(Exception):
pass
class IdadeInvalida(Exception):
pass
class EmailInvalido(Exception):
pass
class User:
def __init__(self, username, idade, email):
self.__username = username
self.__idade = idade
... |
#coding:UTF-8
"""
ftp客户端实现核心方法
@author:yubang
2014-04-23
"""
import socket,re,time,os
class Client(object):
def __init__(self):
self.__fileSocket=None
def __del__(self):
pass
def __initConnect(self):
"初始化连接"
self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREA... |
from .mapper import Mapper
mapper = Mapper() |
from microbepy.common.partition import Partition
import copy
import numpy as np
import pandas as pd
import unittest
IGNORE_TEST = False
ELEMENTS = ['a', 'b', 'c', 'd', 'e']
SET1 = set(['a', 'b', 'c'])
SET2 = set(['d', 'e'])
PARTITION = [SET1, SET2]
class TestPartition(unittest.TestCase):
def setUp(self):
se... |
# -*- coding: utf-8 -*-
"""Public forms."""
from flask_wtf import Form
from wtforms import PasswordField, StringField
from wtforms.validators import DataRequired
from startapp.user.models import User
class LoginForm(Form):
"""Login form."""
username = StringField('Username', validators=[DataRequired()])
... |
import parameters, socket, time, yaml
from Message import Message
'''
Utils functions
'''
# Default callback function for the discovery
def default_discovery_callback(**res):
print("**Default discovery callback:")
print("---------------------------------")
print("ip:{},\nhn:{},\nrs:{}".format(res["ip"], ... |
"""
Argo Server API
You can get examples of requests and responses by using the CLI with `--gloglevel=9`, e.g. `argo list --gloglevel=9` # noqa: E501
The version of the OpenAPI document: VERSION
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from ... |
import socket
import ipaddress
def broadcast(ip, port, broadcast_message):
# Create a UDP socket
broadcast_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Send message on broadcast address
broadcast_socket.sendto(str.encode(broadcast_message), (ip, port))
broadcast_socket.close()
if ... |
from datetime import datetime, timedelta
from typing import Callable, List, Optional, Union
from fastapi import Depends, HTTPException, Request, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from passlib.context import CryptContext
from pydantic import BaseModel
from sqlmodel ... |
import subprocess
import sys
import click
from a2scomp.a2scomp import cli
from a2scomp import apksign
@cli.command()
@click.option('--sign', is_flag=True,
help='After aligning it, sign the APK')
@click.pass_context
def zipalign(ctx, sign):
config = ctx.obj
if config.apk:
click.echo('G... |
import serial
import numpy as np
import time
import signal
import sys
import pandas as pd
import matplotlib.pyplot as plt
def signal_handler(sig, frame):
ser.close()
df = pd.DataFrame({'time':l_time, 'state':l_state, 'fl_int':l_fl_int, 'pres_int':l_pres_int, 'pres_pac':l_pres_pac, 'pres_exp':l_pres_exp, '... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.