content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python3
from argparse import ArgumentParser, Namespace
from datetime import date, datetime
from lxml import etree
from geopy.distance import vincenty
def main(arguments: Namespace):
aggregated_total_distance = sum(
track_distance(gpx_file)
for gpx_file in arguments.gpx_files)
... | python |
from django.contrib import admin
from .models import Tutorial, Complemento
admin.site.register(Tutorial)
admin.site.register(Complemento) | python |
# Generated by Django 2.1.3 on 2019-06-23 15:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pdfmerge', '0013_auto_20190623_1536'),
]
operations = [
migrations.AlterField(
model_name='pdfformfield',
name='fiel... | python |
# (C) Datadog, Inc. 2018
# All rights reserved
# Licensed under a 3-clause BSD style license (see LICENSE)
try:
# Agent5 compatibility layer
from checks.libs.win.pdhbasecheck import PDHBaseCheck
from checks.libs.win.winpdh import WinPDHCounter
except ImportError:
from .winpdh_base import PDHBaseCheck
... | python |
from __future__ import print_function
from __future__ import absolute_import
import cv2
from .tesisfunctions import Plotim,overlay,padVH
import numpy as np
from RRtoolbox.lib.plotter import Imtester
# http://opencv-python-tutroals.readthedocs.org/en/latest/py_tutorials/py_imgproc/py_morphological_ops/py_morphological... | python |
"""Bank module message types."""
from __future__ import annotations
import copy
from typing import List
from secret_sdk.core import AccAddress, Coins
from secret_sdk.core.msg import Msg
from secret_sdk.util.json import JSONSerializable, dict_to_data
__all__ = ["MsgSend", "MsgMultiSend", "MultiSendIO"]
import attr
... | python |
from datetime import datetime
import numpy as np
from pixiu.api.defines import (OrderCommand)
from pixiu.api.utils import (parse_datetime_string)
class Order(object):
def __init__(self, params={'volume': 0}):
self.order_dict = params.copy()
open_time = self.order_dict.get("open_time", None)
... | python |
import numpy as np
def eval_q2m(scores, q2m_gts):
'''
Image -> Text / Text -> Image
Args:
scores: (n_query, n_memory) matrix of similarity scores
q2m_gts: list, each item is the positive memory ids of the query id
Returns:
scores: (recall@1, 5, 10, median rank, mean rank)
gt_ranks: the best ran... | python |
import traceback
import uuid
import socket
import logging
import os
import base64
import zlib
import gzip
import time
import datetime
from http import cookies
from http.server import BaseHTTPRequestHandler
from http.server import HTTPServer
from threading import Thread
import WebRequest
def capture_expected_headers... | python |
import json
from concurrent.futures import ThreadPoolExecutor
import psutil
from notebook.base.handlers import IPythonHandler
from tornado import web
from tornado.concurrent import run_on_executor
try:
# Traitlets >= 4.3.3
from traitlets import Callable
except ImportError:
from .utils import Callable
cl... | python |
NOT_CONTINUATION = -1
CONTINUATION_START = 0
CONTINUATION = 1
CONTINUATION_END = 2
CONTINUATION_EXPLICIT = 3
#A function that returns the correct set of language regex expressions for functions
#and function like objects.
class languageSwitcher(object):
def __init__(self, ext):
self.lang = ""
sel... | python |
import logging
from typing import Any
from typing import List
from typing import Optional
from matchms.utils import filter_none
from matchms.utils import get_common_keys
from ..typing import SpectrumType
logger = logging.getLogger("matchms")
_retention_time_keys = ["retention_time", "retentiontime", "rt... | python |
#!/usr/bin/env python3
# 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 ... | python |
#
# cortexm.py
#
#
# Copyright (c) 2013-2017 Western Digital Corporation or its affiliates.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
... | python |
# Advent of Code - Day 5 - Part One
from collections import defaultdict
def result(data):
points = defaultdict(int)
for line in data:
a, b = line.split(' -> ')
x1, y1 = a.split(',')
x2, y2 = b.split(',')
x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
min_x, max_... | python |
# -*- coding: utf-8 -*-
"""Split Definition dataclass"""
from dataclasses import dataclass
from typing import Optional, List
from .rule import Rule
from .treatment import Treatment
from .environment import Environment
from .default_rule import DefaultRule
from .traffic_type import TrafficType
@dataclass
class Split... | python |
#!/usr/bin/env python
# Copyright (c) 2006-2010 Tampere University of Technology
#
# 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 rig... | python |
import serial
import struct
s = serial.Serial('/dev/cu.usbserial-A600e0ti', baudrate=19200)
def receive_msg():
print 'Receiving messages'
message = []
c = s.read()
while c != '\n':
message.append(c)
message = ''.join(message)
print 'Msg:', message
| python |
from django.conf.urls import url
from app05plus.views import index, register, mylogin
from app05plus.views import mylogout
urlpatterns = [
url(r"^newindex01$",index),
url(r"^register01$",register,name="register"),
url(r"^mylogin01$",mylogin,name="mylogin"),
url(r"^logout$",mylogout),
] | python |
import astropy.units as u
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.animation import FuncAnimation
from einsteinpy.metric import Schwarzschild
class ScatterGeodesicPlotter:
"""
Class for plotting static matplotlib plots.
"""
def __init__(
self, mass, time=0 * u.s, at... | python |
import os, sys
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import scipy.signal
from classy import Class
from helper import cache_grendel, cropsave, grendel_dir
"""
For just one of the boxes, plot the absolute CONCEPT
and GADGET spectra over time, including a = a_begin.
"""
textwidth = 504... | python |
import sys
import errno
from contextlib import contextmanager
from lemoncheesecake.cli.command import Command
from lemoncheesecake.cli.utils import auto_detect_reporting_backends, add_report_path_cli_arg, get_report_path
from lemoncheesecake.reporting import load_report
from lemoncheesecake.reporting.backends.console ... | python |
import torch
from torch.utils.data import Dataset
class GenericDataSet(Dataset):
def __init__(self,
x_inputs: torch.Tensor,
y_targets: torch.Tensor):
if x_inputs.size()[0] != y_targets.size()[0]:
raise Exception("row count of input does not match targets")
... | python |
from abc import ABC, abstractmethod
from typing import Iterable, Mapping, Optional
from bankroll.model import AccountBalance, Activity, Position
from .configuration import Settings
# Offers data about one or more brokerage accounts, initialized with data
# (e.g., exported files) or a mechanism to get the data (e.g.... | python |
"""Integration platform for recorder."""
from __future__ import annotations
from homeassistant.core import HomeAssistant, callback
from . import ATTR_AVAILABLE_MODES, ATTR_MAX_HUMIDITY, ATTR_MIN_HUMIDITY
@callback
def exclude_attributes(hass: HomeAssistant) -> set[str]:
"""Exclude static attributes from being r... | python |
from django.shortcuts import render
from .models import Image, Video
from .serializers import ImageSerializer, VideoSerializer
from accounts.permissions import isAdminOrReadOnly
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import ModelViewSet
# Create you... | python |
# Copyright (c) 2014, Oracle and/or its affiliates. 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
#
# ... | python |
"""This module provides a mock callable class."""
from __future__ import annotations
import queue
import unittest.mock
from typing import Any, Dict, NamedTuple, Optional, Tuple
from .consumer import ConsumerAsserter, MockConsumerGroup
class MockCallableGroup:
"""This class implements a group of callables."""
... | python |
# Is Prime
# determine whether the number is prime or not
class isPrime:
def isPrime(self, n):
i = 2
while i * i <= n:
if n % i == 0:
return False
i += 1
return True
ip = isPrime()
print(ip.isPrime(5)) | python |
#!/bin/env python
import platform, socket, random, time
_appname_="slowloris"
_version_="0.1"
_description_="fastly take down the web"
_author_="blackc8"
ncol ="\033[0m"
bold ="\033[1m"
dim ="\033[2m"
uline ="\033[4m"
reverse="\033[7m"
red ="\033[31m"
green ="\033[32m"
yellow ="\033[33m"
blue ="\033[34m"... | python |
import sys, os
import allel
import random
import numpy as np
from diploshic.msTools import *
from diploshic.fvTools import *
import time
(
trainingDataFileName,
totalPhysLen,
numSubWins,
maskFileName,
vcfForMaskFileName,
popForMask,
sampleToPopFileName,
unmaskedGenoFracCutoff,
chrAr... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: second/protos/train.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.... | python |
'''
Created on Nov 9, 2011
@author: ppa
'''
from analyzer.lib.errors import Errors, UfException
class DAMFactory(object):
''' DAM factory '''
@staticmethod
def createDAM(dam_name, config):
''' create DAM '''
if 'yahoo' == dam_name:
from analyzerdam.yahooDAM imp... | python |
from pydantic import BaseModel
class ProfileStats(BaseModel):
visits: int = 0
views: int = 0
counters: dict = {}
| python |
import pyautogui
import time
import cv2
import numpy as np
import imutils
def ImageDetection(temp_img,threshold,img_type):
image = pyautogui.screenshot()
img_bgr = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
img_gray = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2GRAY)
# 0 is for grayscale
template = cv2.imread(tem... | python |
"""
Finds the dictionary for the measurement specification based on the name of the measurement.
"""
def find_measurement_spec(monitoring_system_specs, measurement_type):
"""
Scans the list of specs and returns dictionary of specifications for the named measurement type
Parameters
----------
... | python |
# HeadPhoneJacks Cause Vaccines
# Softdev2 pd8
# K#06: Yummy Mango Py
#2019-02-28
import pymongo
SERVER_ADDR=""
connection =pymongo.MongoClient(SERVER_ADDR)
db = connection.test
collection = db.restaurants
def boro_find(borough):
'''
finds restaurants by borough and returns them in a list.
'''
restua... | python |
'''
Function:
AI玩俄罗斯方块
Author:
Charles
公众号:
Charles的皮卡丘
'''
import copy
import math
from modules.utils import *
'''AI玩俄罗斯方块'''
class TetrisAI():
def __init__(self, inner_board):
self.inner_board = inner_board
'''获得下一步的行动'''
def getNextAction(self):
if self.inner_board.current_tetris == tetrisShape().shape_e... | python |
import requests
import urllib.request
import time
from bs4 import BeautifulSoup
import json
import csv
filecsv = open('SouqDataapple.csv', 'w',encoding='utf8')
# Set the URL you want to webscrape from
url = 'https://saudi.souq.com/sa-ar/apple/new/a-c/s/?section=2&page='
file = open('SouqDataapple.json','w',encoding='ut... | python |
#!/usr/bin/python
#
# Scraper for libraries hosted at jcenter and custom maven repos
# Retrieves jar|aar files along with some meta data
# @author erik derr [derr@cs.uni-saarland.de]
#
import sys
import json
import urllib2
import datetime
import os
import errno
import zipfile
import traceback
import xml.etree.ElementT... | python |
#!/usr/bin/env python
#
# Copyright (c) 2018 Intel Labs.
#
# authors: Bernd Gassmann (bernd.gassmann@intel.com)
#
"""
Actor registry class for carla-id mapping
"""
class ActorIdRegistry(object):
"""
Registry class to map carla-ids (potentially 64 bit)
to increasing numbers (usually not exceeding 32 bit)... | python |
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to ... | python |
from typing import Optional, Union
from torch_sparse import SparseTensor
from torch_geometric.data import Data, HeteroData
from torch_geometric.transforms import BaseTransform
from torch_geometric.utils import sort_edge_index
class ToSparseTensor(BaseTransform):
r"""Converts the :obj:`edge_index` attributes of ... | python |
from __future__ import print_function
import re
import time
from ...version import __version__
HEADER_FMT = '''\
/**
* The MIT License (MIT)
*
* Copyright (c) 2018 Erik Moqvist
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* fi... | python |
from traffic.imports.builtins import SequenceType, sub
def concat(strings: SequenceType[str], separator: str) -> str:
return "".join(s if i == 0 else separator + s for i, s in enumerate(strings))
def to_func_name(name: str):
return sub(r"\W", "_", name).lower()
| python |
try:
import urllib.parse as urlparse
except ImportError:
import urlparse
from aws_xray_sdk.core.models import http
from aws_xray_sdk.ext.flask.middleware import XRayMiddleware as OrigMiddleware
from flask import request
__all__ = 'XRayMiddleware',
class XRayMiddleware(OrigMiddleware):
def _before_reques... | python |
# Exercício Python 069: Crie um programa que leia a idade e o sexo de várias pessoas. A cada pessoa cadastrada,
# o programa deverá perguntar se o usuário quer ou não continuar. No final, mostre:
# A) quantas pessoas tem mais de 18 anos.
# B) quantos homens foram cadastrados.
# C) quantas mulheres tem menos de 20 anos.... | python |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from __future__ import annotations
import typing # noqa F401
import torch
from torch import Tensor
def _flip_sub_u... | python |
from numpy import *
class Nematic:
def __init__(self, xx=0, xy=0):
self.xx=xx
self.xy=xy
def angle(self):
return 0.5*arctan2(self.xy, self.xx)
def norm(self):
return sqrt(self.xx**2 + self.xy**2)
def __str__(self):
return "Nematic(%g, %g)"%(self.xx, self.xy) | python |
# this file serves as both a test suite and an illustration of how tracing
# responds to various AST node types
import re
from tracelib import macros, kite_trace, get_all_traced_ast_reprs
with kite_trace:
for i in range(5):
print i
print len([1, 2, 3, 1 + 1])
x = {1: 2}
# AugAssign
a = 0... | python |
import numpy as np
import mmap
import os
import glob
import re
class Uio:
"""A simple uio class"""
@staticmethod
def find_device_file(device_name):
device_file = None
r = re.compile("/sys/class/uio/(.*)/name")
for uio_device_name_file in glob.glob("/sys/class/uio/uio*/name"):
... | python |
# Wanderlust Wine - UK
# Tutorial from John Watson Rooney YouTube channel
import requests
from bs4 import BeautifulSoup
from requests.api import head
import pandas as pd
import re
wine_list = []
# Step 1 - Request
def request(x):
url = f'http://www.wanderlustwine.co.uk/buy-wine-online/page/{x}/'
headers = {'... | python |
import os.path
import tempfile
import maptools
import maptools.external
import pytest
@pytest.mark.skipif(not maptools.external.is_ccp4_available(), reason="requires CCP4")
def test_fit(ideal_map_filename, pdb_filename):
_, output_pdb_filename = tempfile.mkstemp()
_, log_filename = tempfile.mkstemp()
ma... | python |
#!/usr/bin/env python3
from otl866 import at89, util
import unittest
import os
class TestCase(unittest.TestCase):
def setUp(self):
"""Call before every test case."""
print("")
port = util.default_port()
self.verbose = os.getenv("VERBOSE", "N") == "Y"
self.tl = at89.AT89(po... | python |
##############################################################################
#
# Copyright (c) 2002 Zope Foundation and Contributors.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS I... | python |
# batch running of experiments
import os
import getpass
import argparse
from utils import *
from runmm2 import Simulation
def CleanState ():
os.system('sudo killall python2 receiver sender mm-link mm-delay >/dev/null 2>&1 ')
# os.system('sudo ../ccp-kernel/ccp_kernel_unload')
# os.system('sudo ../ccp-kernel/cc... | python |
from file_utilities import readCSVFile
from PlotterLine import PlotterLine
solution = readCSVFile("output.csv")
a_liq_plotter = PlotterLine("Position", "Volume Fraction")
a_liq_plotter.addSet(solution["x"], solution["a_liq"], "$\\alpha_\ell$", color=4, linetype=2)
a_liq_plotter.save("volume_fraction.png")
r_liq_plot... | python |
"""
Benchmarks for array expressions.
"""
import numpy as np
# @jit(nopython=True)
def sum(a, b):
return a + b
# @jit(nopython=True)
def sq_diff(a, b):
return (a - b) * (a + b)
# @jit(nopython=True)
def rel_diff(a, b):
return (a - b) / (a + b)
# @jit(nopython=True)
def square(a, b):
# Note this is... | python |
"""
Example usages:
python py/pdf_to_img.py -f data/test_pdfs/00026_04_fda-K071597_test_data.pdf -p 4 -o .
python py/pdf_to_img.py -f data/test_pdfs/00026_04_fda-K071597_test_data.pdf -p 4-9 -o tmp
python py/pdf_to_img.py -f data/test_pdfs/00026_04_fda-K071597_test_data.pdf -p 1,2,4-9 -o tmp
Pages can ... | python |
import util
import os
def run():
util.process_usgs_source(
base_path=os.path.realpath(__file__),
url="http://pubs.usgs.gov/of/1998/of98-354/sfs_data.tar.gz",
uncompress_e00=True,
e00_path="sfs-geol.e00",
srs="+proj=lcc +lat_1=37.066667 +lat_2=38.433333 +lat_0=36.5 "
... | python |
class SleepSort(object):
"""
Sorting list of positive numbers using multi-threading
wherein thread will sleep for integer value and
add integer in result collection.
These multi-threads will add integers of input list
in such way that, result contains collection of sorted integers.
eg: [3, 1... | python |
"""
A precondition for the algorithm working is that the library 'requests'
must be installed on the device prior to using the program
"""
import requests
def auto_reconnect():
"""
Auto reconnect to password module
The ClientURL (cURL) command converted over to python for compatibility
... | python |
class DependencyPropertyDescriptor(PropertyDescriptor):
""" Provides an extension of System.ComponentModel.PropertyDescriptor that accounts for the additional property characteristics of a dependency property. """
def AddValueChanged(self,component,handler):
"""
AddValueChanged(self: DependencyPropertyDescrip... | python |
from pathlib import Path
import pytest
import caption_contest_data as ccd
filenames = list(ccd._api._get_response_fnames().keys())
DUELING_XFAIL = """These contests are dueling bandits, not cardinal bandits
(which have pairwise comparisons, not single caption ratings).
These aren't officially supported.
"""
def _... | python |
from pdip.cqrs.decorators import requestclass
from pdi.application.operation.CreateDataOperation.CreateDataIntegrationConnectionDatabaseRequest import \
CreateDataIntegrationConnectionDatabaseRequest
from pdi.application.operation.CreateDataOperation.CreateDataIntegrationConnectionFileRequest import \
CreateDa... | python |
"""Astronomical coordinate functions."""
import re,pdb
import numpy as np
from numpy import arccos,sin,cos
from math import pi
# constants
DEG_PER_HR = 360. / 24. # degrees per hour
DEG_PER_MIN = DEG_PER_HR / 60. # degrees per min
DEG_PER_S = DEG_PER_MIN / 60. # degrees per sec
DEG_PER_AMIN = 1./... | python |
import os
from functools import reduce
def xor(a,b):
c=bytearray()
for i,j in zip(a,b):
c.append(i^j)
return c
msg1="did you expect another rsa? sorry"
msg2=" to disappoint you. What you see is a bad use "
msg3="of the otp in encryption. It literally says one"
msg4=" and not multi time. masrt{think_out_of_the_b... | python |
import torch
from common.utils.clip_pad import *
import numpy as np
class BatchCollator(object):
def __init__(self, dataset, append_ind=False):
self.dataset = dataset
self.test_mode = self.dataset.test_mode
self.data_names = self.dataset.data_names
self.append_ind = append_ind
... | python |
from .leaderboards import *
#from .nominationAssessmentTeam import *
from .players import *
#from .publicRanking import *
#from .qualityAssuranceTeam import *
#from .rankingTeam import *
#from .websiteUser import *
| python |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | python |
# celcius to fahrenheit
import tkinter
class FahrenheiterGUI(): # :D
def __init__(self):
# create the main window
self.main_window = tkinter.Tk()
# set the title
self.main_window.title("Celcius to Fahrenheit")
# create three frames for this GUI
self.top_frame = tk... | python |
#!/usr/local/bin/python
# Physics Equation Graph
# Ben Payne <ben.is.located@gmail.com>
import sys
import os
lib_path = os.path.abspath('lib')
sys.path.append(lib_path) # this has to proceed use of physgraph
db_path = os.path.abspath('databases')
sys.path.append(lib_path) # this has to proceed use of physgraph
import ... | python |
import numpy as np
import torch
from colorsys import hsv_to_rgb
def get_camera_rays(c_pos, width=320, height=240, focal_length=0.035, sensor_width=0.032, noisy=False,
vertical=None, c_track_point=None):
#c_pos = np.array((0., 0., 0.))
# The camera is pointed at the origin
if c_track_p... | python |
from __future__ import with_statement
import re
import pytest
from flask import Flask
from blessed_extensions import csrf_token
from pg_discuss._compat import to_unicode
csrf_token_input = re.compile(
r'([0-9a-z#A-Z-\.]*)'
)
def get_csrf_token(data):
match = csrf_token_input.search(to_unicode(data))
ass... | python |
##############################################################################
# For copyright and license notices, see __manifest__.py file in root directory
##############################################################################
from odoo import api, fields, models, _
from odoo.exceptions import ValidationErro... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: helloworld.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.prot... | python |
# extract text from a img and its coordinates using the pytesseract module
import cv2
import pytesseract
# You need to add tesseract binary dependency to system variable for this to work
img =cv2.imread('img.png')
#We need to convert the img into RGB format
img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
hI,wI,k=img.shape
pr... | python |
from cwr_admin.resources.cwr import CWRFilesResource, CWRProcessorResource, \
CWRMatchResultResource, CWRFilesRemoveResource, CWRMatchBeginResource, \
CWRMatchRejectResource, CWRMatchAcceptResource, CWRMatchFeedbackResource
| python |
# This code is based on https://github.com/Ryo-Ito/spatial_transformer_network
import tensorflow as tf
def mgrid(*args, **kwargs):
low = kwargs.pop("low", -1)
high = kwargs.pop("high", 1)
low = tf.to_float(low)
high = tf.to_float(high)
coords = (tf.linspace(low, high, arg) for arg in args)
gr... | python |
#!/usr/bin/env python
#
# Copyright (c) 2016 Nutanix Inc. All rights reserved.
#
#
# Unit tests for test reports.
import inspect
import os
import unittest
from curie.node_failure_test.node_failure_test import NodeFailureTest
from curie.node_failure_data_loss_test.node_failure_data_loss_test \
import NodeFailureDataL... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2021-07-24 11:30:23
# @Author : Chenghao Mou (mouchenghao@gmail.com)
from typing import List
from datasketch import MinHash, MinHashLSH
from nltk.util import ngrams
from text_dedup.utils.group import get_group_indices
import multiprocessing as mp
import time
... | python |
from .binary_tree import * | python |
# -*- coding: utf-8 -*-
# KNN.py
import numpy as np
import matplotlib.pyplot as plt
import cv2
if __name__ == '__main__':
# 记住numpy的array有下面这种神器的用法
test = np.array([1,-2,3,-4,5])
res = test[test > 0]
# res = [1,3,5]
a = np.random.randint(0,101,(50,2),dtype=np.int64).astype(np.float32)
fl... | python |
"""
This is comment section
"""
def display_hello_world():
"""
This is a function to display "Hello World!"
:return: void
"""
print("Hello World!")
display_hello_world()
# Set text
texts = ["Hello", "World", "!"]
for text in texts:
print(text)
numberString = "917254"
for char in numberStri... | python |
import xmltodict
import defusedxml.ElementTree as ET
class Locations:
"""Provides lookup of raw location data based on UKPRN and LOCID"""
def __init__(self, root):
"""Build the locations lookup table
Locations are unique on UKPRN and LOCID
"""
self.lookup_dict = {}
f... | python |
from django.urls import path
from apps.contents.views import IndexView
urlpatterns = [
path('index/', IndexView.as_view()),
] | python |
import numpy as np
from data.external_data.maturities import convert_maturity
from data.external_data.yahoo import Yahoo
from data.local_data.parameters_generator import ParametersGenerator
from stochastic_process.markov_chain import MarkovChain, Sigma
from stochastic_process.risky_asset import RiskyAsset
class Data... | python |
# -*- coding: utf-8 -*-
import cv2
import numpy as np
from scipy.sparse.linalg import spsolve
def fix_source(source, mask, shape, offset):
mydict = {}
counter = 0
for i in range(mask.shape[0]):
for j in range(mask.shape[1]):
if mask[i][j]>127:
mydict[(i+offset[0], j+off... | python |
from typing import List, Optional, Tuple, Dict, Callable
import torch
from torch import Tensor
from tha2.poser.poser import PoseParameterGroup, Poser
from tha2.nn.batch_module.batch_input_module import BatchInputModule
from tha2.compute.cached_computation_func import TensorListCachedComputationFunc
class ... | python |
# test_ble_commands.py/Open GoPro, Version 1.0 (C) Copyright 2021 GoPro, Inc. (http://gopro.com/OpenGoPro).
# This copyright was auto-generated on Tue May 18 22:08:51 UTC 2021
import pytest
from construct import Int32ub
from open_gopro.ble_commands import BLECommunicator, BleCommands, BleSettings, BleStatuses
from op... | python |
from django.conf import settings
# - {% if cookiecutter.django_media_engine == S3 %}
from storages.backends.s3boto3 import S3Boto3Storage
class PrivateMediaStorage(S3Boto3Storage):
"""Media storage which disables public access by default
When you use this as the default storage it makes sense to
turn of... | python |
"""
Implementation of POSFrequencyPipeline for score ten only.
"""
import json
import re
from constants import ASSETS_PATH
from core_utils.article import ArtifactType
from core_utils.visualizer import visualize
from pipeline import CorpusManager, validate_dataset
class EmptyFileError(Exception):
"""
Custom e... | python |
#!/usr/bin/env python
"""Helper functions to store and get the selected backend"""
from collections import namedtuple
import logging
from dosna.util import named_module
log = logging.getLogger(__name__)
_current = None
AVAILABLE = ['ram', 'hdf5', 'ceph', 'sage', 's3']
# Currently there is no need for more fancy at... | python |
from helpers.runner import run_main
from helpers.cli import cmdout
def test_no_cmd(cmdout):
try:
run_main([])
except SystemExit:
pass
cmdout.assert_substrs_in_line(0, ["usage:"], on_stderr=True)
| python |
from ZstudentDAO import studentDAO
# We put in the data we get passed up from the json
#create
latestid = studentDAO.create(('Eilish', 22))
#find by id
result = studentDAO.findByID(latestid); # needs to be made into json object
print (result)
#update
studentDAO.update(('Liam',23,latestid))
result = studentDAO.findB... | python |
"""
Script to solve z-factor and gas density at the same time
Using Dranchuk and Aboukassem (1975)
"""
def dranchuk(T_pr, P_pr):
# T_pr : calculated pseudoreduced temperature
# P_pr : calculated pseudoreduced pressure
from scipy.optimize import fsolve # non-linear solver
import numpy as np
a1 ... | python |
# Generated by Django 3.0.2 on 2020-03-06 22:30
from django.db import migrations
import streamfield.fields
class Migration(migrations.Migration):
dependencies = [
('pagine', '0014_event_carousel'),
]
operations = [
migrations.AddField(
model_name='blog',
name='ca... | python |
from typing import Any, Optional
from rx.disposable import Disposable
from rx.core import typing
from .subject import Subject
from .innersubscription import InnerSubscription
class AsyncSubject(Subject):
"""Represents the result of an asynchronous operation. The last value
before the close notification, or ... | python |
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.utils.timezone import now
class BaseModel(models.Model):
created = models.DateTimeField(auto_now_add=True, verbose_name=_("Created, UTC"))
updated = models.DateTimeField(auto_now=True, verbose_name=_("Updated, UTC... | python |
# Testing various potentials.
from asap3 import *
from asap3.md.verlet import VelocityVerlet
from asap3.EMT2013Parameters import PtY_parameters
from ase.lattice.cubic import *
from ase.lattice.compounds import *
from numpy import *
from asap3.testtools import ReportTest
try:
import potResults
except ImportError:
... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.