content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import scapy.all as scapy
import time
from iemlav import logger
class SynFlood(object):
"""SynFlood Class."""
def __init__(self, debug=False):
"""
Initialize SynFlood.
Args:
debug (bool): Log on terminal or not
Raises:
None
Returns:
... | python |
# -*- coding: utf8 -*-
# test encoding: à-é-è-ô-ï-€
# Copyright 2021 Adrien Crovato
#
# 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
#
# Unl... | python |
# name: person_builder.py
# version: 0.0.1
# date: 20211225
# author: Leam Hall
# desc: Build a person.
from person import Person
class PersonBuilder:
def set_data(self, person, data = {}):
person.idx = data.get('idx', -1)
person.gender = data.get('gender', '')
pe... | python |
import rasterio
from sklearn.cluster import AgglomerativeClustering
from shapely.geometry import Polygon
from shapely.ops import nearest_points
from math import sqrt
from gisele import initialization
from shapely import geometry
from gisele.functions import *
from math import *
#from gisele import LV_routing_new_strate... | python |
from typing import Any, Dict, Optional, Union
import httpx
from ...client import AuthenticatedClient
from ...models.osidb_api_v1_schema_retrieve_format import OsidbApiV1SchemaRetrieveFormat
from ...models.osidb_api_v1_schema_retrieve_lang import OsidbApiV1SchemaRetrieveLang
from ...models.osidb_api_v1_schema_retrieve... | python |
def work_well():
print("ok")
return "ok"
def say_hello():
print("hello")
return "hello"
| python |
# uses minimax to look ahead
import sys
from functools import partial
from game import *
import interactive_game
def compute_score(board, res=TURN_OK):
score = board[0]**5 \
+ board[1]**4 + board[4]**4 \
+ board[2]**2 + board[5]**2 + board[8]**2 \
+ board[3] + board[6] + board[... | python |
"""Module with function to regularize a 2D curve (with uniform resolution)."""
import math
import numpy
def _get_perimeter(x, y):
"""Return the perimeter of the geometry.
Parameters
----------
x : numpy.ndarray
x-coordinate of the points along the curve.
y : numpy.ndarray
y-coord... | python |
from bstools import bsSsh
from bstools import bsPrint
from bstools import bsTime
name = "bstools"
__version__ = "0.1.9" | python |
"""
libmonster.py - mixed support library
# TODO: consider replacing pauthor in keyid with _bibtex.names
# TODO: enusure \emph is dropped from titles in keyid calculation
"""
import re
from heapq import nsmallest
from collections import defaultdict
from itertools import groupby
from operator import itemgetter
from cs... | python |
## Code taken from https://github.com/vqdang/hover_net/blob/master/metrics/stats_utils.py
import warnings
import numpy as np
import scipy
from scipy.optimize import linear_sum_assignment
# --------------------------Optimised for Speed
def get_fast_aji(true, pred):
"""AJI version distributed by MoNuSeg, has no p... | python |
from ivy import ivy_module as im
from ivy.ivy_compiler import ivy_from_string
from ivy.tk_ui import new_ui
from ivy import ivy_utils as iu
from ivy import ivy_check as ick
from ivy import ivy_logic as il
prog = """#lang ivy1.5
type t
type p
relation sent(X:p,Y:t)
function pid(X:t):p
axiom X:t = X
axiom X:t < Y & Y... | python |
# -*- coding: utf-8 -*-
# Ambry Bundle Library File
# Use this file for code that may be imported into other bundles
| python |
import kydb
from portfolio_management.common.base_item import BaseItem, Factory
from portfolio_management.common.account_container_mixin import AccountContainerMixin
from portfolio_management.common.position_mixin import PositionMixin
from portfolio_management.portfolio.event import Event, EventType
from portfolio_mana... | python |
uctable = [ [ 48 ],
[ 49 ],
[ 50 ],
[ 51 ],
[ 52 ],
[ 53 ],
[ 54 ],
[ 55 ],
[ 56 ],
[ 57 ],
[ 194, 178 ],
[ 194, 179 ],
[ 194, 185 ],
[ 194, 188 ],
[ 194, 189 ],
[ 194, 190 ],
[ 217, 160 ],
[ 217, 161 ],
[ 217, 162 ],
[ 217, 163 ],
[ 217, 164 ],
[ 217, 165 ],
[ 217, 166 ],
... | python |
import functools
import time
import argparse
import sys
import asyncio
import cocrawler.burner as burner
import cocrawler.config as config
def burn(dt, data):
t0 = time.clock()
end = t0 + dt
while time.clock() < end:
pass
return 1,
async def work():
while True:
dt, data = await... | python |
## Script (Python) "updateProductionStage"
##parameters=sci
# Copy the object in development to review and production.
object = sci.object
st = object.portal_staging
st.updateStages(object, 'dev', ['review', 'prod'],
sci.kwargs.get('comment', ''))
| python |
"""
Benchmark Sorted Dictionary Datatypes
"""
import warnings
from .benchmark import *
# Tests.
@register_test
def contains(func, size):
for val in lists[size][::100]:
assert func(val)
@register_test
def getitem(func, size):
for val in lists[size][::100]:
assert func(val) == -val
@register_... | python |
import sys
import salt.client.ssh
import salt.utils.parsers
class SaltSSH(salt.utils.parsers.SaltSSHOptionParser):
"""
Used to Execute the salt ssh routine
"""
def run(self):
if "-H" in sys.argv or "--hosts" in sys.argv:
sys.argv += ["x", "x"] # Hack: pass a mandatory two option... | python |
import os
import importlib
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ohlc
# from matplotlib.finance import volume_overlay
import matplotlib.ticker as ticker
from catalyst.exchange.exchange_bundle import ExchangeBundle
from catalyst.exchange.excha... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Atmosphere container base class definitions
Created on Wed Nov 16 16:37:03 2016
@author: maxwell
"""
from collections import MutableMapping
import numpy as np
from . import constants
from .readprof import readprof, readprof_ozone
class Atmosphere(MutableMapping):... | python |
# -*- coding:utf-8 -*-
#autor -> manoel vilela
#gerando graficos em relação a eficiencia dos algoritmos de ordenação bubble, merge and personal
import pylab
def extract_data(file_name):
data = open(file_name, "r").read().split()
data = [element.split() for element in data.split("=")]
vector, values = ... | python |
import graphene
from django.db.models import F, Q
from tabletop.models import DurationType, Game
from tabletop.schema import GameNode
from tabletop.utils.graphene import optimize_queryset
class Query(object):
games = graphene.List(
GameNode,
id=graphene.UUID(),
query=graphene.String(),
... | python |
#General imports====================================
from html.parser import HTMLParser
from urllib import parse
#Finds all anchor <a> tags in a website============
class LinkFinder(HTMLParser):
def __init__(self, base_url, page_url):
super().__init__()
self.base_url = base_url
self.page_... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2017 Ganggao Zhu- Grupo de Sistemas Inteligentes
# gzhu[at]dit.upm.es
# DIT, UPM
#
# 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... | python |
"""
MIT License
Copyright (c) 2020-2021 Hyeonki Hong <hhk7734@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
in the Software without restriction, including without limitation the rights
to use, copy,... | python |
"""Command line tools for Flask server app."""
from os import environ
from uuid import UUID
from flask_script import Manager
from flask_migrate import MigrateCommand, upgrade
from app import create_app, db
from app.mongo import drop_mongo_collections
from app.authentication.models import User, PasswordAuthentication... | python |
import torch
from transformers import BertTokenizerFast
from colbert.modeling.tokenization.utils import _split_into_batches, _sort_by_length
class DocTokenizer():
def __init__(self, doc_maxlen):
self.tok = BertTokenizerFast.from_pretrained('bert-base-uncased')
self.doc_maxlen = doc_maxlen
... | python |
# -*- coding: utf-8 -*-
###########################################################################
# Copyright (c), The AiiDA team. All rights reserved. #
# This file is part of the AiiDA code. #
# ... | python |
import signal
import argparse
import logging as log
import os
from pathlib import Path
import errno
from alive_progress import alive_bar
from backupdef import BackupDef
from entries import FolderEntry
from diskspacereserver import DiskSpaceReserver
from util import sanitizeFilename
def backup(source: str, destinatio... | python |
import redis
def handler(message):
print("New message recieved:", message['data'].decode('utf-8'))
r = redis.Redis('10.14.156.254')
p = r.pubsub()
p.subscribe(**{'chat': handler})
thread = p.run_in_thread(sleep_time=0.5) # Создание потока для получения сообщий
print("Press Ctrl+C to stop")
while True:
try... | python |
#!/usr/bin/env python
"""
methrafo.train <reference genomes><input MeDIP-Seq bigWig> <input Bisulfite-Seq bigWig> <output model prefix>
e.g.
methrafo.train hg19 example_MeDIP.bw example_Bisulfite.bw output_trained_model_prefix
"""
import pdb,sys,os
import gzip
from File import *
import re
import pyBigWig
from scipy.... | python |
# -*- coding: utf-8 -*-
"""
Initialize the Hanabi PyQT5 Interface.
"""
from PyQt5 import QtCore, QtGui
from PyQt5.QtGui import QPalette
from PyQt5.QtWidgets import QMainWindow, QDesktopWidget, QApplication
from py_hanabi.interface.hanabi_window import HanabiWindow
from py_hanabi.interface.window import Window
__aut... | python |
# Reference: https://github.com/zhangchuheng123/Reinforcement-Implementation/blob/master/code/ppo.py
import torch
def ppo_step(
policy_net,
value_net,
optimizer_policy,
optimizer_value,
optim_value_iter_num,
states,
actions,
returns,
advantages,
fixed_log_probs,
clip_epsi... | python |
#
# PySNMP MIB module SL81-STD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SL81-STD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:57:56 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,... | python |
from allauth.account.forms import ChangePasswordForm as AllauthChangePasswordForm
class ChangePasswordForm(AllauthChangePasswordForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
del self.fields["oldpassword"].widget.attrs["placeholder"]
del self.fields["password... | python |
"""Tests for the convention subsections."""
import re
import pytest
from tests.test_convention_doc import doctypes
@pytest.fixture(
scope="module",
params=[
pytest.param((index, subsection), id=subsection.identifier)
for section in doctypes.SECTIONS
for index, subsection in enumerat... | python |
from PKG.models import ResnetV2
import tensorflow as tf
class Classifier(tf.keras.models.Model):
def __init__(self, nclasses, weights=None):
super(Classifier, self).__init__()
self.nn = ResnetV2()
self.classifier = tf.keras.layers.Dense(nclasses)
self.activation = tf.keras.layers.... | python |
from helpers.observerpattern import Observable
from HTMLParser import HTMLParser
class DomBuilder(Observable, HTMLParser):
"""
This class is on charge of parse the plainHTML provided via a Reader and construct
a dom representation with it. DOM structure is decoupled from this class and need
to be passe... | python |
class Eventseverity(basestring):
"""
EMERGENCY|ALERT|CRITICAL|ERROR|WARNING|NOTICE|INFORMATIONAL|DEBUG
Possible values:
<ul>
<li> "emergency" - System is unusable,
<li> "alert" - Action must be taken immediately,
<li> "critical" - Critical condition,
<li> "error" ... | python |
from .attachment import Attachment
from .integration import Integration
from .message import Message
from .field import Field
| python |
""" 152. Maximum Product Subarray
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanatio... | python |
import numpy as np
import math
import matplotlib.pyplot as plt
from bandit import Bandit
from explore_then_exploit_agent import ExploreThenExploit
from MC_simulator import *
from epsilon_greedy_agent import EpsilonGreedy
from ubc1_agent import UBC1Agent
from report import plot
| python |
# -*- coding: utf-8 -*-
# import the necessary packages
from tnmlearn.nn.conv import MiniVGGNet
from keras.optimizers import SGD
from tnmlearn.examples import BaseLearningModel
from tnmlearn.datasets import load_cifar10
# %%
class MiniVggNetCifar10(BaseLearningModel):
def __init__(self):
super(MiniVggNetCi... | python |
from app.order.domain.order import Order
from app.order.domain.order_repository import OrderRepository
class SqlOrderRepository(OrderRepository):
def __init__(self, session):
self.session = session
def save(self, order: Order):
self.session.add(order)
self.session.commit()
def fi... | python |
import os
import numpy as np
from copy import copy
from easyric.io import pix4d, geotiff, shp, plot
from easyric.calculate import geo2raw, geo2tiff, raw2raw
####################
# Software wrapper #
####################
class Pix4D:
def __init__(self, project_path, raw_img_path=None, project_name=None,
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 8 14:38:17 2018
@author: jgoldstein
"""
# try to get some simulated PTA data like in Jeff Hazboun's github https://github.com/Hazboun6/pta_simulations
import numpy as np
import glob, os
import matplotlib.pyplot as plt
plt.rcParams['figure.dpi'] =... | python |
N = int(input())
ans = 0
if N % 100 == 0:
ans = N // 100
else:
ans = (N // 100) + 1
print(ans)
| python |
#_*_ coding: utf-8 -*-
{
'name': "Carlosma7",
'summary': """
This is the summary of the addon, second try.""",
'description': """
This is the description of the addon.
""",
'author': "Carlos Morales Aguilera",
'website': "http://www.carlosma7.com",
'category': 'Personal project',
'version... | python |
#
# PySNMP MIB module BENU-HTTP-CLIENT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BENU-HTTP-CLIENT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:37:20 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... | python |
"""
.. module:: __init__
:synopsis: This is where all our global variables and instantiation
happens. If there is simple app setup to do, it can be done here, but
more complex work should be farmed off elsewhere, in order to keep
this file readable.
.. moduleauthor:: Dan Schlosser <dan@dan@... | python |
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# 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 |
""" Unit test for re module"""
import unittest
import re
class ReTests(unittest.TestCase):
def test_findall(self):
#Skulpt is failing all the commented out tests in test_findall and it shouldn't be
val = re.findall("From","dlkjdsljkdlkdsjlk")
self.assertEqual(len(val), 0)
val = re.f... | python |
import os
from setuptools import setup
def package_files(directory):
paths = []
for (path, directories, filenames) in os.walk(directory):
for filename in filenames:
paths.append(os.path.join('..', path, filename))
return paths
extra_files = package_files('sejits4fpgas/hw')
extra_files.... | python |
# ======================================================================================================================
# Fakulta informacnich technologii VUT v Brne
# Bachelor thesis
# Author: Filip Bali (xbalif00)
# License: MIT
# ======================================================================================... | python |
import numpy as np
import math
def nanRound(vs, *args, **kw):
def fun(v):
if math.isnan(v): return(v)
return np.around(v, *args, **kw)
return [fun(i) for i in vs]
| python |
import os
import sys
import pprint
from PIL import Image
from av import open
video = open(sys.argv[1])
stream = next(s for s in video.streams if s.type == b'video')
for packet in video.demux(stream):
for frame in packet.decode():
frame.to_image().save('sandbox/%04d.jpg' % frame.index)
if frame_cou... | python |
from markdownify import markdownify as md, ATX, ATX_CLOSED, BACKSLASH, UNDERSCORE
import re
nested_uls = """
<ul>
<li>1
<ul>
<li>a
<ul>
<li>I</li>
<li>II</li>
<li>III</li>
... | python |
from Assignment2 import *
def test_case1():
cost = [[0,0,0,0],
[0,0,5,10],
[0,-1,0,5],
[0,-1,-1,0]
]
print(UCS_Traversal(cost,1,[3]))
def test_case2():
cost = [[0,0,0,0,0],
[0,0,0,10,5],
[0,-1,0,5,0],
[0,-1,-1,0,0],
[0,-1,-1,5,0]
]
print(UCS_Traversal(cost,1,[3]))
def test_case3():
cos... | python |
import numpy as np
import sys, time, glob
#caffe_root = "/home/vagrant/caffe/"
#sys.path.insert(0, caffe_root + 'python')
import caffe
from sklearn.metrics import accuracy_score
from random import shuffle
from sklearn import svm
def init_net():
net = caffe.Classifier(caffe_root + 'models/bvlc_reference_caffenet/de... | python |
import numpy as np
import py2neo as pn
import random
import math
import copy
def create_ba_subgraph(M, m_0, n, relation):
# Generate Users-Friends un-directed subgraph
# Generate Users-Follower directed subgraph
node_list = []
for i in range(m_0):
node_list.append(pn.Node('User', name='user'... | python |
# coding=utf-8
from __future__ import print_function
import authcode
from sqlalchemy_wrapper import SQLAlchemy
from helpers import SECRET_KEY
def test_user_model():
db = SQLAlchemy('sqlite:///:memory:')
auth = authcode.Auth(SECRET_KEY, db=db, roles=True)
assert auth.users_model_name == 'User'
assert... | python |
# -*- coding: utf-8 -*-
def fluxo_caixa():
fluxo = db(MovimentoCaixa).select()
return locals()
def entradas():
entradas = db(Entradas).select()
return locals()
def n_entrada():
entrada_id = request.vars.entrada
if entrada_id is None:
form = SQLFORM(Entradas, fields=['descri... | python |
# (C) British Crown Copyright 2013 - 2018, Met Office
#
# This file is part of cartopy.
#
# cartopy is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option)... | python |
import sys, os, Jati
class Serve:
def run(self, host, port, sites, log_file, isSSL):
current_dir = os.getcwd()
if current_dir not in sys.path:
sys.path.insert(1, current_dir)
try:
jati = Jati.Jati(host=host, port=port, isSSL=None, log_file=log_file)
jati.... | python |
from django.contrib import admin
from .models import Classifier
admin.site.register(Classifier)
| python |
def cgi_content(type="text/html"):
return('Content type: ' + type + '\n\n')
def webpage_start():
return('<html>')
def web_title(title):
return('<head><title>' + title + '</title></head>')
def body_start(h1_message):
return('<h1 align="center">' + h1_message + '</h1><p align="center">')
def body_end():
return("... | python |
"""Class to host an MlModel object."""
import logging
import json
from aiokafka import AIOKafkaProducer, AIOKafkaConsumer
from model_stream_processor import __name__
from model_stream_processor.model_manager import ModelManager
logger = logging.getLogger(__name__)
class MLModelStreamProcessor(object):
"""Proces... | python |
# -*- coding:utf-8 -*-
from __future__ import print_function
import zipfile
import os
import shutil
import time
import property
import shutil
print('====================================\n\nThis Software Only For Android Studio Language Package Replace\nDevelop By Wellchang\n2019/03/20\n\n==============================... | python |
from collections import Iterable
from iterable_collections.factory import DefaultMethodStrategyFactory
class Collection:
def __init__(self, iterable, strategies):
self._iterable = None
self.iterable = iterable
self._strategies = strategies
def __getattr__(self, item):
if ite... | python |
#!/usr/bin/env python2
import os
import sys
# add the current dir to python path
CURRENT_DIR = os.path.expanduser(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, CURRENT_DIR)
os.system('cd %s ;git pull' % CURRENT_DIR)
from app import app
if 'SERVER_SOFTWARE' in os.environ:
import sae
application ... | python |
# MIT License
#
# Copyright (c) 2021 Douglas Davis
#
# 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... | python |
import numpy as np
import pandas as pd
import joblib
dataset = pd.read_csv("datasets/cleaned_cleveland.csv")
X = dataset.iloc[:, :-1]
y = dataset.iloc[:, -1]
from sklearn.neighbors import KNeighborsClassifier
regressor = KNeighborsClassifier(n_neighbors=21)
regressor.fit(X, y)
joblib.dump(regressor, "classificati... | python |
from flask import Flask
# 创建flask框架
# 静态文件访问的时候url匹配时,路由规则里的路径名字 默认值是、static
app = Flask(__name__, static_url_path='/static')
print(app.url_map)
# @app.route('/')
# def index():
# """处理index页面逻辑"""
# return 'nihao'
@app.route('/login.html')
def login():
"""登录的逻辑"""
# 读取login.html 并且返回
with open('login.htm... | python |
# -*- coding: utf-8 -*-
from setuptools import setup
import pathlib
here = pathlib.Path(__file__).parent.resolve()
long_description = (here / "README.md").read_text(encoding='utf-8')
setup(
name='zarr-swiftstore',
version="1.2.3",
description='swift storage backend for zarr',
long_description=long_d... | python |
import argparse
from config.config import Config
from dataset.factory import DatasetModule
from domain.metadata import Metadata
from logger import logger
from model.factory import ModelModule
from trainer.factory import TrainerModule
def main(args):
mode = args.mode.lower()
config_file_name = args.config.low... | python |
from qiskit.circuit.library import PauliFeatureMap
class ZZFeatureMap(PauliFeatureMap):
def __init__(
self,
feature_dimension,
reps=2,
entanglement="linear",
data_map_func=None,
insert_barriers=False,
name="ZZFeatureMap",
parameter_prefix="x",
):... | python |
#
# @lc app=leetcode.cn id=1 lang=python3
#
# [1] 两数之和
#
# https://leetcode-cn.com/problems/two-sum/description/
#
# algorithms
# Easy (48.55%)
# Likes: 8314
# Dislikes: 0
# Total Accepted: 1.1M
# Total Submissions: 2.2M
# Testcase Example: '[2,7,11,15]\n9'
#
# 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,... | python |
class DetFace:
def __init__(self, conf, bbox):
self.conf = conf
self.bbox = bbox
self.name = ''
| python |
from pathlib import Path
import tables
import pandas as pd
class Stream:
def __init__(self, path):
self.path = path
self.frame_id_list = self._frame_id_list()
self.frame_dict = {k:frame_id for k, frame_id in enumerate(self.frame_id_list)}
def _frame_id_list(self):
if not Path(... | python |
#!/usr/bin/env python
# encoding: utf-8
"""
@version: v1.0
@author: xiaxianba
@license: Apache Licence
@contact: scuxia@gmail.com
@site: http://weibo.com/xiaxianba
@software: PyCharm
@file: SimTrade.py
@time: 2017/02/06 13:00
@describe: 展期数据
"""
import csv
import datetime as pydt
import... | python |
import obswebsocket, obswebsocket.requests
import logging
import time
import random
from obs.actions.Action import Action
from obs.actions.ShowSource import ShowSource
from obs.actions.HideSource import HideSource
from obs.Permission import Permission
class Toggle(Action):
def __init__(self, obs_client, command_name... | python |
from collections import namedtuple
from . import meta, pagination, resource_identifier
class ToOneLinks(namedtuple('ToOneLinks', ['maybe_self', 'maybe_related'])):
"""
Representation of links for a to-one relationship anywhere in a response.
"""
__slots__ = ()
def __new__(cls, maybe_self=None, ... | python |
import random
import networkx as nx
from LightningGraph.LN_parser import read_data_to_xgraph, process_lightning_graph
LIGHTNING_GRAPH_DUMP_PATH = 'LightningGraph/old_dumps/LN_2020.05.13-08.00.01.json'
def sample_long_route(graph, amount, get_route_func, min_route_length=4, max_trials=10000):
"""
Sample src... | python |
# identifies patients with gout and thiazides
import csv
import statsmodels.api as statsmodels
from atcs import *
from icd import is_gout
highrisk_prescription_identified = 0
true_positive = 0
true_negative = 0
false_positive = 0
false_negative = 0
gout_treatment = allopurinol | benzbromaron | colchicin | febuxost... | python |
from AoCUtils import *
result = 0
partNumber = "1"
writeToLog = False
if writeToLog:
logFile = open("log" + partNumber + ".txt", "w")
else:
logFile = "stdout"
printLog = printLogFactory(logFile)
heights = {}
with open("input.txt", "r") as inputFile:
lines = inputFile.read().strip().split("\n")
for ... | python |
import setuptools
__version__ = "0.2.0"
__author__ = "Ricardo Montañana Gómez"
def readme():
with open("README.md") as f:
return f.read()
setuptools.setup(
name="Odte",
version=__version__,
license="MIT License",
description="Oblique decision tree Ensemble",
long_description=readme(... | python |
from setuptools import setup, find_packages
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='ddp_asyncio',
version='0.3.0',
description='Asynchronous DDP library',
long_description=long_description,
long_description_content_type='text/markdown',
url='https://git... | python |
import random
import pandas as pd
def synthetic(n, categorical=[], continuous=[]):
"""Synthetic dataset.
For each element in ``categorical``, either 0 or 1 is generated randomly.
Similarly, for each element in ``continuous``, a random value between 0 and
100 is generated.
Parameters
--------... | python |
# Copyright Aleksey Gurtovoy 2001-2004
#
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
#
# See http://www.boost.org/libs/mpl for documentation.
# $Source: /CVSROOT/boost/libs/mpl/preprocessed/preprocess_set.py... | python |
#!/usr/bin/env python
from Bio import SeqIO
from Bio.SeqUtils import GC
import click
import math
import random
import sys
CONTEXT_SETTINGS = {
"help_option_names": ["-h", "--help"],
}
@click.command(no_args_is_help=True, context_settings=CONTEXT_SETTINGS)
@click.argument(
"fasta_file",
type=click.Path(ex... | python |
# Copyright 2021 by B. Knueven, D. Mildebrath, C. Muir, J-P Watson, and D.L. Woodruff
# This software is distributed under the 3-clause BSD License.
# Code that is producing a xhat and a confidence interval using sequential sampling
# This is the implementation of the 2 following papers:
# [bm2011] Bayraksan, G., Mort... | python |
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from pants.backend.python.tasks.isort_run import IsortRun
from pants_test.pants_run_integration_test import PantsRunIntegrationTest, ensure_daemon
class IsortRunIntegrationTest(PantsRunI... | python |
import cv2
import random
import numpy as np
from utils.bbox_utils import iou, object_coverage
from utils.textboxes_utils import get_bboxes_from_quads
def random_crop_quad(
image,
quads,
classes,
min_size=0.1,
max_size=1,
min_ar=1,
max_ar=2,
overlap_modes=[
None,
[0.1, No... | python |
import torch
import torch.nn as nn
import torchvision
from . import resnet as resnet
from . import resnext as resnext
from torch.nn.init import kaiming_normal_,constant_,normal_
from core.config import cfg
import torch.nn.functional as F
import modeling.CRL as CRL
import modeling.cspn as cspn
import time
timer=time.t... | python |
# -*- coding: utf-8 -*-
# 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, softw... | python |
#
# @lc app=leetcode id=1022 lang=python3
#
# [1022] Sum of Root To Leaf Binary Numbers
#
# @lc code=start
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
... | python |
"""Setup script of django-blog-zinnia"""
from setuptools import find_packages
from setuptools import setup
import zinnia
setup(
dependency_links=[
"git+https://github.com/arrobalytics/django-tagging.git@027eb90c88ad2d4aead4f50bbbd8d6f0b1678954#egg=django-tagging",
"git+https://github.com/arrobalyt... | python |
from numbers import Number
from timegraph.drawing.plotter import Plotter
class Drawing:
def __init__(self):
self.plotter = Plotter()
def create_graph(self, title, db_response):
value_list = self.get_value_list(db_response.get_points())
self.plotter.plot_timeseries(value_list)
d... | python |
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def __init__(self):
self.res=[]
def printnode(self,start,end):
if start==end:
return
if start.next==... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.