content stringlengths 5 1.05M |
|---|
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 RegressionWithSelection(DSBoxTemplate):
def __init__(self):
... |
import re
with open('input.txt') as file:
CMDS = []
for line in file:
cmd, v = line.strip().split(' ')
CMDS.append((cmd, int(v)))
def go(cmds):
visited = []
acc = 0
index = 0
while True:
if index in visited:
return acc
visited.append(index)
... |
# Modules
import matplotlib.pyplot as plt
import numpy as np
from scipy.ndimage import rotate
from scipy.stats import skewnorm
def gaussian(angle=0.0, size=(100, 100), skew=(0.0, 0.0), std=(1.0, 1.0)):
"""Generate asymmetric Gaussian kernel
Keyword Arguments:
angle {int} -- Rotation in degrees (de... |
from math import log
from typing import Sequence, Union, Optional
from jina.executors.evaluators.rank import BaseRankingEvaluator
def _compute_dcg(gains, power_relevance):
"""Compute discounted cumulative gain."""
ret = 0.0
if not power_relevance:
for score, position in zip(gains[1:], range(2, le... |
#
# PySNMP MIB module HH3C-OID-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-OID-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:25:26 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019,... |
# -*- coding: utf-8 -*-
#
from typing import Optional
from ..category import Category
class Market(Category):
def add(
self,
owner_id: int = None,
name: str = None,
description: str = None,
category_id: int = None,
price: Optional[float] = None,
old_price:... |
""" Uses the *.wrd files from train.scp (mfc) to build the timit "words"
corpus, and then applied a phonemic dictionary on it to print phonemic output.
"""
TIMIT_SCP = "/Users/gabrielsynnaeve/postdoc/datasets/TIMIT/train/train.scp"
total_corpus = []
with open(TIMIT_SCP) as f:
for line in f:
fname = line.r... |
"""
Runs tests on main classes
AgentTest, MarketTest, SimulationTest
"""
import matchingmarkets as mm
import numpy.random as rng
import unittest
class TestMarkets(unittest.TestCase):
def test_agent(self):
"""
Agent Tests
"""
AgentList = list()
numTypes = rng.... |
##
## metapredict
## A protein disorder predictor based on a BRNN (IDP-Parrot) trained on the consensus disorder values from
## 8 disorder predictors from 12 proteomes.
##
# import user-facing functions
from .meta import *
from metapredict.backend.meta_predict_disorder import get_metapredict_network_version
import ... |
# Copyright (c) 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
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... |
from train_helper import get_input_args
from train_helper import load_data
from make_model import make_model
from train_helper import train_model
from train_helper import compute_accuracy
from train_helper import save_checkpoint
from workspace_utils import active_session
import torch
from torch import optim
# command... |
#!/usr/bin/python
N, I = map(int, input().strip().split())
assert 1 <= N <= 10**5
assert 1 <= I <= 10**6
lis_of_sets = []
for i in range(I):
a,b = map(int, input().strip().split())
assert 0 <= a < N and 0 <= b < N
indices = []
new_set = set()
set_len = len(lis_of_sets)
s = 0
while ... |
from itertools import cycle
import logging
logger = logging.getLogger(__name__)
class UAVSerialNumberValidator():
''' A class to validate the Serial number of a UAV per the ANSI/CTA-2063-A standard '''
def code_contains_O_or_I(self, manufacturer_code):
m_code = [c for c in manufacturer_code... |
#!/usr/bin/env python
# Very quick hack to monitor 3ware RAID cards via SNMP with check_mk
# Tested using Windows 3ware SNMP plugin (3wSnmp.msi from http://kb.lsi.com)
# Hereward Cooper <coops@fawk.eu> - Sep 2012
# MIB: TW-RAID-MIB
# .1.3.6.1.4.1.1458.100.22.1.10.X = twRaidDriveStatus.X
# 255 = OK
def inventory_3wa... |
"""
Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related doc... |
import plotly.figure_factory as ff
from datetime import datetime
import numpy as np
def int2dt(x):
return datetime.fromtimestamp(31536000+x*24*3600).strftime("%Y-%d-%m")
df = [dict(Task="T111111111111111", Start=int2dt(0), Finish=int2dt(1), Resource='Func1'),
dict(Task="T111111111111111", Start=int2dt(3),... |
"""You could use the scipy.optimize.root for achieving this as described here.
You could use any of the mentioned methods on the above-mentioned link. I am choosing broyden1. In this method, you can set fatol to 0.2 as it is the absolute tolerance for the residual."""
from scipy.optimize import root
amountOfCalls = 0... |
import unittest
from problems.arrays_strings.check_permutation import *
class CheckPermutationTest(unittest.TestCase):
def test_are_permutations_sort(self):
self.assertTrue(are_permutations_sort("qwerty", "yetrwq"))
self.assertFalse(are_permutations_sort("yopqweyeut", "qwoiuriwtpoiwq39dkfj"))
... |
import time
#colors
red='\033[91m'
b='\033[21m'
green='\033[92m'
yellow='\033[93m'
cyan='\033[96m'
blue='\033[94m'
print (red+"""
!!\ /!! /_\ /|| !!==!! ===\ !! !! ~~!!~~
!! \/ !! // \ / || !! ... |
import datetime
from connexion import request
from anchore_engine.apis import exceptions as api_exceptions
from anchore_engine.apis.authorization import (
ActionBoundPermission,
RequestingAccountValue,
get_authorizer,
)
from anchore_engine.apis.context import ApiRequestContextProxy
from anchore_engine.cli... |
# -*- coding: utf-8 -*-
"""
collection
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
import collection.models.party
import collection.models.error_reason
class PreApprovalResult(object):
"""Implementation of the 'PreApprovalResult' model.
TODO: ... |
import os
import networkx as nx
if __name__ == '__main__':
with open(f'{os.path.dirname(os.path.realpath(__file__))}/input.txt', 'r') as reader:
puzzle_input = [(x[0:3], x[4:]) if x[3] == ')' else (x[4:], x[0:3]) for x in [coord for coord in reader.read().splitlines()]]
orbit_map = nx.DiGraph(puzzle_i... |
"""
Test the deployed ocean stack
- Kubernetes, Local docker-compose, etc.
"""
def test_dummy():
assert True
|
#!/usr/local/bin/python
# coding: utf-8
from controller import Controller
if __name__ == '__main__':
Controller.execute()
|
# coding: utf-8
from __future__ import unicode_literals, division, absolute_import, print_function
__version__ = '0.24.0'
__version_info__ = (0, 24, 0)
|
import os
import re
import sys
import numpy as np
# Please modify to fit your environment
import tensorflow.contrib.keras.api.keras as keras
from tensorflow.contrib.keras.api.keras.models import Sequential, Model
from tensorflow.contrib.keras.api.keras.layers import add, Input, Dense, Dropout, Add
from te... |
import sys
import os
from __main__ import MathPy
from setuptools import setup, find_packages
os.environ['ANACONDA3_PATH'] = "C:\\ProgramData\\Anaconda3\\envs\\Calculator\\Library\\bin\\"
base = None
# GUI applications require a different base on Windows (the default is for a console application).
if sys.pl... |
# -*- coding: utf-8 -*-
"""
BuzzlogixTextAnalysisAPILib.Configuration
This file was automatically generated for buzzlogix by APIMATIC BETA v2.0 on 12/06/2015
"""
class Configuration :
# The base Uri for API calls
BASE_URI = "https://buzzlogix-text-analysis.p.mashape.com"
|
# Authors:
# Loic Gouarin <loic.gouarin@polytechnique.edu>
# Benjamin Graille <benjamin.graille@math.u-psud.fr>
#
# License: BSD 3 clause
"""
Solver D1Q2 for the advection equation on the 1D-torus
d_t(u) + c d_x(u) = 0, t > 0, 0 < x < 1, (c=1/4)
u(t=0,x) = u0(x),
u(t,x=0) = u(t,x=1)
the solution is
u... |
import copy
from v3iokubespawner.utils import get_k8s_model, update_k8s_model, _get_k8s_model_attribute
from kubernetes.client.models import (
V1PodSpec, V1SecurityContext, V1Container, V1Capabilities, V1Lifecycle
)
class MockLogger(object):
"""Trivial class to store logs for inspection after a test run."""
... |
import json
import uuid
from rest_framework import status
from rest_framework.test import APIClient, force_authenticate
from django.contrib.auth.models import User
from django.test import TestCase
from quickstart.models import Like, Inbox, Author
from quickstart.serializers import InboxSerializer
from quickstart.tests.... |
#
# Copyright 2015-2020 Andrey Galkin <andrey@futoin.org>
#
# 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 ... |
#!/usr/bin/env python
from pathlib import Path
from tempfile import TemporaryDirectory
from unittest import TestCase, main
from unittest.mock import Mock, patch
from cli_command_parser.utils import camel_to_snake_case, get_args, ProgramMetadata, ProgInfo
class UtilsTest(TestCase):
def test_camel_to_snake(self):... |
# -*- coding:utf-8 -*-
# @Time : 19-7-4 下午7:48
# @Author : zhangshanling
from flask import abort
from threading import Thread
from functools import wraps
from flask_login import current_user
import os
def async(f):
""" 多线程修饰器 """
def wrapper(*args, **kwargs):
thr = Thread(target=f, args=args, kw... |
"""Tests for permalinks.
This tests for the correct permalink behavior
except headings, which are tested in ``test_headerlinks.py``
"""
from pathlib import Path
import pytest
from sphinx.application import Sphinx
from .util import parse_html
@pytest.mark.sphinx(
"html",
testroot="table",
freshenv=True... |
def triangulo(num):
if num < 0: print("Error. Número debe ser > 0")
elif num == 1:
print('*')
else:
triangulo(num-1)
print('*'*num)
#Main
num = int(input("Introduzca el lado del triángulo: "))
triangulo(num) |
#! /usr/bin/env python3
# _*_coding:utf-8 -*_
import time
def singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
@singleton
class WVSState:
def __init__(sel... |
import os
from tempfile import NamedTemporaryFile, TemporaryDirectory
import unittest
from google.cloud import storage
from gfluent import GCS
class TestGCSIntegration(unittest.TestCase):
def setUp(self):
self.bucket = "johnny-trading-data"
self.prefix = "sit-temp"
self.project_id = os.... |
import sys, numpy as np
sys.path.append('./utils')
import models, audio_utils
from functools import partial
# takes a batch tuple (X,y)
def add_channel_dim(X):
return np.expand_dims(X,1)
CONFIG_MAP = {}
CONFIG_MAP['mlp_mfcc'] = {
'batch_size': 32,
'model': models.MLPModel,
'feature_fn': partial(audio... |
#! python3
import pyinputplus as pyip
prices = {'white': 1, 'wheat': 1.25, 'sourdough': 1.5,
'chicken': 2, 'turkey': 1.75, 'ham': 2.25, 'tofu': 2.5,
'cheddar': 1, 'swiss': 1.5, 'mozzarella': 2,
'mayo': 0.25, 'mustard': 0.3, 'lettuce': 0.4, 'tomato': 0.35}
selection = []
print('Time to mak... |
name = "cpimgs"
__version__ = '0.1.3' |
"""FreeWheel Linear Programming Interface for Python"""
from flipy.lp_reader import LpReader
from flipy.lp_problem import LpProblem
from flipy.lp_constraint import LpConstraint
from flipy.lp_expression import LpExpression
from flipy.solvers.cbc_solver import CBCSolver
from flipy.lp_variable import LpVariable, VarType
... |
# -*- encoding: utf-8 -*-
# Module iasebox
from numpy import *
def iasebox(r=1):
from ia870 import iasesum, iabinary
B = iasesum( iabinary([[1,1,1],
[1,1,1],
[1,1,1]]),r)
return B
|
import cPickle as pickle
import os.path
# def load_synonyms():
# with open('data/synonyms.pck', 'rb') as f:
# syns = pickle.load(f)
# return syns
# SYNONYMS = load_synonyms()
# WORDS = SYNONYMS.keys()
SYNONYMS = dict()
i = 0
while True:
if os.path.exists('data/synonyms.%02d.pck' % i):
... |
def FizzBuzz(num):
answer=''
for x in range(1,num+1):
if x%3 == 0:
answer+='Fizz'
if x%5 == 0:
answer+='Buzz'
if x%3 !=0 and x%5 !=0:
answer+=str(x)
answer+=' '
return answer
print(FizzBuzz(50))
|
f = open("input.txt")
d = f.read().splitlines()
registers = {"a":1, "b":0}
memory = d
ip = 0
while True:
try:
next_line = memory[ip]
except:
break
line_parts = next_line.split(" ")
inst = line_parts[0]
if inst == "hlf":
registers[line_parts[1]] /= 2
ip += 1
elif i... |
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, Form
from wtforms.validators import DataRequired
class RecipeStepForm(Form):
step_number = IntegerField('stepNumber', validators=[DataRequired()])
content = StringField('content', validators=[DataRequired()])
|
from __future__ import print_function
from autostep import Autostep
import time
port = '/dev/ttyACM0'
stepper = Autostep(port)
servo_angle_0 = stepper.get_servo_angle()
servo_angle_1 = stepper.get_servo_angle_alt()
print(f'servo_angle_0: {servo_angle_0} and servo_angle_1: {servo_angle_1}')
angle_list_fwd = list(ran... |
# SPDX-FileCopyrightText: Copyright 2021, Siavash Ameli <sameli@berkeley.edu>
# SPDX-License-Identifier: BSD-3-Clause
# SPDX-FileType: SOURCE
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the license found in the LICENSE.txt file in the root
# directory of this source ... |
"""
Logger builder for getting a logger that can be used for debugging
(print on console) and for reales mode (disable console output)
@author: wimmer, simon-justus
"""
import logging
import os
class logger_builder:
def __init__(self, log_name = 'default Logger', log_dir='logging123'):
self.log_dir = log... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.contrib import admin
from django.contrib.auth.models import Group
from django.forms import TextInput
from django.db import models
from import_export.admin import ImportExportModelAdmin
from .models import *
from .form... |
import sys
input = sys.stdin.readline
from collections import deque
def bfs(start):
queue = deque([start])
sign = [-1] * (n) # 最短経路長 / 最短経路 到達可能 False
sign[start] = 0 # 最短経路長 自分との距離は0(1往復を考えるときは消す) / 最短経路 到達可能 sign[start] = 1
while queue:
node = queue.popleft() # .pop()ならdfs
for n... |
# ============LICENSE_START=======================================================
# org.onap.dcae
# ================================================================================
# Copyright (c) 2017-2020 AT&T Intellectual Property. All rights reserved.
# Copyright (c) 2020 Pantheon.tech. All rights reserved.
# ====... |
# Copyright (c) 2019-2021 - for information on the respective copyright owner
# see the NOTICE file and/or the repository
# https://github.com/boschresearch/pylife
#
# 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 co... |
from tkinter import *
from tkinter import messagebox
from script import *
def show_message():
lst = processing(message.get())
h = 0
l = 0
temp = ''
for c in lst:
temp += str(c) + '\n'
h += c.get_freq() * log2(c.get_freq())
l += c.get_freq() * len(c.get_code())
... |
from bs4 import BeautifulSoup as bs
import requests
import json
def scrape(
station, units={"temp": "c", "pressure": "hpa", "speed": "kph", "precip": "mm"}
):
USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"
LANGUAGE = "en-US,en;q=0.5... |
__version__ = "0.3.9"
from .eval import *
from .eval_algorithms import *
from .system_analysis import * |
#! /usr/bin/env python
import os
import datetime
from future.utils import iteritems
import pandas as pd
class EnvironTransition(object):
"""Representation of a single environmental transition."""
def __init__(self, start_state, end_state, time, env_conds):
"""
Args:
start_state (s... |
import pytest
from PySide import QtGui, QtCore
import qmenuview
@pytest.fixture(scope='function', autouse=True)
def useqtbot(qtbot):
pass
@pytest.fixture(scope='function')
def model():
m = QtGui.QStandardItemModel()
for i in range(10):
m.appendRow(QtGui.QStandardItem("testrow%s" % i))
retur... |
class TestWorksIDGet:
id_result = "https://openalex.org/W2894744280"
name_result = "Fusing Location Data for Depression Prediction"
def test_works_openalex_get(self, client):
res = client.get("/works/W2894744280")
json_data = res.get_json()
assert json_data["id"] == self.id_result
... |
from discord.ext.commands import BadArgument
from discord.ext.commands.converter import MemberConverter
from discord.ext.commands.view import StringView
def binary_search(array, query, key=lambda a: a, start=0, end=-1):
"""Python's 'in' keyword performs a linear search on arrays.
Given the circumstances of st... |
import glfw
import OpenGL.GL as gl
import imgui
from imgui.integrations.glfw import GlfwRenderer
def app(render):
imgui.create_context()
window = impl_glfw_init()
impl = GlfwRenderer(window)
while not glfw.window_should_close(window):
glfw.poll_events()
impl.process_inputs()
gl... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础计算平台 available.
Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may o... |
"""
__init__.py for alias command
"""
from .alias_command import AliasCommand
|
from . import utils
class Meshes(object):
def __init__(
self, vertices=None, vertices_t=None, normals=None, faces=None, faces_t=None, faces_n=None,
textures=None, texture_params=None):
# Vertices (vertices) must be [batch_size, num_vertices, 3].
# Texture vertices (vertices... |
import csv
import os
import random
import numpy as np
import torchfile
#from torch.utils.serialization import load_lua
data_folder = '/media/user/DATA/ArtImages'
out_base_f = './art_data'
if not os.path.exists(out_base_f):
os.makedirs(out_base_f)
max_folder_length = 34
vocab = {}
alphabet = list(" abcdefghijklmnopqrs... |
import os
from datetime import datetime
if os.getenv("CARBONLINK_HOSTS"):
CARBONLINK_HOSTS = os.getenv("CARBONLINK_HOSTS").split(',')
if os.getenv("CLUSTER_SERVERS"):
CLUSTER_SERVERS = os.getenv("CLUSTER_SERVERS").split(',')
if os.getenv("MEMCACHE_HOSTS"):
MEMCACHE_HOSTS = os.getenv("MEMCACHE_HOSTS").spl... |
# Solution of;
# Project Euler Problem 645: Every Day is a Holiday
# https://projecteuler.net/problem=645
#
# On planet J, a year lasts for $D$ days. Holidays are defined by the two
# following rules. At the beginning of the reign of the current Emperor, his
# birthday is declared a holiday from that year onwards. I... |
__import__("calculator_1")
|
import torch
import math
import torch.nn.functional as F
from model.Model import Model
from abc import abstractmethod
class Generator(Model):
def __init__(self):
super(Generator,self).__init__()
@abstractmethod
def forward(self,e1_embedding, rel_embedding):
pass
class Translation_G(Gener... |
#!/usr/bin/env python
#
# year of release ! 2016
#
# With the exponential growth of Posttranslational modifications (PTMs)
# data and and lack of characterisation of all the PTM-types. Its important
# to undersand properly the functions and experimental relevence of PTMs by
# creating the tools that facilitate the PT... |
import json
from datetime import datetime
from numpy import array
from graphviz import Digraph
from log_parser.block_manager import BlockManager
from log_parser.executor import Executor
from log_parser.job import Job
from log_parser.job import Task
def get_json(line):
# Need to first strip the trailing newline, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from uvctypes import *
import time
import cv2
import numpy as np
try:
from queue import Queue
except ImportError:
from Queue import Queue
import platform
from datetime import datetime
BUF_SIZE = 2
q = Queue(BUF_SIZE)
def py_frame_callback(frame, userptr):
array_po... |
from pyb import UART
from pyb import delay
from pyb import micros, elapsed_micros
# This hashmap collects all generic AT commands
CMDS_GENERIC = {
'TEST_AT': b'AT',
'RESET': b'AT+RST',
'VERSION_INFO': b'AT+GMR',
'DEEP_SLEEP': b'AT+GSLP',
'ECHO': b'ATE',
'FACTORY_RESET': b'AT+RESTORE'... |
from .config import add_fcos_config
# 只有导入FCOS类, 该模型才会被注册到detectron2的META_ARCH里面
from .fcos import FCOS
|
from interpreter import Builtin, to_str, Import, lenlist
def call_ref(interpreter, v):
try:
v.call(interpreter)
except AttributeError:
raise TypeError(f'"{v}" is not a reference')
_list = list
def _find_getch():
try:
import termios
except ImportError:
# Non-POSIX. R... |
from coinbase_commerce.util import register_resource_cls
from .base import (
CreateAPIResource,
DeleteAPIResource,
ListAPIResource,
UpdateAPIResource,
)
__all__ = (
'Checkout',
)
@register_resource_cls
class Checkout(ListAPIResource,
CreateAPIResource,
UpdateAPIResou... |
# coding: utf-8
import sys
from plugins import Plugin
class FirstPlugin(Plugin):
hooks = ['on_privmsg']
def __init__(self):
pass
def on_privmsg(self, bot, source, target, message):
pass
|
from sympycore import *
def test_Matrix1():
a = Matrix(2)
assert a.rows==2
assert a.cols==2
assert a.tolist()==[[0,0], [0,0]]
a = Matrix([1,2])
assert a.rows==2
assert a.cols==1
assert a.tolist()==[[1], [2]]
a = Matrix([1,2], diagonal=True)
assert a.rows==2
assert a.cols=... |
from typing import Optional, Union
import numpy as np
import torch
from torch.optim import Optimizer
from pyraug.customexception import LoadError
from pyraug.data.loaders import BaseDataGetter, ImageGetterFromFolder
from pyraug.data.preprocessors import DataProcessor
from pyraug.models import RHVAE, BaseVAE
from pyra... |
# encoding: utf-8
# basics.py
# TODO documentation!
import numpy as np
from math import sqrt
from numba import jit
def pad_data(x, d1, d):
pad = lambda z: np.lib.pad(z, ((0, 0), (0, d1-d)),
'constant', constant_values=(0))
x = pad(x)
return x
@jit(nopython=True)
def ... |
"""Command-line interface for notesdir."""
import argparse
import dataclasses
from datetime import datetime
import json
from operator import itemgetter, attrgetter
import os.path
import sys
from terminaltables import AsciiTable
from notesdir.api import Notesdir
from notesdir.models import FileInfoReq, FileInfo
def ... |
"""
Testing the http sink
"""
import json
from mock import patch
from sinks.http import StatsiteHttp
@patch('requests.post')
def test_http(req):
metrics = [
"foo|123|1500000000",
"bar|456|1500000001",
]
expected = [
{"key": "foo", "value": "123", "timestamp": "1500000000"},
... |
# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name: sfp_threatfox
# Purpose: Check if an IP address is malicious according to ThreatFox.
#
# Author: <bcoles@gmail.com>
#
# Created: 2021-09-20
# Copyright: (c) bcoles 2021
# Licence: ... |
from part import *
from parts import *
|
class Solution(object):
def tree2str(self, t):
"""
:type t: TreeNode
:rtype: str
"""
if not t:
return ""
res = []
def dfs(root):
if not root:
return
res.append(str(root.val))
if root.left:
res.append("(")
dfs(root.left)
res.append(")")
if not root.left and root.right:
... |
import argparse
import collections
import logging
import asyncio
import datetime as dt
import sys
import zmq
import zmq.asyncio
import numpy as np
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore, QtWidgets
from pyqtgraph.WidgetGroup import WidgetGroup
from ami import Defaults
from ami.data import Deserial... |
import os
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import DataLoader, random_split
from torchvision import datasets, transforms
from torchvision.datasets import MNIST
import pytorch_lightning as pl
from pytorch_lightning.core.lightning import LightningModule
from py... |
"""
DCI proof of concept
Context is a separate object to the Collaboration (again for exploration of alternatives).
Made a class for it, but a Dictionary is also possible.
Author: David Byers, Serge Beaumont
7 October 2008
N.B.
Adapted to run on python 3.
"""
import types
class Role:
"""A role is a special clas... |
# coding=utf-8
# Copyright 2020 HuggingFace Inc. team.
#
# 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... |
from project.models import Project, User
from project import bcrypt, db, app
from functools import wraps
from flask import abort, request, jsonify
import jwt
import json
def authorize(f):
@wraps(f)
def decorated_function(*args, **kws):
print('qweqweqwe')
if not 'Authorization' in request.headers:
abort(401)
... |
"""
TopologicalGraph class will contain standard topological sort functionalities
"""
class TopologicalGraph:
def __init__(self, total_nodes):
self.graph = {}
self.reverse_graph = {}
self.total_nodes = total_nodes
self.dependeny_count = {}
self.clusters = []
f... |
import new.setup.environment as env |
from __future__ import division
from __future__ import print_function
from sarclf import train
from sarclf import test
import argparse
def main():
"""Provides command line interface and calls functions to compute MLPH.
:raises ValueError: If passed argument h is an even number.
"""
# Defines CLI a... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from Utilis import init_weights, init_weights_orthogonal_normal, l2_regularisation
from torch.distributions import Normal, Independent, kl
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class UNet_CMs(nn.Module):
""" Propo... |
#!/usr/bin/env python3
import sys
import os
import copy
from unittest import TestCase
sys.path.append(
os.path.join(os.path.dirname(os.path.abspath(__file__)), "../utils"))
from config import config
config["datasource"] = "MySQL"
from cluster_resource import ClusterResource
from job_manager import d... |
#!/usr/bin/python
# Slightly modified version of mooglazer/blockfeed's FalconPunch
# https://github.com/blockfeed/FalconPunch
#
# The only difference is an extra log and a different size used
# in the initial struct ('I' instead of 'q')
import os, socket, sys, struct
statinfo = os.stat(sys.argv[2])
fbiinfo = struct.... |
import agent
import random as rand
import string
import time
import sys
if __name__ == "__main__":
a = agent.Agent()
while True:
a.live();
time.sleep(.5) |
import tsk4
class Flora:
def __init__(self, name, lifespan, habitat, plant_type):
self.name = name
self.lifespan = lifespan
self.habitat = habitat
self.plant_type = plant_type
self.plant_size = 0
def ad_flora(self, planet:tsk4.Planet):
if planet.f... |
import pandas as pd
import re
'''
luigi_miner takes a log generated by Luigi looking e.g. like:
2019-09-01 09:29:23,303 DEBUG worker.py:260 - Checking if RootTask(date=2019-09-01_09-29-01, prev_date=2019-08-30_13-45-01, chunk=03) is complete
2019-09-01 09:29:23,306 INFO worker.py:313 - Scheduled Root... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.