content stringlengths 5 1.05M |
|---|
# -*- encoding: utf-8 -*-
import os
from aws_cdk import (
core,
aws_ec2,
aws_s3 as s3,
aws_neptune,
aws_iam,
aws_sagemaker
)
class NeptuneDemoStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
# The code that defines... |
""" Display browser support stats """
import sys
import json
import argparse
import warnings
import pkg_resources
from pathlib import Path
import requests
import colorama
import config
# Configure colorama for platform
colorama.init()
# Wrap parse_version so that it accepts numbers
def parse_version(version):
... |
# make sure templates are present and netmiko knows about them
# git clone https://github.com/networktocode/ntc-templates
# export NET_TEXTFSM=/home/ntc/ntc-templates/templates/
# see https://github.com/networktocode/ntc-templates/tree/master/templates
# for list of templates
from netmiko import ConnectHandler
import... |
import dash
import dash_core_components as dcc
import dash_html_components as html
from si7021 import get_tempC,get_humidity
from datetime import datetime
import pytz
location_india=pytz.timezone('Asia/Kolkata')
time_india=datetime.now(location_india)
timestamp='{:%H:%M:%S}'.format(time_india)
app =dash.Dash()
ap... |
# Generated by Django 3.0.8 on 2020-09-04 09:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('offer', '0004_auto_20200903_2003'),
]
operations = [
migrations.AlterField(
model_name='offer',
name='status',
... |
"""NASDAQ DataLink View"""
__docformat__ = "numpy"
import os
from colorama import Style
from tabulate import tabulate
from gamestonk_terminal.helper_funcs import export_data
from gamestonk_terminal.stocks.discovery import nasdaq_model
import gamestonk_terminal.feature_flags as gtff
def display_top_retail(n_days: i... |
import tkinter as tk
import constants.main_window_constants as const
from graphics.gui.main_gui import MainGUI
def on_closing():
main_gui.on_closing()
exit_app()
def exit_app():
root.destroy()
root = tk.Tk()
main_gui = MainGUI(root, exit_app)
root.title(const.MW_TITLE)
root.protocol("WM_DELETE_WIND... |
import streamlit as st
import util
def app():
st.image('./Streamlit_UI/Header.gif', use_column_width=True)
st.write("Upload a Picture to see if it is a fake or real face.")
st.markdown('*Need a face to test? Visit this [link]("https://github.com/kanakmi/Deforgify/tree/main/Model%20Training/dataset")*')
... |
#!/bin/env python3
import re # refers to regular expressions module
from Bio import SeqIO
import json
import argparse
class FastaStats:
def __init__(self):
self.entry_counter = 0
self.stats = {}
for data_type in ['identifiers', 'sequences', 'descriptions']:
s... |
import sublime
import sublime_plugin
import os
import tempfile
from Default.exec import ExecCommand
class OverridePanelExecCommand(ExecCommand):
def run(self, **kwargs):
settings = sublime.load_settings("Preferences.sublime-settings")
show_panel = settings.get("show_panel_on_build")
ove... |
"""Fetches a file, files or dir from remote suite"""
import os
from logging import getLogger
from omnium.omnium_errors import OmniumError
from omnium.syncher import Syncher
logger = getLogger('om.fetch')
ARGS = [(['filenames'], {'help': 'Filenames to fetch', 'nargs': '+'}),
(['--sync', '-s'], {'help': 'Sync ... |
import datetime
from decimal import Decimal as D
import isodate
import pytest
import pytz
from zeep.xsd.types import builtins
class TestString:
def test_xmlvalue(self):
instance = builtins.String()
result = instance.xmlvalue("foobar")
assert result == "foobar"
def test_pythonvalue(s... |
import os
import glob
import traceback
import random
from svlib.svtools import svtools as svt
log = svt.log
class XRayProducer:
def __init__(
self,
producer_id: int,
path_images: str,
cron_expr: str
) -> None:
self.producer_id = producer_id
self.path_images =... |
from efr32mg21.halconfig import halconfig_types as types
from efr32mg21.halconfig import halconfig_dependency as dep |
# Generated by Django 4.0.2 on 2022-02-09 18:07
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('solar_system', '0016_remove_asteroidobservation_seeing_and_more'),
]
operations = [
migrations.RemoveField(
mode... |
from __future__ import print_function
import zmq
import time
import ujson
import traceback
import importlib
from zmq.utils.strtypes import asbytes
from oct.core.turrets_manager import TurretsManager
from oct.results.stats_handler import StatsHandler
DEFAULT_HIGHTQUATER_CLASS = 'oct.core.hq.HightQuarter'
def get_hq_... |
from uuid import uuid4
from django.db import models
class IdentifiableModel(models.Model):
name = models.CharField(max_length=200)
uuid = models.UUIDField(default=uuid4, editable=False, unique=True)
class Meta:
abstract = True
class IdentifiableManager(models.Manager):
def get_by_uuid(self... |
# Generated by Django 2.1.7 on 2019-10-19 06:17
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('main', '0013_auto_20190617_1903'),
]
operations = [
migrations.CreateModel(
name='Subscriber',
... |
from __future__ import absolute_import
import plotly_study.graph_objs as go
D = dict(
left=[0, 1, 2, 3, 4, 5],
height=[10, 20, 50, 80, 100, 200],
bottom=[0, 1, 2, 3, 4, 5, 6],
width=[1, 4, 8, 16, 32, 64, 128],
multi_left=[0, 10, 20, 30, 40, 50],
multi_height=[1, 4, 8, 16, 32, 64],
multi_bo... |
#!/usr/bin/env python3
import getopt, sys, os
import argparse
import random
from modules import *
def start( args ):
parser = argparse.ArgumentParser(
prog='domain_scraper',
description='''Scrapes domains from one input URL or
from a file list of domains for broken links,
valid emails, and valid social me... |
from typing import List
from guet.committers import CurrentCommitters
from guet.steps.action import Action
class PreCommit(Action):
def __init__(self, current: CurrentCommitters):
super().__init__()
self.current = current
def execute(self, args: List[str]):
if len(self.current.get())... |
#!/usr/bin/env python
# encoding: utf-8
"test scores.py"
from __future__ import print_function
import datetime
import json
import os
import pytest
import app
import scores.common as common
# This run once for all
THIS_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__)))
TEST_DIR = os.path.join(THIS_DIR, 't... |
"""
Counts the number of sub_sequence in the string.
Example:
string = "ababc" sub_str = "abc"
Number of sub_seq: 3
"""
def find_sub_seq_count(string,sub_str):
if sub_str == "":
return 1
if string == "":
return 0
result = 0
if string[0] == sub_str[0]:
result += find_sub_seq_cou... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("Test")
process.source = cms.Source("PoolSource",
fileNames = cms.untracked.vstring(
"file:patTuple_standard.root"
)
)
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(100) )
process.MessageLogger = cms.Service("MessageLogger")... |
import traceback
import logging
from tornado import escape
from tornado.escape import *
from tornado.web import HTTPError
from tornado.web import RequestHandler
from m2core.common.options import options
from m2core.utils.session_helper import SessionHelper
from m2core.db.sqlalchemy_json import AlchemyJSONEncoder
# 200... |
import gdsfactory as gf
from ubc.tech import LAYER
from ubc.add_pins import add_pins
@gf.cell
def straight(
length: float = 10.0,
width: float = 0.5,
layer: gf.types.Layer = LAYER.WG,
with_pins: bool = True,
**kwargs,
) -> gf.Component:
"""Straight waveguide.
Args:
length:
... |
def arrayManipulation(n, queries):
arr=[]
for i in range(n):
arr.append(0)
for i in queries:
a=i[0]
b=i[1]
arr[a]=arr[a]+k
arr[b]=arr[b]-k
return max(arr)
r1=[1,2,100]
r2=[2,5,100]
r3=[3,4,100]
queries=[r1,r2,r3]
#print(arrayManipulation(6... |
# helpers.py
# ----------
# This file holds little helper functions, so they don't clutter up the main
# files. Import them if you need them!
from datetime import datetime
import os
import yaml
import logging
def get_date_from_json(date_string):
try:
return datetime.strptime(date_string, "%Y-%m-%dT%H:%M:... |
from django.db import models
from utils.behaviors import Timestampable, Permalinkable
from sponsors.models import Sponsor
class JobManager(models.Manager):
def active(self):
return self.get_queryset().filter(is_active=True)
class Job(Timestampable, Permalinkable):
title = models.CharField(max_lengt... |
from modules import edicomm
from modules.server import auth
from modules.server.battle.player import tokens
class Player:
def __init__(self, handler, addr):
self.handler = handler
self.addr = addr
self.nick = None
self.metanick = None
def process_message(self, msg):
# TODO: Handle long data (currently un... |
import boto3
from boto3 import Session
from botocore.exceptions import BotoCoreError, ClientError
from contextlib import closing
import os
import sys
import subprocess
from tempfile import gettempdir
# With no parameters or configuration, boto3 will look for
# access keys in these places:
#
# 1. Environment variabl... |
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
# Layer Normalization (Ref. https://arxiv.org/abs/1607.06450)
class LayerNorm(nn.Module):
def __init__(self, num_features, eps=1e-12, affine=True):
super(LayerNorm, self).__init__()
self.num_features = num_features
... |
import subprocess
import os
import sys
from pathlib import Path
import pytest
import json
import copy
from regolith.main import main
from tests.conftest import ALTERNATE_REGOLITH_MONGODB_NAME, FS_DB_NAME
from regolith.runcontrol import DEFAULT_RC, load_rcfile
from regolith.database import connect
from regolith.mongocl... |
#!/usr/bin/env python3
import os
import requests
from pprint import pprint
tweet_url = 'https://twitter.com/kyxvbx364872/status/1228935216544112640?s=20'
parts = tweet_url.split('/')
username = parts[3]
tweet_id = parts[-1].split('?')[0]
proxies = { "http": "http://127.0.0.1:1081", "https": "http://127.0.0.1:1081", ... |
# -*- coding: utf-8 -*-
# © 2017-2019, ETH Zurich, Institut für Theoretische Physik
# Author: Dominik Gresch <greschd@gmx.ch>
"""
Submodule for identifying nodal features such as points and lines from a
point-cloud of nodes as created by the :mod:`.search` submodule.
"""
from ._run import *
from . import result
from ... |
"""
square example
"""
S = int(input())
AREA = S**2
print("The area of square with size ", S, " is ", AREA)
|
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
... |
from .logging import get_logger
logger = get_logger()
from . import _types
from . import libs
from . import constants
from . import type_utils
from . import file_adapters
from . import type_utils
from . import iopath
from . import generic_path
from .compat import File |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# http://www.python.org/dev/peps/pep-0263/
"""Base class to call Named Entity Recognition APIs"""
from __future__ import division # 1/2 == 0.5, as in Py3
from __future__ import absolute_import # avoid hiding global modules with locals
from __future__ import print_function... |
"""
homeassistant.components.automation.state
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Offers state listening automation rules.
"""
import logging
from homeassistant.helpers.event import track_state_change
from homeassistant.const import MATCH_ALL
CONF_ENTITY_ID = "state_entity_id"
CONF_FROM = "state_from"
CONF_TO... |
#!/usr/bin/env python3
import asyncio
import socket
import logging
import numpy as np
from io import BytesIO
class ConfigurationError(Exception):
"""Server/Client Configuration Issue"""
def __init__(self, *args):
if args:
self.message = args[0]
else:
self.message = No... |
from .model_mixins import TimestampMixin
|
#!/usr/bin/env python3
from baselines.common import set_global_seeds, tf_util as U
from baselines import bench
import gym, logging
from baselines import logger
def train(env_id, num_timesteps, seed):
from baselines.ppo1 import mlp_policy, pposgd_simple
U.make_session(num_cpu=1).__enter__()
set_global_seeds... |
from __future__ import absolute_import
import sys
import string
"""
Parsing utilities, pulled out so they can be used in multiple modules
"""
def encode_unicode_bytes(my_string):
""" Shim function, converts Unicode to UTF-8 encoded bytes regardless of the source format
Intended for python 3 compatibility... |
# Copyright (c) Lawrence Livermore National Security, LLC and other VisIt
# Project developers. See the top-level LICENSE file for dates and other
# details. No copyright assignment is required to contribute to VisIt.
"""
file: __init__.py
author: Cyrus Harrison <cyrush@llnl.gov>
created: 7/6/2020
description:
... |
from unittest.mock import patch
import urllib
import json
from django.test import TestCase
from django.urls import reverse
from django.contrib.auth.models import Permission
from django.test.client import RequestFactory
from hostlookup_netdisco.api.views import HostView
from netdash.models import User
from hostlookup_... |
from pathmap import resolve_paths, resolve_path_if_long
from paths import paths, get_toc
def compare():
wrong = 0
toc = get_toc()
for item in paths:
resolved_list = list(resolve_paths(toc, [item[0]]))
resolved = resolved_list[0]
if resolved != item[1]:
print('Path: %s'... |
from typing import List
from clikit.utils._compat import OrderedDict
from .command import Command
from .exceptions import NoSuchCommandException
class CommandCollection(object):
"""
A collection of named commands.
"""
def __init__(self, commands=None): # type: (List[Command]) -> None
if co... |
__copyright__ = 'Copyright(c) Gordon Elliott 2017'
"""
"""
import graphene
from a_tuin.api import node_class, get_local_fields
from a_tuin.unittests.api.fixtures.models import AClass, AReferringClass
from a_tuin.unittests.api.fixtures.leaves import AClassLeaf, AReferringClassLeaf
aclass_node_fields = get_local_fie... |
import deep_q_graph as dqg
import utils as ut
import tensorflow as tf
import numpy as np
import os
import logging
import mem_top
logger = logging.getLogger(__name__)
class DeepQNetwork:
def __init__(self, num_actions, args):
# remember parameters
self.num_actions = num_actions
self.batch_size = args.ba... |
from flint import Rule
from flint import Msg
rule = Rule(name="func_name_rule", priority=-1)
msg = Msg()
msg.add_msg(error_code="W0001", display="函数不可以使用过短的名称", symbol="func_name_too_short")
msg.add_msg(error_code="W0002", display="examples.code文件中统一命名def xxx_api()", symbol="func_name_xxx_api")
msg.add_msg(error_code... |
# -*- coding: utf-8 -*-
'''
torstack.storage.redis
redis storage definition.
:copyright: (c) 2018 by longniao <longniao@gmail.com>
:license: MIT, see LICENSE for more details.
'''
import os
import aiofiles
class AsyncFile(object):
path = '/tmp'
def __init__(self, path=None):
if path:
s... |
import numpy as np
def f(s):
words = s.split(" ")
r = []
for word in words:
if len(word) < 3:
r.append(word)
else:
subword = [c for c in word[1:-1]]
np.random.shuffle(subword)
r.append("".join([word[0]] + subword + [word[-1]]))
return " "... |
#!/usr/bin/python
#############################################################
# Logistic regression #
# Sk. Mashfiqur Rahman #
# collect data from http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data #
#############################################################
import numpy as np
from scipy.opt... |
# Copyright 2018 ICON 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
#
# Unless required by applicable law or agreed to in writi... |
# coding=utf-8
import os
from itertools import chain
import numpy as np
import torch
import torch.nn as nn
import torch.nn.utils
from torch.autograd import Variable
import torch.nn.functional as F
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
from common.registerable import Registrable
from... |
#! python $this
import os,sys
isPython3 = sys.version_info[0]==3
if isPython3:
unicode = str
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
#from UnicodeTranslate import Translate
from yue.core.SymTr import SymTr
#from Kana import Translate
class LineEdit(QLineEdit):
accept... |
from django.http import Http404, HttpResponse
from rest_framework.views import APIView
from rest_framework.response import Response
from hubcare_api.indicators import active_indicator
from hubcare_api.indicators import welcoming_indicator
from hubcare_api.indicators import support_indicator
from hubcare_api.services im... |
import pandas as pd
from ast import literal_eval
from pprint import pprint
from nltk.tokenize import TweetTokenizer
import re
tTokenizer = TweetTokenizer()
def read_csv_to_dataframe():
trial = pd.read_csv("tsd_trial.csv")
trial["spans"] = trial.spans.apply(literal_eval)
return trial
def dataframe_to_txt(data... |
import math
print('Soma dos números ímpares múltiplos de 3 no intervalo de 1 a 500')
s = 0
cont = 0
for c in range(1, 500, 2):
m = c % 3
if m == 0:
cont += 1
s = s + c
print('A soma dos {} números solicitados é {}'.format(cont, s))
|
from django.urls import path
import blog.views as v
urlpatterns = [
path('', v.PublicPostView.as_view(), name='blog-home'),
path('post/<int:pk>/', v.PostDetailView.as_view(), name='post-detail'),
path('post/new/', v.PostCreateView.as_view(), name='post-new'),
path('post/admin_posts/', v.AdminPostView.... |
import vtk
from argparse import ArgumentParser
from glob import glob
import numpy
import os.path
def main(vtk_file_patterns):
for filename in glob(vtk_file_patterns):
print(f'file: {filename}')
reader = vtk.vtkPolyDataReader()
reader.SetFileName(filename)
reader.Update()
... |
import six
import subprocess
import io
import os
from tests.helpers import patch_open
from testtools import TestCase
from mock import (
patch,
MagicMock,
call,
sentinel,
)
from charmhelpers.fetch import ubuntu as fetch
if six.PY3:
builtin_open = 'builtins.open'
else:
builtin_open = '__builtin_... |
# Generated by Django 4.0.3 on 2022-03-11 15:40
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0004_remove_user_first_name_remove_user_groups_and_more'),
]
operations = [
migrations.RemoveField(
model_name='user',
... |
"""Code adapted from PytorchLightning/Lightnig-bolts and facebookresearch/vissl"""
import torch
from torch import nn
from torch.random import initial_seed
class MoCoLoss(nn.Module):
def __init__(
self,
embedding_dim,
queue_size,
momentum,
temperature,
scale_loss,
... |
from rest_framework.routers import APIRootView
from nautobot.dcim.models import Device
from nautobot.extras.api.views import (
ConfigContextQuerySetMixin,
CustomFieldModelViewSet,
ModelViewSet,
StatusViewSetMixin,
)
from nautobot.utilities.utils import count_related
from nautobot.virtualization import ... |
from . import DA
def get_da_list(da):
base_da_list = [[DA.NON_DA]]
da_list = [[DA.NON_DA]]
if (da & 0x0001) != 0:
da_list.append([DA.H_FLIP])
if (da & 0x0002) != 0:
da_list.append([DA.V_FLIP])
if (da & 0x0004) != 0:
da_list.append([DA.ROTATE, 90])
... |
"""
Tests for marshalling between formats
"""
import ast
import os
from ast import FunctionDef
from copy import deepcopy
from platform import system
from tempfile import TemporaryDirectory
from unittest import TestCase
from meta.asttools import cmp_ast
from doctrans import emit, parse
from doctrans.ast_utils import a... |
import logging
import subprocess
from collections import namedtuple
import numpy as np
from pathlib import Path
from typing import Union, List, Iterator, IO
import cv2
from PIL import Image
from torchvideo.samplers import frame_idx_to_list
_LOG = logging.getLogger(__name__)
VideoInfo = namedtuple("VideoInfo", ("h... |
import asyncio
import websockets
import json
CHANNELS = ['lf', 'rf', 'c', 'sub1', 'sub2', 'sub3', 'ls', 'rs']
class Htp1:
def __init__(self):
self.__bands = {
'peq': {
'slots': [
{
'checksum': None,
'channels... |
#!/usr/bin/env python
import os, sys, shutil
import subprocess
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
DIST_DIR = os.path.join(THIS_DIR, "dist")
sys.path.append(os.path.join(THIS_DIR, "src", "Selenium2Library"))
sys.path.append(os.path.join(THIS_DIR, "doc"))
sys.path.append(os.path.join(THIS_DIR, "demo"... |
from enum import Enum, auto
from AST import *
from Tokens import *
class PrecedenceBuilder:
class Flags(Enum):
OPERAND = auto()
CONCAT = auto()
OR = auto()
AND = auto()
ADD = auto()
SUB = auto()
MUL = auto()
DIV = auto()
def __init__(self):
... |
#!/usr/bin/python3
# Plugins updater based on plugins list defined in configs/plugins.list file
# Orginal version is created by PaulWebbster
# https://github.com/PaulWebbster/vim-configuration
import sys
import os
from git import Repo
import re
class PluginsManager(object):
"""Manages the connection with the syn... |
#!/usr/bin/env python
import unittest
from acme import Product
from acme_report import generate_products, ADJECTIVES, NOUNS
class AcmeProductTests(unittest.TestCase):
"""
Making sure Acme products are the tops!
"""
def test_default_product_price(self):
"""Test default product price being 10."... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="coastl",
version="0.0.1",
author="Pratham Gandhi",
author_email="prathamgandhi.school@gmail.com",
description="Lightweight Python package for converting Signal Temporal Logic into contract... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'Ren Qiang'
# %% 汉明距离
def hanmingDistance(nums: list) -> int:
# c1 = bin(nums[0])
# c2 = bin(nums[1])
# c3 = nums[0] ^ nums[1]
calc = bin(nums[0] ^ nums[1])
output = calc.count('1')
print(output)
return output
if __name__ == '__... |
from pydantic import BaseModel
from telegraph_api.models import Node
ALLOWED_EXTENSIONS = ['gif', 'jpg', 'jpe', 'jpeg', 'jfif', 'png', 'mp4', 'm4v', 'mp4v']
class UploadedFile(BaseModel):
""" Pydantic model for Uploaded to server File """
src: str
""" Path to telegra.ph file """
@property
def ex... |
# -*- coding: utf-8 -*
from __future__ import absolute_import
from .decorators import stick_meta, stick_cj
from .middlewares import StickyMetaMiddleware
__author__ = 'mikhail.kolganov@gmail.com'
|
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
def main():
th = []
ti = []
cp = []
runtime_file = "runtime_method4.csv"
cpu_file = "cpu_util4.csv"
runtime = np.array(pd.read_csv(runtime_file,header=None))
cpu = np.array(pd.read_csv(cpu_file,header=None))
for i in range(len(cpu... |
from app import assign_value, display, unitlist, peers, cols, boxes, grid_values, assignments
assignments = []
def assign_value(values, box, value):
"""
Please use this function to update your values dictionary!
Assigns a value to a given box. If it updates the board record it.
"""
# Don't waste m... |
import pytest
from bocadillo import API, Recipe
def test_if_prefix_not_given_then_routes_mounted_at_slash_name(api: API):
numbers = Recipe("numbers")
@numbers.route("/real")
async def real(req, res):
pass
api.recipe(numbers)
assert api.url_for("numbers:real") == "/numbers/real"
def t... |
import re
class Suggest(object):
"""
Suggests short and long name by adding 1 to any common
number suggfixed in the given short and long name.
"""
pattern = re.compile(r'^.+?(?P<suffixnumber>\d+)$')
def __init__(self, long_name, short_name):
self.long_name = long_name
self.sho... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# adapter.py
# @Author : (Zack Huang)
# @Link :
# @Date : 11/26/2021, 9:49:38 AM
import sys
sys.path.append('lib\\sim_access')
import six
import serial
from abc import ABCMeta, abstractmethod
import logging
import time
logger = logging.getLogger('maps6')
@six.a... |
# Ívar Þór Þórðarson 20.9.2018
import math
import time
# Finnur langhliðina af hringi með hliðum a og b
def langhlid(a,b):
svar = pow(a,2) + pow(b,2)
hlidc = math.sqrt(svar)
return round(hlidc,2)
# Finnur út hvort að tala 2 er margföldun af tölu 1
def margfoldun_af(t1,t2):
if t2 % t1 == 0:... |
"""
"""
from django.forms import Form
from oscar.apps.checkout.forms import ShippingAddressForm
from oscar.core.loading import get_model
from captcha.fields import CaptchaField
class ShippingAddressForm(ShippingAddressForm):
"""
Custom Shipping Address form
"""
def __init__(self, *args, **kwargs):
... |
""" Scripts processing pcap files and generating text output and figures """
import sys
import pyshark
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal
from trafficAnalyser import *
from optparse import OptionParser, OptionGroup, OptionValueError
__author__ = "Roman Kolcun"
__copyright_... |
"""Basic tests for the project."""
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from _pytest.pytester import Pytester
pytest_plugins = ["pytester"]
def test_basic_dot(pytester: "Pytester"):
"""Basic parsing test."""
pytester.copy_example(Path("tests", "fixtures", "basic.t... |
"""
Entry points for API calls
"""
from flask import request, jsonify, abort
from . import app, DB, logger
from . import errors
from .models.planets import Planet
from .models.alerts import Alert
from .util import validate_session, api_request, validate_request
from .config import SECRET_KEY
"""
Statuses
"""
@app... |
import selenium
from selenium import webdriver
import time
import urllib.parse
from selenium.common.exceptions import NoSuchElementException
class NCSearch:
def __init__(self):
self.driver = webdriver.Chrome("./driver/chromedriver.exe")
# Get the chinese character and Return meaning of the character
... |
class Solution:
def maxNumberOfFamilies(self, n: int, reservedSeats: List[List[int]]) -> int:
|
#Function finds first return from radargram per method in Grima et al., 2012
#Author: Brandon S. Tober
#Created 30January2018
import os
from PIL import Image
import math
import numpy as np
import scipy.misc
from config import *
#convert binary .img PDS RGRAM to numpy array. Reshape array with 3600 lin... |
'''
n = int(input("enter number"))
for i in range(0,n):
print(i*i)'''
#2
'''l = ["Infosys","campus","connect"]
print("list iteration")
for i in l:
print(i)
l1 = ("Infosys","campus","connect")
print("\n Tuple iteration")
for i in l1:
print(i)
s = "Infosys"
print("string iteration")
for i in s:
print(i)
... |
from pydantic import BaseModel
from datetime import datetime
class TokenPayload(BaseModel):
id: str
exp: datetime
class TokenResponse(BaseModel):
access_token: str
token_type: str = 'bearer'
|
#!/usr/bin/env python3
class SharedData:
spam = 42
x = SharedData()
y = SharedData()
print(x.spam, y.spam)
SharedData.spam = 99
print(x.spam, y.spam, SharedData.spam)
x.spam = 88
print(x.spam, y.spam, SharedData.spam)
class MixedNames:
data = 'spam'
def __init__(self, value):
self.data = va... |
from pysnmp.hlapi import (
SnmpEngine,
CommunityData,
UdpTransportTarget,
ContextData,
ObjectType,
ObjectIdentity,
getCmd,
setCmd,
nextCmd,
OctetString,
)
def snmp_query(host, community, oid):
errorIndication, errorStatus, errorIndex, varBinds = next(
getCmd(
... |
#!/usr/bin/python
# -*- coding:utf-8 -*-
from module import command,pathkey,concrontab
import subprocess as sub
import time
#先判断账号数量,备份,停服,删库,重启
user="#######"
pwd="#######"
file= "/data/lyadmin/scripts/clear.txt"
datepath=time.strftime("%Y%m%d%H%M")
dumppath="/data/lyadmin/backup/clearbak"
#判断目标库种的账号数量,大于5则不能清除,小... |
# -*- coding: utf-8 -*-
def ackerman(m, n):
if m == 0:
return n + 1
elif n == 0:
return ackerman(m - 1, 1)
else:
return ackerman(m - 1, ackerman(m, n - 1))
print('ackerman(1, 1) = {0}'.format(ackerman(1, 1)))
print('ackerman(1, 2) = {0}'.format(ackerman(1, 2)))
print('ackerman(1,... |
from os.path import abspath, dirname, join
from setuptools import setup
FOLDER = dirname(abspath(__file__))
DESCRIPTION = '\n\n'.join(open(join(FOLDER, x)).read().strip() for x in [
'README.rst'])
setup(
name='crosscompute-types',
version='0.7.7.1',
description='Default data type plugins for CrossComp... |
# x_2_9
#
# 「2-8」のように関数の中で自分自身を呼び出すものを「再帰関数」といいます
# 再帰関数を使って全てのメンバーを1行づつ表示してください
# ヒント: リスト内の要素がリストでなければ「print()」で値を表示してリストであれば自身の関数を呼び出します
members = [
['桃太郎', 'いぬ', 'さる', 'きじ', ['赤鬼', '青鬼', '黄鬼']],
['くり', 'うす', 'はち', '牛糞', ['子がに1', '子がに2']],
['浦島太郎', 'かめ', '乙姫', 'たい', 'ひらめ', ['つる']],
]
if type(members) =... |
from Utilities import swap
def partition_v2(arr, low, high):
if low >= high:
return -1
pi = low
li = low + 1
ri = high
while ri >= li:
if arr[li] > arr[pi]:
swap(arr, ri, li)
ri -= 1
else:
li += 1
pi = li - 1
swap(arr, low, pi)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.