text stringlengths 1 927k |
|---|
# (C) Copyright 2019 Hewlett Packard Enterprise Development LP.
# 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 ... |
import git
import os
import logging
import glob
# Logger
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
LOGGER = logging.getLogger(__name__)
SECURITY_CONTENT_URL = "https://github.com/splunk/security_content"
class GithubService:
def __init__(self, security_content_branch):
self.securit... |
import sklearn.model_selection
import numpy as np
from sklearn.model_selection import ShuffleSplit, StratifiedShuffleSplit, cross_val_score, StratifiedKFold
def normal(X, labels, test_size):
"""Split a dataset into training and test parts.
Args:
X (numpy.ndarray): 2D features matrix
labels: ... |
import json
import requests
from utils import get_secret
from utils import is_pro
def send_slack(text="", channel="test", blocks=None):
assert channel in ["test", "events", "general"]
webhook = get_secret(f"SLACK_WEBHOOK_{channel.upper()}")
data = {"text": text}
if blocks:
data["blocks"] ... |
# B. Сбалансированное дерево
# ID успешной посылки 66593272
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.right = right
self.left = left
def height(root):
if root is None:
return 0
return max(height(root.left), height(root.right)) ... |
"""
Get the normalized best template to do flux calibration.
"""
#- TODO: refactor algorithmic code into a separate module/function
import argparse
import sys
import numpy as np
from astropy.io import fits
from astropy import units
from astropy.table import Table
from desispec import io
from desispec.fluxcalibratio... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: object_detection/protos/box_predictor.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
from google.protob... |
from pybeerxml.parser import Parser
from .picobrew_recipe import PicoBrewRecipe
from .picobrew_program_step import PicoBrewProgramStep
from xml.etree import ElementTree
class PicoBrewParser(Parser):
def parse(self, xml_file):
# Parse the BeerXML file
recipes = super(PicoBrewParser, self).parse(xm... |
#!/usr/bin/env python
import matplotlib.pyplot as pl
import numpy as np
from utils import util
from sklearn.cluster import KMeans
from utils.util import save_fig
data = util.load_mat('heightWeight/heightWeight')
data = data['heightWeightData']
markers = 'Dox'
colors = 'rgb'
for i in range(3):
KM_model = KMeans(i... |
#: Okay
def test():
good = 1
#: Okay
def test():
def test2():
good = 1
#: Okay
GOOD = 1
#: Okay
class Test(object):
GOOD = 1
#: N806
def test():
Bad = 1
#: N806
def test():
VERY = 2
#: N806
def test():
def test2():
class Foo(object):
def test3(self):
B... |
import torch
import torch.nn.functional as F
from torch.nn import Module
from torch_geometric.nn.conv import *
gnn_list = [
"gat_8", # GAT with 8 heads
"gat_6", # GAT with 6 heads
"gat_4", # GAT with 4 heads
"gat_2", # GAT with 2 heads
"gat_1", # GAT with 1 heads
"gcn", # GCN
"cheb", ... |
#!/usr/bin/env python
'''
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License")... |
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from pathlib import Path
from traitlets import default, observe, Unicode
from tornado.web import RedirectHandler
from jupyter_server.extension.application import ExtensionApp
from jupyter_server.utils import url_path... |
import asyncio
import os
from datetime import date
from os import getenv
from django.core.files.images import ImageFile
from django.core.management.base import BaseCommand
from movies.models import Poster, Movie, Genre
from person.models import Person, Photo, PersonRole
from parser.formatter import get_formatted_movie... |
from archspee.presenters import PresenterBase
from archspee.listeners import ListenerStatus
_LOG_LEVEL = None
class LogPresenter(PresenterBase):
def __init__(self, action_callback, **kwargs):
self.__log_level = _LOG_LEVEL
super(LogPresenter, self).__init__(action_callback)
self.status = Li... |
"""
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agr... |
# Copyright (c) 2017-2018 Uber Technologies, Inc.
#
# 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 ... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2022 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... |
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
from .document import DocumentArray
from .querylang import QueryLangArray
from .chunk import ChunkArray
from .match import MatchArray |
#Filename="finanzassistent"
#Type=Prerun
import os
def main():
ctx.gui_setMainLabel("Postbank Finanzassistent: Extracting key");
error=""
dbkey="73839EC3A528910B235859947CC8424543D7B686"
ctx.gui_setMainLabel("Postbank: Key extracted: " + dbkey)
if not (ctx.fs_sqlcipher_decrypt(filename, filename +... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
# Copyright (c) 2012 NTT DOCOMO, INC.
# Copyright (c) 2011-2014 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.apa... |
#!/usr/bin/env python
# Copyright (c) 2019 Rackspace US, Inc.
#
# 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 applica... |
from decrypt_file import decrypt
from get_commands import fetch_commands
import netmiko
import os
import concurrent.futures
hosts = decrypt(f'{os.getcwd()}/device_json.gpg')
def send_commands(connection, host, commands):
connection.send_config_set(commands)
return
def run(ip_address):
for device in hosts... |
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 4 12:29:21 2021
@author: aduell
"""
#import numpy as np
from numpy import pi, linspace, array, exp
#import tmm
from tmm import inc_tmm, inc_absorp_in_each_layer, inf
#import pandas as pd
#import tmm_vw as tmm
#import matplotlib.pyplot as plt
from matplotlib.pyplot impo... |
"""
Collection of functions and classes for testing a naive version
of parallel execution for topic model variational inference.
Usage
-----
From a shell/terminal, use like a standard Python script.
$ python TestFiniteTopicModel.py --N 200 --nDoc 500 --K 50 --nWorkers 2
For some keyword args (like N, nDoc, K, nWorker... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('plan_marker', '0002_userprofile_plan_created'),
]
operations = [
migrations.AlterField(
model_name='userprofile'... |
#!/usr/bin/env python
# Copyright 2012 Yummy Melon Software LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appl... |
# This is an example of a very basic discord bot in python
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=".", description="A basic discord bot")
@bot.event
async def on_ready():
print("I'm online!")
@commands.command(name="ping")
async def _ping(ctx):
latency = bot.late... |
#!/usr/bin/env python
from csvitself import csv2csv
from fixed import fixed2csv
from js import json2csv
from xls import xls2csv
SUPPORTED_FORMATS = ['fixed', 'xls', 'csv']
def convert(f, format, schema=None, key=None, **kwargs):
"""
Convert a file of a specified format to CSV.
"""
if not f:
r... |
import torch
from torch import nn
from torch.utils.data import DataLoader, Dataset, TensorDataset
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda, Compose
import matplotlib.pyplot as plt
import torch.distributions as D
import torch.nn.functional as F
# Download training data from... |
# coding=utf-8
from geoist.snoopy.algorithms.correlator_algorithms import CorrelatorAlgorithm
from geoist.snoopy.modules.correlation_result import CorrelationResult
from geoist.snoopy.constants import (DEFAULT_SHIFT_IMPACT,
DEFAULT_ALLOWED_SHIFT_SECONDS)
class CrossCorrelator(Correlato... |
from typing import List
class Solution:
def minCostClimbingStairs(self, cost: List[int]) -> int:
dp = [0x7FFFFFFF for _ in range(len(cost)+2)]
dp[0] = dp[1] = 0
for i, v in enumerate(cost):
v += dp[i]
dp[i+1] = min(dp[i+1], v)
dp[i+2] = min(dp[i+2], v)
... |
"""string multiplication"""
def main():
a = 'hi'
b = a * 2
TestError( b == 'hihi' ) |
from torch.distributions import constraints
from torch.distributions.transforms import AbsTransform
from pyro.distributions.torch import TransformedDistribution
class ReflectedDistribution(TransformedDistribution):
"""
Equivalent to ``TransformedDistribution(base_dist, AbsTransform())``,
but additionally... |
from django.utils.translation import ugettext_lazy as _
from django.db.models.fields import CharField
from .in_states import STATE_CHOICES
class INStateField(CharField):
"""
A model field that forms represent as a ``forms.INStateField`` field and
stores the two-letter Indian state abbreviation in the dat... |
from django.db import models
from django.utils import timezone
from django.db.models import Q
import asyncio
from ib_insync import IB, Stock, MarketOrder, util
from core.common import empty_append
from core.indicators import rel_dif
import vectorbtpro as vbt
import sys
import math
import pandas as pd
import numpy a... |
from easydict import EasyDict as edict
# the corresponding semantics to the index of
# obs.observation.feature_minimap and obs.observation.feature_screen
feature_mini_id = edict()
feature_mini_id.HEIGHT_MAP = 0
feature_mini_id.VISIBILITY = 1
feature_mini_id.CREEP = 2
feature_mini_id.CAMERA = 3
feature_mini_id.PLAYER_... |
# Generated by Django 2.2 on 2021-01-12 07:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects_api', '0031_auto_20201217_2330'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
... |
# -*- coding: utf-8 -*-
{
'!langcode!': 'fr',
'!langname!': 'Français',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression optionnelle comme "champ1=\'nouvellevaleur\'". Vous ne pouvez mettre à jour ou supprimer les résultats ... |
import pytest
from content.ext.envconfig import EnvConfig
@pytest.mark.parametrize('use_init_app', [True, False])
def test_ext_init(app, mocker, use_init_app):
mock_init_app = mocker.patch.object(EnvConfig, 'init_app')
if use_init_app:
ext = EnvConfig()
ext.init_app(app)
else:
Env... |
# ======================================================================
# Amplification Circuit
# Advent of Code 2019 Day 07 -- Eric Wastl -- https://adventofcode.com
#
# Computer simulation by Dr. Dean Earl Wright III
# ======================================================================
# ======================... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import os
import copy
def is_similar(s1, s2):
count = 0.0
for token in s1.split(' '):
if token in s2:
count += 1
# if count / len(s1.split(' ')) >= 0.7 and abs(len(s1.split(' '))-len(s2.split(' '))<5):
if count / len(s1.split(' ')) >= 0.7 and count / len(s2.split(' ')) >= 0.7:
... |
# MIT License
#
# Copyright (c) 2021 Kazuyuki HIDA
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge... |
"""Test of the reversed linked list."""
import pytest
@pytest.fixture
def linked_list():
"""Make linked_list for testing."""
from linked_list import LinkedList
linked_list = LinkedList([1, 2, 3])
return linked_list
def test_empty_linked_list(linked_list):
"""Test exception from empty linked_lis... |
from wtforms import Form
from wtforms import StringField
from wtforms import IntegerField
from wtforms.validators import DataRequired
class EmailForm(Form):
name = StringField('name', validators=[DataRequired()])
email = StringField('email', validators=[DataRequired()])
class LoginForm(Form):
username =... |
from brute import brute
from pwn import *
from hashlib import md5
import numpy as np
bru = 25
best_imgs = dict()
for p in xrange(1):
for r in xrange(1):
for k in xrange(bru):
conn = remote('localhost', 29281)
salt = conn.recvn(12)
for i in brute(length=6, ramp=False):
if True:
print('Broke md5 wit... |
import sqlite3
import graphviz
from DSGRN._dsgrn import *
from functools import reduce
from DSGRN.Query.Logging import LogToSTDOUT
class Database:
def __init__(self, database_name):
"""
Initialize a DSGRN database object
"""
self.dbname = database_name
self.conn = sqlite3.connect(database_name)
... |
# Lint as: python3
r"""Code example for a custom model, using PyTorch.
This demo shows how to use a custom model with LIT, in just a few lines of code.
We'll use a transformers model, with a minimal amount of code to implement the
LIT API. Compared to models/glue_models.py, this has fewer features, but the
code is mor... |
#!/usr/bin/python
# Author: Vadim Gumerov
# 03.04/2019
import sys, getopt
import re
from ete2 import Tree
from Bio import SeqIO
from Bio import Entrez
import time
import collections
import urllib
import json
import math
import multiprocessing
import time
#pip install timeout-decorator
import timeout_decorator
manager ... |
# coding=utf8
import os
from threading import Thread
try:
from queue import Queue, Empty as QueueEmpty
except ImportError:
from Queue import Queue, Empty as QueueEmpty
import requests
import logging
import traceback
error_logger = logging.getLogger('error')
error_logger.setLevel(logging.ERROR)
ERROR_STATU... |
from __future__ import absolute_import
from rest_framework.response import Response
from sentry.api.bases.project import ProjectEndpoint
from sentry.api.serializers import serialize
from sentry.models import EnvironmentProject
environment_visibility_filter_options = {
'all': lambda queryset: queryset,
'hidd... |
# --------------------------
# UFSC - CTC - INE - INE5663
# Exercício da Tribo
# --------------------------
# Classe responsável por criar uma tribo
#
from model.tribo import Tribo
from view.paineis.painel_abstrato import PainelAbstrato
class PainelCriaTribo(PainelAbstrato):
def __init__(self, iu):
super... |
# Used in setup.py
# -*- coding: utf-8 -*-
VERSION = "0.1.1"
PROJECT_PACKAGE_NAME = "lupupy"
PROJECT_LICENSE = "MIT"
PROJECT_URL = "http://www.github.com/majuss/lupupy"
PROJECT_DESCRIPTION = "A python cli for Lupusec alarm panels."
PROJECT_LONG_DESCRIPTION = (
"lupupy is a python3 interface for"
" the Lupus Ele... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File: globvars.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
import six
import argparse
__all__ = ['globalns', 'use_global_argument']
if six.PY2:
class NS:
pass
else:
import types
NS = types.SimpleNamespace
globalns = NS()
def use_global_argument(a... |
# LIBTBX_SET_DISPATCHER_NAME iotbx.pdb.sort_atoms
from __future__ import absolute_import, division, print_function
from libtbx.utils import Usage
import sys
import iotbx.pdb
import mmtbx.model
master_phil_str = """
file_name = None
.type = path
.multiple = False
.optional = False
.style = hidden
"""
def show... |
"""A dumb and slow but simple dbm clone.
For database spam, spam.dir contains the index (a text file),
spam.bak *may* contain a backup of the index (also a text file),
while spam.dat contains the data (a binary file).
XXX TO DO:
- seems to contain a bug when updating...
- reclaim free space (currently, space once o... |
import pickle
from airflow import DAG
from airflow.hooks.postgres_hook import PostgresHook
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
from airflow.utils import timezone
from sklearn.ensemble import RandomForestClassifier
default_args = {
... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author: toddler
import jieba
import re
import os
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt
def cut_analyze(input_file):
"""
:param input_file: 输入带切词分析的文本路径
:return: (list1, list2) list1切词处理后的列表结果, list2输出... |
import sys
import math
import pathlib
import bpy
import mathutils
from PIL import Image
modelDir = pathlib.Path(__file__).parent.absolute()
scn = bpy.context.scene
images_created = 0
def update_camera(camera, focus_point=mathutils.Vector((0.0, 0.0, 0.0)), distance=10.0):
"""
Focus the camera to a focus point... |
from random import randint
from timeit import timeit
from matplotlib import pyplot as plt
import matplotlib.patches as mpatches
def generate_dataset(n_inst, n_attr, n_val):
instances = []
for i in range(n_inst):
i = {}
for j in range(n_attr):
i[str(j)] = randint(1, n_val)
... |
import starlette
from starlette.middleware import Middleware
from starlette.routing import Match
from ddtrace import config
from ddtrace.contrib.asgi.middleware import TraceMiddleware
from ddtrace.internal.logger import get_logger
from ddtrace.internal.utils.wrappers import unwrap as _u
from ddtrace.vendor.wrapt impor... |
# -*- coding: utf-8 -*-
import scrapy
import json
import re
from locations.items import GeojsonPointItem
class McDonaldsHUSpider(scrapy.Spider):
name = "mcdonalds_hu"
allowed_domains = ["www.mcdonalds.hu"]
start_urls = (
'https://www.mcdonalds.hu/ettermeink',
)
def store_hours(self, data... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import re
from re import sub
from typing import Any, List, Text
from functools import reduce
from rasa.nlu.components import Component
from rasa.nlu.config import RasaNLU... |
# flake8: noqa
# pylint: disable
from __future__ import annotations
import dataclasses
import io
import pprint
import sys
from enum import Enum
from typing import Any, BinaryIO, Dict, List, Tuple, Type, Callable, Optional, Iterator
from blspy import G1Element, G2Element, PrivateKey
from wheat.types.blockchain_format... |
from setuptools import setup
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(name= 'dicomcat',
version= '0.1',
description='A simple python-based tool based on imgcat f... |
try:
f = open("myfile","w")
a,b = [int(x) for x in input("Enter two numbers:").split()]
c = a/b
f.write("Writing %d into file" %c)
except ZeroDivisionError:
print("Division by zero is not allowed")
print("Please enter a non zero number")
finally:
f.close() # Writi... |
# Copyright 2020 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
import json
from functools import partial
import time
import jax.numpy as np
import jax.random as random
from jax import jit... |
from os import path
from shutil import make_archive
import os
from json import load, dump
PLUGINEXTENSION = '.epf'
DESCRIPTIONNAME = 'description'
def packPluginFromFolder(folderPath):
folderPath = path.abspath(folderPath)
if not path.exists(folderPath):
raise FileNotFoundError('the folder does not ... |
from .utils import TestCase
from .utils import build_and_test_module
class Test(TestCase):
def test_enums(self):
build_and_test_module('enums')
def test_invalid_string_enum_member_value(self):
self.assert_transpile_raises(
'@enum\n'
'class Foo:\n'
' A =... |
import logging
def configure_logging(logfile_path):
''' Initialize logging defaults for in-notebook messages and
'log.info' file written to store intermediate results during analysis of each defect
To use, the following lines must be added to the code:
import LogFileSetup as lfs
logg... |
import io
import os
import re
from setuptools import find_packages
from setuptools import setup
def read(filename):
filename = os.path.join(os.path.dirname(__file__), filename)
text_type = type(u"")
with io.open(filename, mode="r", encoding='utf-8') as fd:
return re.sub(text_type(r':[a-z]+:`~?(.*?... |
# This is an edited version of https://github.com/minhptx/iswc-2016-semantic-labeling, which was edited to use it as a baseline for Tab2KG (https://github.com/sgottsch/Tab2KG).
import logging
from elasticsearch.exceptions import RequestError
from elasticsearch.helpers import scan, bulk
from lib.utils import get_index... |
#!/home/adam/Documents/revkit-1.3/python
#!/usr/bin/python
# RevKit: A Toolkit for Reversible Circuit Design (www.revkit.org)
# Copyright (C) 2009-2011 The RevKit Developers <revkit@informatik.uni-bremen.de>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Gener... |
#!/usr/bin/env python3
# This code greatly inspires itself from http://aosabook.org/en/500L/a-web-crawler-with-asyncio-coroutines.html
import cgi
from collections import namedtuple
import os
import re
import logging
import urllib
import asyncio
import aiohttp
from asyncio import Queue
import time
LOGGER = logging.get... |
# Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2019-Present Datadog, Inc.
from datadog_api_client.v1.model_utils import (
ModelNormal,
cached_property,
... |
"""
Admin views for ecommerce models
"""
from django.contrib import admin
from ecommerce.models import (
Coupon,
CouponAudit,
CouponInvoice,
CouponInvoiceAudit,
Line,
Order,
OrderAudit,
Receipt,
RedeemedCoupon,
RedeemedCouponAudit,
UserCoupon,
UserCouponAudit,
)
from mi... |
# Licensed to the StackStorm, Inc ('StackStorm') under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use th... |
import torch as th
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.autograd import Variable
import numpy as np
from convlab2.policy.larl.multiwoz.latent_dialog.enc2dec.base_modules import BaseRNN
from convlab2.policy.larl.multiwoz.latent_dialog.utils import cast_type, LONG, ... |
# coding=utf-8
"""
Send metrics to a [graphite](http://graphite.wikidot.com/) using the default
interface.
Graphite is an enterprise-scale monitoring tool that runs well on cheap
hardware. It was originally designed and written by Chris Davis at Orbitz in
2006 as side project that ultimately grew to be a foundational... |
import calendar
import datetime
import json
import os
import os.path
import shutil
import tqdm
import traceback
from concurrent.futures import ThreadPoolExecutor
import urllib.error
import urllib.parse
from sqlalchemy import and_
from sqlalchemy import or_
import sqlalchemy.exc
if __name__ == "__main__":
import log... |
import re
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union
import orjson
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.core.exceptions import ValidationError
from django.db import connection
from django.http import HttpRequest,... |
mocked_indicators = [
{
"type": "URL",
"industry_type": [
"IT",
"online gaming",
"Military"
],
"value": "https://test.domainos.com?test=true&id=32423",
"handling_condition": "GREEN",
"discovered_at": "2020-12-31T14:18:26+0000",
... |
# Class: blueprint for creating new objects
# Object: instances of a class
# Class: Human
# Objects: John, Mary, Jack
class Point:
def draw(self):
print("draw")
point = Point()
print(type(point))
print(isinstance(point, Point)) |
# Copyright 2015 EasyStack, Inc.
#
# 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 writ... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListCaseLabelsResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
... |
import arrow
from config.app import celery_app, app
from models.container_image_registry import RegistryCredential
from models.scheduler import Scheduler
from models.setting import Setting
from croniter import croniter
from utils import constants
import time
from datetime import datetime
from utils.helper import websoc... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='fn_bluecoat_recategorization',
version='1.0.0',
license='<<insert here>>',
author='<<your name here>>',
author_email='you@example.com',
url='<<your company url>>',
description="Resilient ... |
'''
Created on 08.04.2019
@author: mort
ipywidget interface to the GEE for IR-MAD
'''
import ee, time, warnings, math
import ipywidgets as widgets
from IPython.display import display
from ipyleaflet import (Map,DrawControl,TileLayer,
basemaps,basemap_to_tiles,
LayersCo... |
"""
Get the data from covidtracking.com.
Store it in a knpsValue.
Assign to a knpsVariable.
Everytime we run this, the knpsVariable is not changed.
But the knpsValue it points to should be updated.
i.e. a new knpsValue is created.
"""
import requests
import json
from collections import defaultdict
from datetime import ... |
"""
WSGI config for serveup project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTI... |
from pypy.rpython.test.test_llinterp import gengraph, interpret
from pypy.rlib import rgc # Force registration of gc.collect
import gc
def test_collect():
def f():
return gc.collect()
t, typer, graph = gengraph(f, [])
ops = list(graph.iterblockops())
assert len(ops) == 1
op = ops[0][1]
... |
#!/usr/bin/python
# Copyright 2001 Dave Abrahams
# Copyright 2011 Steven Watanabe
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE.txt or copy at
# https://www.bfgroup.xyz/b2/LICENSE.txt)
import BoostBuild
def simple_args(start, finish):
return " : ".join("%d" % x fo... |
import caffe
import re
from pittnuts import *
import os
import matplotlib.pyplot as plt
import argparse
import caffeparser
import caffe_apps
import numpy as np
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--original_alexnet', type=str, required=True,help="The original alex... |
import threading
try:
from .grab import Image
except:pass
def grab_bytes():
return Image().asbytes
def send(s,a):
s.post(b's'+grab_bytes(),a)
def show_bytes(r):
if not r.startswith('s'):return
Image(r[1:]).show()
def conf(s,a):
def _conf():
while True:
send(s,a)
threading... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import time
import argparse
import sys
import numpy as np
import torch
import torch.optim as optim
from tqdm import tqdm
from network.BEV_Unet import BEV_Unet
from network.ptBEV import ptBEVnet
from dataloader.dataset import collate_fn_BEV,collate_fn_BEV_test,Se... |
from .playlist import Playlist
from .video import Video
__all__ = [
'Playlist',
'Video',
] |
class Solution(object):
def mySqrt(self, x):
if x<2:
return x
low = 0
high = x
result=0
while(low<=high):
mid = (low+high)//2
if(mid*mid==x):
return mid
elif(mid*mid<x):
low = mid+1
... |
# Copyright (c) 2012 NTT DOCOMO, INC.
# 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 requ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.