content stringlengths 5 1.05M |
|---|
from django.conf import settings
from django.contrib.auth import user_logged_out
from django.test.utils import override_settings
from djet import assertions, restframework
from rest_framework import status
import djoser.views
from .common import create_user
class TokenDestroyViewTest(restframework.APIViewTestCase,
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import cv2
import matplotlib.pyplot as plt
def viewImage(name, image, y):
if y == 1:
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.figure(name)
plt.axis('off')
plt.imshow(image)
# plt.show()
def viewShow():
plt.show()
|
#!/usr/bin/env python3
"""
Recursively iterates the given path, looking for .java files. For
each file found, it parses the javadoc, and spell checks it, producing
an HTML file with the final report.
"""
import contextlib
import glob
import os
# For cleaning up text
import re
import string
# For running mwic
import s... |
import numpy as np
from pathlib import Path
JAMENDO_TAGS = [
'genre---downtempo',
'genre---ambient',
'genre---rock',
'instrument---synthesizer',
'genre---atmospheric',
'genre---indie',
'instrument---electricpiano',
'genre---newage',
'instrument---strings',
'instrument---drums'... |
from socketIO_client import SocketIO, BaseNamespace, find_callback
from unittest import TestCase
HOST = 'localhost'
PORT = 8000
DATA = 'xxx'
PAYLOAD = {'xxx': 'yyy'}
class TestSocketIO(TestCase):
def setUp(self):
self.socketIO = SocketIO(HOST, PORT)
self.called_on_response = False
def tear... |
import notify2
def send_notification(title, message):
notify2.init("OS Resources Notifier")
n = notify2.Notification(title, message)
n.show() |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-07-28 22:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('usuarios', '0001_initial'),
]
op... |
""" Day 12 of the 2021 Advent of Code
https://adventofcode.com/2021/day/12
https://adventofcode.com/2021/day/12/input """
from collections import namedtuple
Node = namedtuple("Node", "name is_small neighbours")
class CaveSystem:
def create_nodes(self, connections):
for node_1, node_2 in connections:
... |
class Solution:
def repeatedNTimes(self, A: List[int]) -> int:
A.sort()
n = len(A)
count = 1
for i in range(1, n):
count = count + 1 if A[i] == A[i - 1] else 1
if count == n / 2:
return A[i]
return A[-1]
|
import ast
import sys
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
import astunparse
from tests.common import AstunparseCommonTestCase
class UnparseTestCase(AstunparseCommonTestCase, unittest.TestCase):
def assertASTEqual(self, ast1, ast2):
self.assertEqual(ast... |
'''
Example user interface
'''
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import generate_disparity_image
import display_depth
import config
class SdenetDemo(QWidget):
'''Define button function and widgets layout'''
def __init__(self, parent=None):
su... |
import logging
logger = logging.getLogger(__name__)
from flask import request, Response
from flask_restful import Resource
from baseadmin import config
from baseadmin.backend.api.rest import api
from baseadmin.backend.repositories import registration
class Registration(Resource):
... |
import origen
import _origen
JTAG = _origen.services.JTAG
SWD = _origen.services.SWD
Simple = _origen.services.Simple
# This defines the methods for defining sub-blocks in Python and then handles serializing
# the definitions and handing them over to the Rust model for instantiation.
class Loader:
def __init__(se... |
from scipy.interpolate import interp1d
class Input_data():
def __init__(self, t, tws, twr, ta, alpha_s=600, alpha_r=600, alpha_a=20):
self.alpha_s = alpha_s
self.alpha_r = alpha_r
self.alpha_a = alpha_a
self.tws = interp1d(t, tws, fill_value="extrapolate")
self.twr = interp1... |
#!/usr/bin/env python
import base64
from binascii import hexlify
import os
import socket
import sys
import threading
import traceback
import paramiko
import json
import time
import pwd
import grp
os.chdir(os.path.dirname(os.path.realpath(__file__)))
raw_config = open('data/config.json').read()
config = json.loads(raw... |
# coding=utf-8
from __future__ import print_function
from __future__ import absolute_import
from __future__ import unicode_literals
import os
import sys
from clint.textui import puts
from commcare_cloud.colors import color_warning
def patch_environ():
if 'ANSIBLE_CONFIG' not in os.environ:
from commcare... |
"""
===============================
Compute and visualize ERDS maps
===============================
This example calculates and displays ERDS maps of event-related EEG data. ERDS
(sometimes also written as ERD/ERS) is short for event-related
desynchronization (ERD) and event-related synchronization (ERS) [1]_.
Concept... |
from dash import Dash, callback, html, dcc, Input, Output
# dashアプリの初期化
app = Dash(
__name__,
meta_tags=[{"name": "viewport", "content": "width=device-width, initial-scale=1"}],
)
app.title = "Hello Dash Callback"
def _layout():
return html.Div(
[
html.H1(app.title),
html.... |
from .embed_based import EmbedBasedSubstitute
from ....data_manager import DataManager
from ....tags import TAG_English
import torch
class CounterFittedSubstitute(EmbedBasedSubstitute):
TAGS = { TAG_English }
def __init__(self, cosine : bool = False, k : int = 50, threshold : float = 0.5, device = None):
... |
# from biothings.web.settings.default import *
# from web.api.query_builder import ESQueryBuilder
# from web.api.query import ESQuery
# from web.api.transform import ESResultTransformer
# *****************************************************************************
# Elasticsearch variables
# ************************... |
from tensorboardX import SummaryWriter
import torch
import torch.nn as nn
import torch.nn.functional as F # noqa: N812
import wandb
def main():
wandb.init(tensorboard=True)
class ConvNet(nn.Module):
def __init__(self):
super().__init__()
self.conv1 = nn.Conv2d(1, 10, kernel_s... |
import os, random, cv2
import numpy as np
from albumentations import Compose
from albumentations.augmentations.transforms import HorizontalFlip, Normalize
class DataLoader(object):
def __init__(self, data_folder, batch_size, input_shape, do_augmentation, gray_scale=False):
self._file_paths = []
sel... |
import torchvision.models as models
import torch
import torch.nn as nn
#******************************* VGG19 STUFF ********************************************
vgg19_model = models.vgg19(pretrained=True, progress=True)
print(vgg19_model)
new_classifier = nn.Sequential(*list(vgg19_model.classifier.children())[:1])
... |
import vapoursynth as vs
import vsutil
from typing import Any, List, Optional, Tuple
from lvsfunc.mask import DeferredMask
from lvsfunc.misc import replace_ranges, scale_thresh
from lvsfunc.types import Range
core = vs.core
class SelfDehardsub(DeferredMask):
"""
oh god why
basically use a reference f... |
# Get PurpleAir sensor data from PurpleAir url into dataframe
# James S. Lucas 20210318
import pandas as pd
import json
def get_sensor_data(sensor_id):
root_url = "https://www.purpleair.com/json?show="
params = {
'sensor_id': sensor_id
}
url_template = root_url + "{sensor_id}"
url = url_templa... |
#!/usr/bin/env python
# coding=utf-8
import RPi.GPIO as GPIO
import time
PWMA = 18
AIN1 = 22
AIN2 = 27
PWMB = 23
BIN1 = 25
BIN2 = 24
def t_up(speed, t_time):
L_Motor.ChangeDutyCycle(speed)
GPIO.output(AIN2, False) # AIN2
GPIO.output(AIN1, True) # AIN1
R_Motor.ChangeDutyCycle(sp... |
import numpy as np
import math
# Python3 code to remove whitespace
def remove_space(string):
return string.replace(" ", "")
def string_splitter(text):
a = [] # for saving the 3 parts of the instruction
str1 = text.split(',') #split at ','
str2 = str1[0].split() #split at spa... |
import logging
class OutStream:
INFO = 1
WARNING = 2
DEBUG = 3
ERROR = 4
CRITICAL = 5
def __init__(self,module_name_str, log_filename_str, screen_out_bool = True):
self.screen_out=screen_out_bool
self.log_fn=log_filename_str
self.logger=logging.getLogger(module... |
#Author : Vishwajeet Bamane
#Last modified Date:10/05/2020
# Number Guessing Game
# using Python
#importing random module to generate random number of chances
import random
print("Number guessing game")
#generating random rumber using randint() between 0 and 9
number = random.randint(0,9)
chances = 0
prin... |
#!/usr/bin/env python3
## ===============================================================================
## Authors: AFRL/RQQA
## Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division
##
## Copyright (c) 2017 Government of the United State of America, as represented by... |
import angr
from angrutils import *
from paths_to_target import PathsToTarget
class PathStats():
def __init__(self, paths, proj):
self.paths = paths
self.proj = proj
self.path_rank = []
def shortest_path_by_edges(self):
self.paths = sorted(self.paths, key=lambda x: len(x['nodes... |
# -*- coding: utf-8 -*-
import datetime, json, logging, os, pprint
# from typing import List
import django, requests
from mp_vl_app import settings_app
from django.conf import settings
from django.core.urlresolvers import reverse
log = logging.getLogger(__name__)
# def build_get_data( id: str, scheme: str, host: ... |
#
# PySNMP MIB module ChrComPmOpticsOTS-SNK-Current-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ChrComPmOpticsOTS-SNK-Current-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:35:47 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using P... |
#/usr/bin/env python
import pygame
from pygame.locals import *
from time import time
import AStar
class AStarExample:
# -1 1 2 3 4 Start Finish Find path Reset
colors = [(0,0,0),(0,255,0),(0,255-20,0),(0,255-40,0),(0,255-60,0),(0... |
# @author: Ville Wilpola
# @date: 2021-10-18
# Score:
"""
Assignment:
Consider this main program:
a = add(multi(3));
a = a + mod(div(a + 3)) + sub(12)
Sort the method names below in the order where they are called in the program; the method called first should be at the top, and the method called last at the bottom... |
import pandas as pd
import re
import csv
import datetime
'''
@Author Anand Chitale
This program reads in the raw FOMC scraped metadata and produces
A readable and actionable derived data csv for data download and analysis
'''
def extract_derived_data():
raw_df = pd.read_csv("../output/raw_data.csv")
documents... |
#!/usr/bin/env python3
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# ... |
from functools import wraps
from django.contrib.admin.models import CHANGE, LogEntry
from django.contrib.contenttypes.models import ContentType
from django.shortcuts import redirect, reverse
# Admin site specific utilities
def log_admin(msg, authorizer, model_type, model_object, flag=CHANGE):
LogEntry.objects.... |
from pathlib import Path
from fhir.resources.valueset import ValueSet as _ValueSet
from oops_fhir.utils import ValueSet
from oops_fhir.r4.code_system.action_cardinality_behavior import (
ActionCardinalityBehavior as ActionCardinalityBehavior_,
)
__all__ = ["ActionCardinalityBehavior"]
_resource = _ValueSet.p... |
import rpm
rpm.rng().Debug(1);
#rpm.mpw().Debug(-1);
# Generate random intergers
r = rpm.rng()
for i in range(100):
print r.next()
# Generate random numbers with lots of bits
m = rpm.mpw("800000000000000000000000000000000000000000000000000000000000000000000000")
for i in range(100):
r.next(m)
# Generate 160 bit r... |
import json
import os
from pathlib import Path
import pytest
from rotkehlchen.exchanges.binance import Binance, create_binance_symbols_to_pair
from rotkehlchen.tests.utils.factories import make_api_key, make_api_secret
@pytest.fixture
def function_scope_binance(
accounting_data_dir,
inquirer, # pyl... |
import pickle
import tensorflow as tf
from rllab.sampler.base import BaseSampler
from sandbox.rocky.tf.envs.parallel_vec_env_executor import ParallelVecEnvExecutor
from sandbox.rocky.tf.envs.vec_env_executor import VecEnvExecutor
from rllab.misc import tensor_utils
import numpy as np
from rllab.sampler.stateful_pool i... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from functools import total_ordering # из модуля functools импортируем функцию total_ordering
from math import log2 # из модуля math импортируем функцию нахождения двоичного логарифма
@total_ordering # декоратор класса, в котором заданы методы сравнения
class Char:
de... |
from rest_framework import routers
from django.urls import path
from .views import CommentViewSet, TopicCommentAPIView
router = routers.SimpleRouter()
router.register(r"comments", CommentViewSet)
urlpatterns = router.urls
urlpatterns.append(
path('topics/<int:topic>/comments', TopicCommentAPIView.as_view(), na... |
from chalicelib.utils.TimeUTC import TimeUTC
from chalicelib.utils import helper, pg_client
from chalicelib.utils import dev
@dev.timed
def get_by_url(project_id, data):
args = {"startDate": data.get('startDate', TimeUTC.now(delta_days=-30)),
"endDate": data.get('endDate', TimeUTC.now()),
... |
from typing import cast
import pykube
import pytest
from pytest_helm_charts.api.deployment import wait_for_deployments_to_run
from pytest_helm_charts.fixtures import Cluster
@pytest.mark.smoke
def test_we_have_environment(kube_cluster: Cluster) -> None:
assert kube_cluster.kube_client is not None
assert len(... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##
# @file shotcutHelper.py
# @version 1.0.0
# @author Ryosuke Igarashi(HN:igapon)
# @date 2021/12/4
# @brief 動画編集shotcutのプロジェクトファイルを編集するヘルパー
# @details
# @warning
# @note
import datetime
import glob
import os
import sys
import pyperclip
import xmltodict
import collections
... |
def merge_the_tools(string, k):
substrings = int(len(string)/k)
size_substring = int(len(string)/substrings)
count = 0
frequency = {}
word = ""
for value in string:
count += 1
if not value in frequency:
word += value
frequency[value] = True
... |
import asyncio
import contextlib
import datetime
import os # noqa
import pathlib
import pickle
import re
from collections import defaultdict
from http.cookies import BaseCookie, Morsel, SimpleCookie
from typing import ( # noqa
DefaultDict,
Dict,
Iterable,
Iterator,
List,
Mapping,
Optional,... |
"""Evaluation context information, shared across arithmetics."""
import re
from ..titanic import utils
from ..titanic import gmpmath
from ..titanic.ops import RM, OF
binary8_synonyms = {'binary8', 'posit8', 'posit8_t', 'quad'}
binary16_synonyms = {'binary16', 'float16', 'float16_t', 'posit16', 'posit16_t', 'half'}
... |
version = 1114
versionString = "2.0.0"
versionNameAppendix = "_%s" % str(version)
|
# coding=utf-8
from setuptools import setup, find_packages
# RELEASE STEPS
# $ python setup.py bdist_wheel
# $ python twine upload dist/VX.Y.Z.whl
# $ git tag -a VX.Y.Z -m "release version VX.Y.Z"
# $ git push origin VX.Y.Z
__title__ = "cryptoalgotrading"
__description__ = "Algotrading framework for crypto currencie... |
import json
import os
import random
import string
import uuid
from urlparse import urlparse
import time
from twisted.logger import Logger
from twisted.internet.protocol import Factory
Factory.noisy = False
log = Logger()
from service.settings import ENABLE_UNIQUE_NAMES
class TASK_STATUSES:
CREATED = "CREATED"... |
#coding:utf-8
from urllib3 import encode_multipart_formdata
import requests
def sendFile(filename, file_path):
# "Content-Type": "multipart/form-data; boundary=76a22e30da2bb7790828887966871012"
# url = "http://localhost:3000/articles/uploadhtml" # 请求的接口地址
url = "https://www.deepinews.com/api/articles/upl... |
if __name__ == "__main__":
l = [int(x) for x in input().split()]
def isValidMaxHeap(l, n):
for i in range(((n-2)//2)+1):
if l[2*i+1] < l[i]:
return False
if 2*i+2 < n and l[2*i+2] < l[i]:
return False
return True
print(isValidMaxHeap(l, len(l))) |
#!/bin/env python3
import argparse
import sys
import requests
import hexdump
from os import path
class PiSteg(object):
def __init__(self, input_file=None, output_file=None):
self.piSource = requests.get("https://teamisotope.com/pi.txt")
self.piIndex = 0
if not self.piSource.status_code:
... |
def write_log(log, log_path):
print(log)
f = open(log_path, mode='a')
f.write(str(log))
f.write('\n')
f.close() |
import pydot
from typing import Type
from ..graph import (Node as ExecutionNode, MatcherNode as ExecutionMatcherNode,
Graph as ExecutionGraph)
from ..registration import get_nodetypes
__all__ = ['Graph', 'Node']
class Node:
def __init__(self, *, type: str = None, branch: str = None,
... |
import os
from pathlib import Path
import argparse
import pandas as pd
from sklearn.model_selection import train_test_split
from utils.load_params import load_params
def data_split(data_dir,
data_fname,
cat_cols,
num_cols,
targ_col,
test_... |
#
# Copyright 2015 IBM Corp.
#
# 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 require... |
numbers = [int(n) for n in input().split()]
average_number = sum(numbers) / len(numbers)
answer = []
for n in range(len(numbers) - 1, -1, -1):
if (len(answer)) == 5:
break
if numbers[n] > average_number:
max_number = max(numbers)
answer.append(max_number)
numbers.remove(max_num... |
from puzzles.puzzle13 import get_data
from puzzles.puzzle13 import solve_part_1
from puzzles.puzzle13 import solve_part_2
def test_solve_part_1():
departure, bus_ids, _ = get_data("./data/test_data13.txt")
assert solve_part_1(bus_ids, departure) == 295
def test_part_2():
departure, bus_ids, delays = get... |
#!/usr/bin/env python
#
# pwman2pass.py takes in an unencrypted pwman db via filename or STDIN
# and uses `pass' to import:
#
# ./pwman2pass.py pwman.db.plaintext
# gpg -d pwman.db | ./pwman2pass.py
#
# your pwman db is imported into pass under a timestamped subfolder (in
# order to prevent overwriting any existing... |
#!/usr/bin/env python
# Copyright 2018-2021 John T. Foster
#
# 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... |
# Faça um programa que leia o ano de nascimento de um jovem e informe, de acordo com sua idade:
# -Se ele ainda vai se alistar no serviço militar.
# -Se é a hora de se alistar.
# -Se já passou da hora
# Seu programa tambem deverá mostrar o tempo que falta ou que passou do prazo.
import datetime
anoatual = datetime.date... |
# -*- coding: utf-8 -*-
import os # noqa: F401
import time
import unittest
import json
from os import environ
try:
from ConfigParser import ConfigParser # py2
except:
from configparser import ConfigParser # py3
from Workspace.WorkspaceClient import Workspace as workspaceService
from kb_prokka.kb_prokkaImpl... |
#!/usr/bin/env python3
import argparse
import os
import shutil
from codecs import open
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument("basename",
action='store',
help='basename of the .xyz and .gbw file to extract. The script will use al... |
from django.urls import include, path
from drf_yasg.views import get_schema_view
from rest_framework import routers, permissions
from drf_yasg import openapi
from django.conf.urls import url
from . import views
router = routers.DefaultRouter()
router.register(r'courses', views.CourseViewSet)
router.register(r'course_g... |
class Solution(object):
def canFinish(self,numCourses, prerequisites):
"""
:type numCourses: int
:type prerequisites: List[List[int]]
:rtype: bool
"""
if numCourses<=1:
return True
if prerequisites==[]:
return True
#get the inde... |
from .arm import *
from .mobile import *
from .uav import *
url = "https://petercorke.github.io/bdsim/" + __package__ |
import clr
clr.AddReference('SIPSorcery.SIP.Core')
from SIPSorcery.SIP import *
m_registrarSocket = "udp:127.0.0.1:5001"
m_regAgentSocket = "udp:127.0.0.1:5002"
m_notifierSocket = "udp:10.249.142.143:5003"
m_proxySocketLoopback = "udp:127.0.0.1:5060"
m_proxySocketInternal = "udp:10.249.142.143:5060"
#====... |
import os
os.environ["DGLBACKEND"] = "pytorch"
import dgl
from . import contigsdataset
from . import graph_functions
from . import evaluate
from . import graphsage_unsupervised
from . import version
|
#!/usr/bin/python
import requests
import json
token = "y5BAhu9Tdmi84XjSY2yR"
recurso = "users"
url = "http://gitlab.dexter.com.br/api/v3/%s?private_token=%s"%(recurso,token)
def createuser(dados):
token = "y5BAhu9Tdmi84XjSY2yR"
recurso = "users"
url = "http://gitlab.dexter.com.br/api/v3/%s?private_token=... |
from PIL import Image
import os
import math
import shutil
from image_generator import texture_size
tiles_dir_name = "StreamingAssets"
cache_dir_name_prefix = "cache"
table_Size = 32
padding_size = 0
dimension_size = texture_size
class PixelData:
def __init__(self, size, path, name):
self._component_count ... |
from kafka import KafkaConsumer
import pandas as pd
from common.fetcher import ChocFetcher
import multiprocessing, queue, signal, time
import zmq
import sys
from common.arimapredictor import ArimaPredictor
def parseTskBatch(content):
if content[0:9] != b'TSKBATCH\x00':
return None
content = content[9:... |
from rcrs_core.connection import URN
from rcrs_core.entities.building import Building
class PoliceOfficeEntity(Building):
urn = URN.Entity.POLICE_OFFICE
def __init__(self, entity_id):
Building.__init__(self, entity_id)
def copy_impl(self):
return PoliceOfficeEntity(self.get_id())
de... |
# Copyright 2020 by Chromation, Inc
# All Rights Reserved by Chromation, Inc
from microspeclib.expert import MicroSpecExpertInterface
from microspeclib.logger import CHROMASPEC_LOGGER as log
from microspeclib.datatypes.command import CHROMASPEC_COMMAND_NAME
from microspeclib.internal.docst... |
# Circuit Playground Express Dear Diary Alarm
#
# Don't let sister/brother read your secrets! Place the "armed" Circuit
# Playground under your diary. If someone tries to remove the diary, an alarm
# will sound.
#
# Author: Carter Nelson
# MIT License (https://opensource.org/licenses/MIT)
import time
from adafruit_cir... |
# Crichton, Admirable Source Configuration Management
# Copyright 2012 British Broadcasting 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/licens... |
from queue import Queue
from threading import Thread
import logger
from quantum_execution_job import Execution_Type, QuantumExecutionJob
class ResultAnalyzer(Thread):
"""Routes the results based on their execution type
"""
def __init__(self, input:Queue, output:Queue, output_agg:Queue, output_part:Q... |
#!/usr/bin/env python
#
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import azure.functions as func
from onefuzztypes.enums import ErrorCode
from onefuzztypes.models import Error
from onefuzztypes.requests import NodeGet, NodeSearch, NodeUpdate
from onefuzztypes.responses import BoolResult
... |
from drf_nested_serializer import NestedModelSerializer
from .models import SimpleModel, ForwardRelationModel
class ReverseO2OSerializer(NestedModelSerializer):
class Meta:
model = SimpleModel
nested_fields = {'o2o_models': 'simple_model'}
fields = '__all__'
class ReverseFKSerializer(Nes... |
from models.base import BaseModel
import numpy as np
import operator
from keras import backend as K
from keras.models import Model, Sequential
from keras.layers import Input, Dense, concatenate, Dropout, Activation
from keras import optimizers, applications, callbacks
from keras.callbacks import ModelCheckpoint, Reduce... |
"""Common get info functions for SNMP"""
# Python
import re
import logging
# Genie
from genie.metaparser.util.exceptions import SchemaEmptyParserError
log = logging.getLogger(__name__)
def get_snmp_snmpwalk(
device, community, ip_address, oid, version="2c", option=None
):
""" Get snmpwalk output from SNMP ... |
#!/usr/bin/env python
from __future__ import absolute_import
import argparse
import ipaddress
import sys
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from configurator.thriftgen.ConfigurationService import Configura... |
from decimal import Decimal
from itertools import groupby, islice
from operator import itemgetter
if __name__ == '__main__':
a = []
for i in range(int(input())):
x, y = (input(), Decimal(input()))
a.append((y, x))
a.sort()
for k, v in islice(groupby(a, key=itemgetter(0)), 1, 2):
... |
import time
from multiprocessing import Process
from flask import Flask, request, make_response
from exceptionalpy.HTTP import HTTPGetHandler
def main():
app = Flask(__name__)
@app.route("/notify")
def notify():
data = request.json
print(data)
return make_response()
app.run("... |
#from cobra import Model, Reaction, Metabolite, io
import model_data as md
import make_pairs
import networkx as nx
import matplotlib.pyplot as plt
model = md.model_data()
#model.load_model_sbml("iCHOv1_final.xml")
#model.load_model_cobra_sbml("iCHOv1_final.xml")
#model.load_model_mat("gimmeDG44.mat")
model.load_m... |
SECRET_KEY = "cat"
INSTALLED_APPS = (
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.admin",
"channels",
)
DATABASES = {}
CHANNEL_LAYERS = {}
MIDDLEWARE_CLASSES = []
|
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_dependencies_installed(host):
assert host.package("etckeeper").is_installed
assert host.package("openssh-clients").is_installed
... |
## Send data to a Graphite/Carbon Server
import traceback
import sys, time, socket, datetime
from datetime import datetime
class piSender:
carbon_server = '127.0.0.1'
carbon_port = 2003
station = "pi2wu"
def __init__(self, config):
if config.has_option('graphite','server'):
se... |
import pandas as pd
import numpy as np
from ftx.clients.rest_client import FtxAuth, FtxClient
from ftx.data._wranglers import add_trades, preprocess_fills
# Account summary for all traded futures
def get_futures_summary(futures_fills: pd.DataFrame, funding: pd.DataFrame, open_positions: pd.DataFrame) -> pd.Dat... |
"""Copyright 2019 Cisco Systems
All rights reserved.
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 copyright
notice, this list of conditions and the following discl... |
"""
Michael S. Emanuel
Wed Dec 5 09:12:18 2018
"""
import os
from importlib import util
import numpy as np
from numpy import cbrt
import matplotlib as mpl
# Allows matplotlib to run without being install as a framework on OSX
mpl.use('TkAGG')
import matplotlib.pyplot as plt
from datetime import date
# Import from so... |
import os
from conans import ConanFile, tools, AutoToolsBuildEnvironment
from conans.errors import ConanInvalidConfiguration
class tinycborConan(ConanFile):
name = "tinycbor"
license = "MIT"
homepage = "https://github.com/intel/tinycbor"
url = "https://github.com/conan-io/conan-center-index"
descri... |
from unittest import mock
class MockReadUpdates(object):
def __init__(self, cam, frames, prepend=""):
self.cam = cam
self.frames = frames
self.patches = []
self.mocks = []
self.prepend = prepend
def __enter__(self):
self.patches.append(
mock.patch(s... |
#Curso #9 Archivos estaticos
from flask import Flask
from flask import render_template
app = Flask(__name__)
#app = Flask(__name__, template_folder = 'prueba_template')
#para darle una carpeta en especifico
@app.route('/')
def index():
title = 'Curso flask'
return render_template('index.html', titulo = title)
... |
# -*- coding: utf-8 -*-
# 记住上面这行是必须的,而且保存文件的编码要一致!
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
# font = pygame.font.SysFont("宋体", 40)
# 上句在Linux可行,在我的Windows 7 64bit上不行,XP不知道行不行
font = pygame.font.SysFont("simsunnsimsun", 40)
# 用get_... |
FIRST_NAMES = [
"Kwiatkowski",
"Nikodim",
"Mattie",
"Duma",
"Samoti",
"Jenniferrose",
"Alyxandrea",
"Shadric",
"Crishaun",
"Semetria",
"Hichem",
"Danayja",
"Lavera",
"Suad",
"Irizarry-bazile",
"Tau",
"Geisler",
"Buzzard",
"Gemmill",
"Keysho... |
# Copyright (c) 2016 Fabian Schuiki
#
# This file implements LIB output generation.
import itertools
def gather_axes(data, scale, axes, fixes=[]):
axis = axes[0]
if len(axes) == 1:
keys = [",".join(fixes+[axis[0]+"="+stop]) for stop in axis[3]]
return [", ".join(["%f" % (data[k]*scale) for k in keys])]
else:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.