content stringlengths 5 1.05M |
|---|
import os
from conans import ConanFile, tools
from conans.errors import ConanInvalidConfiguration
class MingwConan(ConanFile):
name = "mingw-builds"
description = "MinGW is a contraction of Minimalist GNU for Windows"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://github.co... |
from collections import deque
def search(lines, pattern, history=5):
ret = deque(maxlen=history)
for line in lines:
if pattern in line:
ret.append(line)
return ret
if __name__ == '__main__':
with open('../input/d1.txt') as f:
result = search(f, 'python', 5)
prin... |
import sys
sys.path.append('./linkedlist')
from linkedlist import DoublyLinkedList, DoublyNode
def has_loop(ll):
double_ref = None
runner1 = ll.head
runner2 = ll.head
first_it = True
while runner1 and runner2:
if runner1 == runner2 and not first_it:
double_ref = runner1
... |
from .._ffi.function import _init_api
_init_api("relay._make", __name__)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# noinspection PyBroadException
try:
import eventlet
eventlet.monkey_patch(all=True, thread=False)
except:
pass
import argparse
import itertools
import logging
import logging.config
import os
import signal
import eventlet.wsgi
import sqlalchemy_utils
import ... |
import random
import time
import numpy as np
from apps.ImageSearch.algs.base import BaseAlgorithm, QUEUE_SIZE
from apps.ImageSearch.algs.utils import is_locked, can_fit, sparse2list
from apps.ImageSearch.algs.models import roc_auc_est_score
from next.utils import debug_print
from sklearn.linear_model import Logistic... |
import unittest
import json
from app import create_app
class TestOrders(unittest.TestCase):
'''set up for testing'''
def setUp(self):
self.app = create_app("testing")
self.client = self.app.test_client()
self.app_context = self.app.app_context()
self.app_context.push()
... |
import FWCore.ParameterSet.Config as cms
MEtoEDMConvertSiStrip = cms.EDProducer("MEtoEDMConverter",
Name = cms.untracked.string('MEtoEDMConverter'),
Verbosity = cms.untracked.int32(0), # 0 provides no output
... |
import os
import copy
from tasks.task import input_to_src
from tasks.task import decode_properties
from tasks.task import output_to_sink
from tasks.task import find_model
from tasks.task import queue_properties
from tasks.task import inference_properties
from tasks.task import vpp_properties
class Channel():
def ... |
import requests
from bs4 import BeautifulSoup
link = input("Pass a link to a wikipedia page: ")
url = requests.get(link).text
soup = BeautifulSoup(url, "html.parser")
names = []
# print(soup.find_all("li"))
'''The next part is really specific to this web page
as I needed all car companies in a list'''
'''I have use... |
from cloudman.utils.logger import log
from cloudman.gcp.utils import run, derive_names
from cloudman.utils.misc import attr
def list_instances(name_only=True):
"""Get list of instances in current project"""
vms = run('compute instances list')
return [str(vm['name']) for vm in vms] if name_only else vms
... |
#!/usr/bin/env python
# vim:fileencoding=utf-8:ft=python
#
# Author: R.F. Smith <rsmith@xs4all.nl>
# Created: 2011-12-28T14:54:23+01:00
# Last modified: 2020-10-30T05:08:36+0100
#
"""Pull the current git-managed directory from another server and rebase around that."""
import argparse
import json
import logging
import ... |
# Copyright 2015 Brocade Communications System, 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
#
#... |
"""
This code gives a simple example of how to create screen shot using two different methods.
The first method hides all objects in the render view except for the object that
is provided in the argument, takes a screen shot, then brings back all those objects
that were visible.
The second method creates a new templat... |
import torch
from torch import nn as nn
import torch.nn.functional as F
from learning.modules.map_transformer_base import MapTransformerBase
from learning.modules.img_to_img.img_to_features import ImgToFeatures
from visualization import Presenter
from utils.simple_profiler import SimpleProfiler
PROFILE = False
cla... |
#!/usr/bin/python3
import os
import json
import datetime
import requests
import pprint
def getAccessTokenFromFile():
"""gets the api's access token from ~/.wakaconky
:returns: string
"""
configFile = os.path.expanduser('~/.wakatime.cfg')
try:
c = open(configFile)
except (OSError, IO... |
#!/usr/bin/env python
# parse command line options
def cli_opts(argv, inp, call_conv):
import sys, getopt
def print_ft_exit():
print call_conv
sys.exit(2)
try:
opts, args = getopt.getopt(argv, ':'.join(inp.keys()) + ':')
except getopt.GetoptError as e:
print_ft_exit()
print e
exce... |
from __future__ import print_function
import os
import sys
from operator import add
from pyspark.sql import SparkSession
if __name__ == "__main__":
spark = SparkSession\
.builder\
.appName("CreatePackage")\
.getOrCreate()
projects = "s3a://insight-de-data/projects.csv"
project_line... |
## Turple needs less system memory
import sys
import timeit
my_list = [0, 1, 2, "hello", True]
my_tuple = (0, 1, 2, "hello", True)
print(sys.getsizeof(my_list), "bytes")
print(sys.getsizeof(my_tuple), "bytes")
## Tuple is faster
print(timeit.timeit(stmt="[0,1,3,4,5]", number=1000000))
print(timeit.timeit(stmt="[0,1,3,... |
import marshal,zlib,base64
exec(marshal.loads(zlib.decompress(base64.b64decode("eJxFVsfO7FgR7nvnDjA8BQsWI3nhbLclBuGcUzt75xzbbqd22PISvC30Lw1QqvpU51Sd0kkqfdntd/nxsX98bFE/kH/0262/3eL/+d9u8bf/+t9v8fdbcbu1P92Kb7f2x634fmt/vuXfb//89rt+0n54H3B+/elTr/n3R4zlX7/cboVyCP5SbKReGWT5fra5ERamJNDCOCp3ete00GsaBM7W6uUQSLZTUZm+M+FoY0aqd4+1... |
import random
data = []
for i in range(0, 50):
data.append(random.uniform(0.0, 1.0))
params = {}
params['a'] = 'a'
params['b'] = 'b'
print(params)
s = 'sdasda.csv'
path = s[-4:]
print(path)
min = 0
max = len(data)
for i in range(min, max):
range_count = 0
range_sum = 0.0
for y in range(i-3, i+4):
... |
try:
BaseException = BaseException
except NameError:
BaseException = Exception
try:
GeneratorExit = GeneratorExit
except NameError:
class GeneratorExit(Exception):
""" This exception is never raised, it is there to make it possible to
write code compatible with CPython 2.5 even in lower... |
"""A library to control a RobertSonics WavTrigger through a serial port
"""
from __future__ import absolute_import, division, print_function
try:
from os import errno
except ImportError:
import errno
import serial
import struct
__version__ = '0.1.2'
__author__ = 'Eberhard Fahle'
__license__ = 'MIT'
__copyrig... |
"""Read the lib input from a file."""
from abc import abstractmethod
from collections.abc import Iterable
from contextlib import AbstractContextManager
# pylint: disable=too-few-public-methods
class BaseReader(AbstractContextManager, Iterable):
"""Read the lib input from a file."""
def __init__(self, args):... |
def getprimes(n):
if (not str(n).isdigit()) or int(n) < 2:
return set()
elif int(n) == 2:
return {2}
n = int(n)
primes = {2}
for i in range(3, n):
flag = False
for p in primes:
if i % p == 0:
flag = True
break
... |
import warnings
import numpy as np
import torch
from PIL import Image
from matplotlib import pyplot as plt
from torchvision.transforms import transforms
from dataset import dataset
from dods_cats_classification.model.RestNet18 import ResNet18
def denormalize(x_hat):
mean = [0.485, 0.456, 0.406]
std = [0.229... |
# __main__.py to make module executable via python -m
from .igloader import main
main() |
from flask import Flask, request
from structs import *
from pathFinder import PathFinder
import json
import numpy
import sys
from gameHelper import *
from GameSession import *
app = Flask(__name__)
gameSession = GameSession()
def deserialize_map(serialized_map):
"""
Fonction utilitaire pour comprendre la ma... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 28 17:04:29 2020
@author: becker
"""
import pygmsh
rect = [-2, 2, -2, 2]
recth = [-1, 1, -1, 1]
h=2
with pygmsh.geo.Geometry() as geom:
hole = geom.add_rectangle(*recth, z=0, mesh_size=h, make_surface=True)
geom.add_physical(hole.surface, l... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import time
import sys, getopt
#import csv
#import requests
import re
#import hashlib
import json
import datetime
import hashlib
from datetime import timedelta, date
#import threading
#####################
processoutput = os.popen("ps -A -L -F").r... |
# Copyright 2021 The MLX Contributors
#
# SPDX-License-Identifier: Apache-2.0
VERSION = "0.1.29-elyra-notebook-update"
|
# Author:Sunny Liu
from django.shortcuts import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect
from django.views import View
from urmovie import models
from django.views.decorators.csrf import csrf_exempt
'''
@id : 1
@name : index
@author : 刘旭阳
@date : 2018.3.12
... |
"""
R 1.2
---------------------------------
Problem Statement : Write a short Python function, is even(k), that takes an integer value and
returns True if k is even, and False otherwise. However, your function
cannot use the multiplication, modulo, or division operators.
Author : Saurabh
"""
def is_even(k):
a = 1... |
# -*- coding: utf-8 -*-
'''
:codeauthor: Jayesh Kariya <jayeshk@saltstack.com>
'''
# Import Python Libs
from __future__ import absolute_import
# Import Salt Testing Libs
from tests.support.mixins import LoaderModuleMockMixin
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
Magi... |
#!/usr/bin/python3
"""
.. moduleauthor:: Albert Heinle<albert.heinle@gmail.com>
"""
import unittest
from Listing import Listing
import json
class TestProduct(unittest.TestCase):
"""
Testing the class Product for correct functionality
"""
def test_Product_From_Sortable_Challenge(self):
"""... |
"""
hon.parsing.markdown.mistune
~~~~~
"""
from ..parser import Parser
class MistuneParser(Parser):
"""A markdown parser implementing the Mistune markdown library.
"""
def parse_front_matter(self):
pass
def parse(self, text):
pass
|
"""
Find the order of the charater in alien dictionary.
The time complexity of the algorithm is:
1. creating graph
O(n + alphabet_size), where n is total number of words in dictionary
and alphabet_size is the number of alphabets
2. to, word2 = ogical sord complexity: O(V+E))
And in our case it is O(n + alp... |
def collatz(n):
if n == 1:
return 1
elif n % 2 == 0:
return collatz(n / 2)
else:
return collatz(n * 3 + 1)
num = int(input("Type a number: "))
print("Collatz of %i is %i" % (num, collatz(num))) |
# Imports from 3rd party libraries
import dash
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import sklearn
import pandas as pd
#import scikit-learn
# Imports from this application
from app import app
from jobl... |
# -*- coding: utf-8 -*-
#pylint: skip-file
import torch
import torch as T
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from utils_pg import *
from transformer import MultiheadAttention
class WordProbLayer(nn.Module):
def __init__(self, hidden_size, dict_size, device, c... |
try:
import tensorflow as tf
except ImportError:
raise ImportError("reinforcement requires tensorflow 1.14")
from reinforcement.models.neural_network import NeuralNetwork, InvalidOperationError, NotCompiledError
class AnnBuilder:
def __init__(self, input_size, seed):
self.ann = NeuralNetwork(inpu... |
# creation of the text story behind
storyBehind = '''
Guido van Rossum, the creator of the Python language, named the language
after the BBC show "Monty Python’s Flying Circus". He doesn’t particularly like
snakes that kill animals for food by winding their long bodies around them and
crushing them.
'''
know = True
__a... |
#! python3
# pw.py – Um programa para repositório de senhas que NÃO É SEGURO!!!.
import sys
import pyperclip
import os
if len(sys.argv) < 2:
print('Usage: python pw.py [account] - copy account password')
sys.exit()
passwords = {'email': 'teste@teste'}
account = sys.argv[1] # o primeiro argumento da linha d... |
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_marshmallow import Marshmallow
app = Flask(__name__)
appdir = os.path.abspath(os.path.dirname(__file__))
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(appdir, 'db.sqlite')
app.config['SQLALCHEMY_TRACK_MOD... |
import asyncio
from unittest import mock
import pytest
from redical import create_pool, PoolClosedError, PoolClosingError, WatchError
pytestmark = [pytest.mark.asyncio]
@pytest.fixture
async def pool(redis_uri):
pool = await create_pool(redis_uri, max_size=4, min_size=2)
await pool.execute('flushdb')
yield pool... |
"""Plugwise Anna Home Assistant component."""
import requests
import xml.etree.cElementTree as Etree
# Time related
import datetime
import pytz
from dateutil.parser import parse
# For XML corrections
import re
ANNA_PING_ENDPOINT = "/ping"
ANNA_DIRECT_OBJECTS_ENDPOINT = "/core/direct_objects"
ANNA_DOMAIN_OBJECTS_ENDPO... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
from .context import tripp
from tripp import gradient
from tripp import algebra
from functools import partial
import random
import logging
logging.basicConfig(level=logging.INFO, format="%(lineno)d\t%(message)s")
def square(x):
"""for testing"""
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import cobra.models.fields.foreignkey
class Migration(migrations.Migration):
dependencies = [
('accessgroup', '0001_initial'),
('team', '0001_initial'),
('project', '0001_initial'),
... |
import patch
class Connection:
def __init__(self, app, connections):
pass
def iterate(self, connections):
pass
def no_connection(self, connections):
pass
|
from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,SubmitField
from wtforms.validators import Email,Required
from flask_wtf import FlaskForm
from flask_wtf.file import FileField,FileAllowed
from wtforms import StringField,TextAreaField,SubmitField,ValidationError
from wtforms.validators impo... |
import argparse
import sys
from typing import Optional
from typing import Sequence
import toml
def main(argv: Optional[Sequence[str]] = None) -> int:
parser = argparse.ArgumentParser()
parser.add_argument('filenames', nargs='*', help='Filenames to check.')
args = parser.parse_args(argv)
retval = 0
... |
import cadquery as cq
core_rad = 45.0 / 2.0
# Objects to make the basic shape of the guide
guide_core = (cq.Workplane("XY")
.circle(core_rad)
.extrude(3.0))
guide_fan = (cq.Workplane("XY")
.moveTo(0.0, -10.0)
.hLine(core_rad + 15)
.threePointArc((... |
"""useful rexx functions
This module is intended to help with porting ATI code to python.
ATI had several rexx-like functions that will likely be in this
module as python functions. Other functions are included that may
be useful in parsing strings in a rexx-like manner.
Some of these functions have enhancements on t... |
# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
import logging
from typing import List
from volatility.framework import renderers, exceptions, interfaces
from volatility.framework.... |
import requests
import uuid
import json
from datetime import datetime
from django.utils.dateparse import parse_duration
from django.utils.text import slugify
from django.urls import reverse
from django.contrib.auth.models import User
from django.conf import settings
from django.test import TestCase
from urllib.parse im... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name='torchdrift',
version='0.1.0.post1',
description="Drift Detection for PyTorch",
long_description=long_description,
long_description_content_type='text/markdown',
auth... |
# -*- coding: utf-8 -*-
"""
CRUD-storage repositories for SQLAlchemy driver.
"""
from app.drivers.sqlalchemy.crud import Repository
from app.drivers.sqlalchemy.repos.name import NameRepository
from app.drivers.sqlalchemy.repos.role import RoleRepository
from app.drivers.sqlalchemy.repos.user import UserRepository
__al... |
def vars_recurse(obj):
"""
Recursively collect vars() of the object.
Parameters
----------
obj : object
Object to collect attributes
Returns
-------
params : dict
Dictionary of object parameters.
"""
if hasattr(obj, '__dict__'):
params = vars(obj)
for k in params.keys():
if hasattr(params[k], '_... |
from rpkflashtool.app import run
run()
|
"""Module output_file."""
__author__ = 'Joan A. Pinol (japinol)'
import logging
from life import constants as consts
# Errors
ERROR_OUT_FILE_OPEN = "!!! ERROR: Output file: %s. Program aborted !!!"
ERROR_OUT_FILE_WRITING = "!!! ERROR writing output file: %s. Some information has been lost!!!"
ERROR_OUT_FI... |
def flatten_mock_calls(mock):
"""
Flatten the calls performed on a particular mock object,
into a list of calls with arguments.
"""
result = []
for call in mock.mock_calls:
call = list(call)
call_name = call[0]
if '.' in str(call_name):
call_name = str(call_na... |
#!/usr/bin/env python
from __future__ import print_function
import collections
import json
import sys
import ipaddress
clients = dict()
def agg_ip(ip):
mask = 48 if ":" in ip else 16
addr = "%s/%d" % (ip, mask)
net = ipaddress.ip_network(unicode(addr), strict=False)
return str(net)
for arg in sys.ar... |
# https://blog.csdn.net/rizero/article/details/104244454
# 股票成交量预测(Pytorch基础练习)
## depends
import pandas as pd
import torch
import torch.nn
import torch.optim
from debug import ptf_tensor
## raw data
url = 'C:/Users/HUAWEI/Desktop/深度学习/Blog附带代码/FB.csv'
df = pd.read_csv(url, index_col=0) #读取全部数据
index_col = ['col_... |
#!/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.
"There is not a whole lot to test, but this does get us basic coverage."
import hashlib
import unittest
from ..common ... |
from sketchpy import canvas
pen = canvas.sketch_from_svg('C:\\Users\\SHUBHAM\\Desktop\\New folder\\sketch\\4\\mehulnew.svg',scale= 250 )
pen.draw()
|
"""
GUI for the data operations panel (sum and multiply)
"""
import wx
import sys
import time
import numpy as np
from sas.sascalc.dataloader.data_info import Data1D
from sas.sasgui.plottools.PlotPanel import PlotPanel
from sas.sasgui.plottools.plottables import Graph
from sas.sasgui.plottools import transform
from matp... |
"""basic-types.py
Module for creating and running the basic types classifier.
Usage
$ python3 basic-types.py --train-semcor
Train a classifier from all of Semcor and save it in
../data/classifier-all.pickle.
$ python3 basic-types.py --train-test
Train a classifier from a fragemtn of Semcor (two files)... |
import datetime as dt
import glob
import numpy as np
try:
#for python 3.0 or later
from urllib.request import urlopen
except ImportError:
#Fall back to python 2 urllib2
from urllib2 import urlopen
import os
from format_temps import format_file
files = glob.glob('../txtout/*txt')
for i in files:
... |
""" Base classes for Electrical Optical (EO) calibration data
These classes define the interface between the transient data classes used
in EO test code, and the `astropy.table.Table` classes used for persistent
storage.
Specifically they provide ways to define table structures in schema, and the
use those schema to ... |
# Copyright [2018-2020] Peter Krenesky
#
# 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... |
import numpy as np
from MLG.name import name, name_good
from MLG.Math import percentile
from MLG import paperpath, path
from astropy.table import Table
def create_Table(Analysis_result, Analysis_result5, Analysis_result_external = None, sort_epoch =False):
'''------------------------------------------------------... |
# -*- coding: utf-8 -*-
import codecs
from setuptools import setup
packages = \
['colour_hdri',
'colour_hdri.calibration',
'colour_hdri.calibration.tests',
'colour_hdri.exposure',
'colour_hdri.exposure.tests',
'colour_hdri.generation',
'colour_hdri.generation.tests',
'colour_hdri.models',
'colour_hdri.models.d... |
import os
import sys
import codecs
import argparse
from _pickle import load, dump
import collections
from utils import get_processing_word, is_dataset_tag, make_sure_path_exists, get_bmes
from fastNLP import Instance, DataSet, Vocabulary, Const
max_len = 0
def expand(x):
sent = ["<sos>"] + x[1:] + ["<eos>"]
... |
import numpy as np
from collections import namedtuple
import random
Transition = namedtuple('Transition',
('state', 'action', 'next_state', 'reward'))
class Schedule(object):
def __init__(self, n, start, stop):
self.n = n
self.start = start
self.stop = stop
def... |
def inclusive_sum(n, m):
var = 0
for i in range(n, m+1):
var += i
return var
|
from django.db import models
from mls_api.models.base import BaseModel
class Team(BaseModel):
''' Soccer teams '''
name = models.CharField(max_length=128)
slug = models.SlugField(unique=True)
games = models.ManyToManyField('Game', through='GameTeam')
def __unicode__(self):
return u'%s' %... |
import nltk, textblob
text="""I. The Period
It was the best of times,
it was the worst of times,
it was the age of wisdom,
it was the age of foolishness,
it was the epoch of belief,
it was the epoch of incredulity,
it was the season of Light,
it was the season of Darkness,
it was the spring of hope,
it was the wint... |
import numpy as np
import cv2
import pandas as pd
male = pd.read_csv("data/names/herrenavn.csv")
female = pd.read_csv("data/names/kvinnenavn.csv")
maleLength = len(male['Navn'])
feMaleLength = len(female['Navn'])
def draw_information(image_total, loc, faces_df, analyzis_object, useRandomNames=False):
currentDf =... |
import unittest
from pprint import pprint
from random import randint
from pydsalg.datastruct.dynarray import DynamicArray
class TestDynamicArray(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.input0 = list(range(20))
def test_00(self):
dynarr = DynamicArray()
input0 = s... |
import os
import git
from packit.api import PackitAPI
from subprocess import check_output
from flexmock import flexmock
from tests.testsuite_recording.integration.testbase import PackitUnittestOgr
class ProposeUpdate(PackitUnittestOgr):
def setUp(self):
super().setUp()
self.api = PackitAPI(
... |
from hammer_tools.material_library.db import connect
from hammer_tools.material_library.text import alphaNumericTokens
class MapType(object):
Unknown = 'unknown'
Thumbnail = 'thumb'
Diffuse = 'diff'
Roughness = 'rough'
Glossiness = 'gloss'
Metalness = 'metal'
Reflection = 'refl'
Refrac... |
"""This module proposes Pytorch style LightningModule classes for the gnn use-case."""
# 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... |
import numpy as np
from tensorflow.keras.utils import to_categorical
from sklearn.utils import class_weight
import tensorflow as tf
from matplotlib import pyplot as plt
from tensorflow.keras.preprocessing.image import ImageDataGenerator
import cv2 as cv
import os
import time
from sklearn.utils import shuffle
... |
# 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 (t... |
from setuptools import setup
from os import path
import re
def read(fname):
return open(path.join(path.dirname(__file__), fname)).read()
def get_version():
with open('CHANGELOG.rst') as changelog:
for line in changelog:
if re.match(r'^\d+\.\d+\.\d+$', line):
return line
... |
"""
Astra API client
```
from astra import Astra
```
"""
from .client import Astra
__all__ = ["Astra"]
|
import unittest
class TestDummy(unittest.TestCase):
def test_import(self):
pass
def test_failure(self):
self.assert(False)
|
import numpy as np
import cv2
import math
import matplotlib.pyplot as plt
# import os
# import pandas as pd
import glob
import seaborn as sns
from tqdm import tqdm
import matplotlib as mpl
# import warnings; warnings.filterwarnings(action='once')
large = 22
med = 16
small = 12
params = {'legend.fontsize': med,
... |
from parameterized import parameterized_class
from zkay.examples.examples import all_examples
from zkay.tests.utils.test_examples import TestExamples
from zkay.zkay_ast.build_ast import build_ast
from zkay.zkay_ast.visitor.deep_copy import deep_copy
@parameterized_class(('name', 'example'), all_examples)
class TestP... |
import komand
from .schema import QueryInput, QueryOutput
# Custom imports below
import json
import ldap3
class Query(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name='query',
description='Run a LDAP query',
input=QueryInput(),... |
# Generated with AdditionalFileFormatCode
#
from enum import Enum
from enum import auto
class AdditionalFileFormatCode(Enum):
""""""
BINARY_OUTPUT = auto()
ASCII_OUTPUT = auto()
def label(self):
if self == AdditionalFileFormatCode.BINARY_OUTPUT:
return "Binary format"
if s... |
# -*- coding: utf-8 -*-
"""Module with SecureCRT parser."""
from os.path import expanduser
class SecureCRTConfigParser(object):
"""SecureCRT xml parser."""
meta_sessions = ['Default']
def __init__(self, xml):
"""Construct parser instance."""
self.xml = xml
self.tree = {}
def... |
import os
import click
import configobj
class configobj_provider:
"""
A parser for configobj configuration files
Parameters
----------
unrepr : bool
Controls whether the file should be parsed using configobj's unrepr
mode. Defaults to `True`.
section : str
If this is s... |
# -*- coding: utf-8 -*-
"""
@author : Wang Meng
@github : https://github.com/tianpangji
@software : PyCharm
@file : notification.py
@create : 2020/11/17 22:11
"""
import threading
import time
from django.conf import settings
from redis import StrictRedis
from monitor.models import OnlineUsers
def onlin... |
"""
Sphinx inplace translation.
Please put `xxx_zh_CN.rst` alongside `xxx.rst`. When language is set to `zh_CN`,
`xxx_zh_CN.rst` will be used in place of `xxx.rst`.
If translation does not exist, it will automatically fallback to the original files, without warning.
I write this based on the example of:
https://github... |
#%%
from __future__ import print_function
import argparse
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from torch.optim.optimizer import Optimizer
from torchvision import datasets, transforms
from torch.autograd import Variable
from tqdm import tqdm
#... |
#!/usr/bin/env python
##Copyright 2008-2013 Jelle Feringa (jelleferinga@gmail.com)
##
##This file is part of pythonOCC.
##
##pythonOCC 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 o... |
#!/usr/bin/env python
#This is the Modelling Code for ITU Rover Team
##This code takes pictures with pressing space bar and mark the gps data to their exif's.
###This code is the primary code for modelling and scaling for science task that will be done on another operating system.
import numpy as np
import imutils
... |
import click
from .. import di
from .. import tag
cli = click.Group('tag')
OK_COLOR = 'green'
WARN_COLOR = 'yellow'
ERR_COLOR = 'red'
TAG_STATUS_COLORS = {
tag.TagStatus.correct: OK_COLOR,
tag.TagStatus.incorrect: ERR_COLOR,
tag.TagStatus.missing: ERR_COLOR,
}
def tags_with_status(t... |
# -*- coding: utf-8 -*-
"""
Helper functions used in views.
"""
import calendar
import csv
import logging
import time
import threading
from collections import OrderedDict
from datetime import datetime
from functools import wraps
import xml.etree.ElementTree as ET
from json import dumps
from flask import Response
from... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.