content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
import unittest import dace import numpy as np from dace.transformation.dataflow import MapTiling, OutLocalStorage N = dace.symbol('N') if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 11748, 288, 558, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 288, 558, 13, 7645, 1161, 13, 7890, 11125, 1330, 9347, 51, 4386, 11, 3806, 14565, 31425, 198, 198, 45, 796, 288, 558, 13, 1837, 23650, 10786, ...
2.764706
68
# Licensed under a 3-clause BSD style license - see PYFITS.rst import gzip import os from .base import _BaseHDU, BITPIX2DTYPE from .hdulist import HDUList from .image import PrimaryHDU from astropy.io.fits.file import _File from astropy.io.fits.header import _pad_length from astropy.io.fits.util import fileobj_name
[ 2, 49962, 739, 257, 513, 12, 565, 682, 347, 10305, 3918, 5964, 532, 766, 350, 56, 37, 29722, 13, 81, 301, 198, 198, 11748, 308, 13344, 198, 11748, 28686, 198, 198, 6738, 764, 8692, 1330, 4808, 14881, 10227, 52, 11, 36992, 47, 10426,...
2.944954
109
import django from django.test import TestCase from django.template import Template, Context def render(template_string, context_dict=None): """ A shortcut for testing template output. """ if context_dict is None: context_dict = {} c = Context(context_dict) t = Template(template_string) return t.render(c).strip()
[ 11748, 42625, 14208, 201, 198, 6738, 42625, 14208, 13, 9288, 1330, 6208, 20448, 201, 198, 6738, 42625, 14208, 13, 28243, 1330, 37350, 11, 30532, 201, 198, 201, 198, 201, 198, 201, 198, 4299, 8543, 7, 28243, 62, 8841, 11, 4732, 62, 116...
2.622378
143
# Copyright (C) 2016 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """A module containing the workflow TaskGroup model.""" from sqlalchemy import or_ from ggrc import db from ggrc.login import get_current_user from ggrc.models.associationproxy import association_proxy from ggrc.models.mixins import ( Titled, Slugged, Described, Timeboxed, WithContact ) from ggrc.models.reflection import AttributeInfo from ggrc.models.reflection import PublishOnly from ggrc.models import all_models from ggrc_workflows.models.task_group_object import TaskGroupObject
[ 2, 15069, 357, 34, 8, 1584, 3012, 3457, 13, 198, 2, 49962, 739, 2638, 1378, 2503, 13, 43073, 13, 2398, 14, 677, 4541, 14, 43, 2149, 24290, 12, 17, 13, 15, 1279, 3826, 38559, 24290, 2393, 29, 198, 198, 37811, 32, 8265, 7268, 262, ...
3.234043
188
import pytest import rumps from src.app_functions.menu.change_auto_login import change_auto_login def test_setting_is_true(mocker, basic_app): """Check if setting is changed correctly if True""" basic_app.settings["auto_login"] = True mock_function = mocker.patch("src.app_functions.menu.change_auto_login.update_menu") mocker.patch("src.app_functions.menu.change_auto_login.save_settings") change_auto_login(basic_app) assert basic_app.settings["auto_login"] is False mock_function.assert_called_once_with(basic_app) def test_setting_is_false(mocker, basic_app): """Check if setting is changed correctly if false""" basic_app.settings["auto_login"] = False mock_function = mocker.patch("src.app_functions.menu.change_auto_login.update_menu") mocker.patch("src.app_functions.menu.change_auto_login.save_settings") change_auto_login(basic_app) assert basic_app.settings["auto_login"] is True mock_function.assert_called_once_with(basic_app)
[ 11748, 12972, 9288, 198, 11748, 7440, 862, 198, 6738, 12351, 13, 1324, 62, 12543, 2733, 13, 26272, 13, 3803, 62, 23736, 62, 38235, 1330, 1487, 62, 23736, 62, 38235, 628, 198, 198, 4299, 1332, 62, 33990, 62, 271, 62, 7942, 7, 76, 127...
2.868195
349
# -*- coding: utf-8 -*- """VGG 19 architecture for CIFAR-100.""" import tensorflow as tf from ._vgg import _vgg from ..datasets.cifar100 import cifar100 from .testproblem import TestProblem
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 53, 11190, 678, 10959, 329, 327, 5064, 1503, 12, 3064, 526, 15931, 198, 198, 11748, 11192, 273, 11125, 355, 48700, 198, 198, 6738, 47540, 85, 1130, 1330, 4808, 85...
2.757143
70
year = int(input())
[ 198, 1941, 796, 493, 7, 15414, 28955, 198 ]
2.625
8
"""Contains utility functions.""" BIN_MODE_ARGS = {'mode', 'buffering', } TEXT_MODE_ARGS = {'mode', 'buffering', 'encoding', 'errors', 'newline'} def split_args(args): """Splits args into two groups: open args and other args. Open args are used by ``open`` function. Other args are used by ``load``/``dump`` functions. Args: args: Keyword args to split. Returns: open_args: Arguments for ``open``. other_args: Arguments for ``load``/``dump``. """ mode_args = BIN_MODE_ARGS if 'b' in args['mode'] else TEXT_MODE_ARGS open_args = {} other_args = {} for arg, value in args.items(): if arg in mode_args: open_args[arg] = value else: other_args[arg] = value return open_args, other_args def read_wrapper(load, **base_kwargs): """Wraps ``load`` function to avoid context manager boilerplate. Args: load: Function that takes the return of ``open``. **base_kwargs: Base arguments that ``open``/``load`` take. Returns: Wrapper for ``load``. """ return wrapped def write_wrapper(dump, **base_kwargs): """Wraps ``dump`` function to avoid context manager boilerplate. Args: dump: Function that takes the return of ``open`` and data to dump. **base_kwargs: Base arguments that ``open``/``dump`` take. Returns: Wrapper for ``dump``. """ return wrapped
[ 37811, 4264, 1299, 10361, 5499, 526, 15931, 198, 198, 33, 1268, 62, 49058, 62, 1503, 14313, 796, 1391, 6, 14171, 3256, 705, 36873, 1586, 3256, 1782, 198, 32541, 62, 49058, 62, 1503, 14313, 796, 1391, 6, 14171, 3256, 705, 36873, 1586, ...
2.55536
569
import asyncio import functools import time import weakref from collections import defaultdict from typing import AsyncIterable from typing import Awaitable from typing import Callable from typing import Dict from typing import List from typing import Optional from typing import TypeVar T = TypeVar("T") # NOTE: this method is not thread-safe due to lack of locking while checking # and updating the cache
[ 11748, 30351, 952, 198, 11748, 1257, 310, 10141, 198, 11748, 640, 198, 11748, 4939, 5420, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 19720, 1330, 1081, 13361, 29993, 540, 198, 6738, 19720, 1330, 5851, 4548, 540, 198, 6738, 19720, 133...
4.13
100
#!/usr/bin/python ''' generate dataset ''' import csv import argparse import numpy as np import sklearn.metrics import theanets from sklearn.metrics import accuracy_score import logging from trendStrategy import OptTrendStrategy, TrendStrategy from util import visu def load_dataset(stock, ratio=0.8, name=OptTrendStrategy.__name__): ''' return train, valid (x,y) ''' orders = np.loadtxt("{0}_{1}_orders.csv".format(stock, name), usecols=[1], delimiter=',') orders[orders==-1]=0 features = np.loadtxt("{0}_input.csv".format(stock), delimiter=',') if len(orders)!=len(features): logging.error("len(orders)!=len(features) -> %s!=%s" %(len(orders),len(features))) features = features.astype('f') orders = orders.astype('i') pos = round(len(features)*ratio) train = (features[:pos], orders[:pos]) valid = (features[pos:], orders[pos:]) return train, valid if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--stock', '-s', default="TSLA", help='stock') parser.add_argument('--ratio', '-r', default=0.8, type=int, help='train/valid ratio') parser.add_argument('--min', '-m', default=0.001, type=int, help='min improvement (stop learning)') parser.add_argument('--field', default='orders', help='compare field') args = parser.parse_args() if args.field: compare(args.stock, args.field) train, valid = load_dataset(args.stock) exp = train_strategy(args.stock, args.ratio, args.min) exp = load_strategy(args.stock, True)
[ 1303, 48443, 14629, 14, 8800, 14, 29412, 198, 7061, 6, 7716, 27039, 705, 7061, 198, 11748, 269, 21370, 198, 11748, 1822, 29572, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 1341, 35720, 13, 4164, 10466, 198, 11748, 262, 272, 1039, 19...
2.646566
597
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of the SPORCO package. Details of the copyright # and user license can be found in the 'LICENSE.txt' file distributed # with the package. """ Basis Pursuit DeNoising ======================= This example demonstrates the use of class :class:`.admm.bpdn.BPDN` to solve the Basis Pursuit DeNoising (BPDN) problem :cite:`chen-1998-atomic` $$\mathrm{argmin}_\mathbf{x} \; (1/2) \| D \mathbf{x} - \mathbf{s} \|_2^2 + \lambda \| \mathbf{x} \|_1 \;,$$ where $D$ is the dictionary, $\mathbf{x}$ is the sparse representation, and $\mathbf{s}$ is the signal to be represented. In this example the BPDN problem is used to estimate the reference sparse representation that generated a signal from a noisy version of the signal. """ from __future__ import print_function from builtins import input import numpy as np from sporco.admm import bpdn from sporco import util from sporco import plot """ Configure problem size, sparsity, and noise level. """ N = 512 # Signal size M = 4*N # Dictionary size L = 32 # Number of non-zero coefficients in generator sigma = 0.5 # Noise level """ Construct random dictionary, reference random sparse representation, and test signal consisting of the synthesis of the reference sparse representation with additive Gaussian noise. """ # Construct random dictionary and random sparse coefficients np.random.seed(12345) D = np.random.randn(N, M) x0 = np.zeros((M, 1)) si = np.random.permutation(list(range(0, M-1))) x0[si[0:L]] = np.random.randn(L, 1) # Construct reference and noisy signal s0 = D.dot(x0) s = s0 + sigma*np.random.randn(N,1) """ Set BPDN solver class options. """ opt = bpdn.BPDN.Options({'Verbose': False, 'MaxMainIter': 500, 'RelStopTol': 1e-3, 'AutoRho': {'RsdlTarget': 1.0}}) """ Select regularization parameter $\lambda$ by evaluating the error in recovering the sparse representation over a logarithmicaly spaced grid. (The reference representation is assumed to be known, which is not realistic in a real application.) A function is defined that evalues the BPDN recovery error for a specified $\lambda$, and this function is evaluated in parallel by :func:`sporco.util.grid_search`. """ # Function computing reconstruction error at lmbda # Parallel evalution of error function on lmbda grid lrng = np.logspace(1, 2, 20) sprm, sfvl, fvmx, sidx = util.grid_search(evalerr, (lrng,)) lmbda = sprm[0] print('Minimum 1 error: %5.2f at = %.2e' % (sfvl, lmbda)) """ Once the best $\lambda$ has been determined, run BPDN with verbose display of ADMM iteration statistics. """ # Initialise and run BPDN object for best lmbda opt['Verbose'] = True b = bpdn.BPDN(D, s, lmbda, opt) x = b.solve() print("BPDN solve time: %.2fs" % b.timer.elapsed('solve')) """ Plot comparison of reference and recovered representations. """ plot.plot(np.hstack((x0, x)), title='Sparse representation', lgnd=['Reference', 'Reconstructed']) """ Plot lmbda error curve, functional value, residuals, and rho """ its = b.getitstat() fig = plot.figure(figsize=(15, 10)) plot.subplot(2, 2, 1) plot.plot(fvmx, x=lrng, ptyp='semilogx', xlbl='$\lambda$', ylbl='Error', fig=fig) plot.subplot(2, 2, 2) plot.plot(its.ObjFun, xlbl='Iterations', ylbl='Functional', fig=fig) plot.subplot(2, 2, 3) plot.plot(np.vstack((its.PrimalRsdl, its.DualRsdl)).T, ptyp='semilogy', xlbl='Iterations', ylbl='Residual', lgnd=['Primal', 'Dual'], fig=fig) plot.subplot(2, 2, 4) plot.plot(its.Rho, xlbl='Iterations', ylbl='Penalty Parameter', fig=fig) fig.show() # Wait for enter on keyboard input()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 770, 2393, 318, 636, 286, 262, 6226, 1581, 8220, 5301, 13, 14890, 286, 262, 6634, 198, 2, 290, 2836, 5964, 460, ...
2.791921
1,312
# This file was generated automatically by the Snowball to Python compiler # http://snowballstem.org/ from .basestemmer import BaseStemmer from .among import Among
[ 2, 770, 2393, 373, 7560, 6338, 416, 262, 7967, 1894, 284, 11361, 17050, 198, 2, 2638, 1378, 82, 2197, 1894, 927, 13, 2398, 14, 198, 198, 6738, 764, 12093, 395, 368, 647, 1330, 7308, 1273, 368, 647, 198, 6738, 764, 35131, 1330, 9754,...
3.659574
47
# -*- coding: utf-8 -*- # ================================================================= # uspec # # Copyright (c) 2020 Takahide Nogayama # # This software is released under the MIT License. # http://opensource.org/licenses/mit-license.php # ================================================================= from __future__ import unicode_literals, print_function, division import unittest import uspec from uspec import describe, context, it ################################### with describe("Game", test_class=TestGame): assert test_class is TestGame assert TestGame is not None ################################## TEST_CLASS_NAME_GAME2 = None with describe("Game2"): TEST_CLASS_NAME_GAME2 = test_class.__name__ assert TEST_CLASS_NAME_GAME2 in globals() ################################## wrap() assert TEST_CLASS_NAME_GAME3 in globals() if __name__ == '__main__': import unittest unittest.main(verbosity=2)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 38093, 198, 2, 514, 43106, 198, 2, 198, 2, 15069, 357, 66, 8, 12131, 15804, 993, 485, 399, 519, 323, 1689, 198, 2, 198, 2, 770, 3788, 318, 2716, 739, 262, ...
3.494505
273
import pygame from game.game_logic.game import Game import matplotlib.pyplot as plt if __name__ == "__main__": main()
[ 11748, 12972, 6057, 198, 6738, 983, 13, 6057, 62, 6404, 291, 13, 6057, 1330, 3776, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, ...
2.717391
46
import os import sys from glob import glob if __name__=="__main__": main()
[ 11748, 28686, 198, 11748, 25064, 198, 6738, 15095, 1330, 15095, 628, 220, 220, 220, 220, 198, 361, 11593, 3672, 834, 855, 1, 834, 12417, 834, 1298, 198, 220, 220, 220, 1388, 3419 ]
2.625
32
#!/usr/bin/env python # coding: utf-8 # In[1]: # src: http://datareview.info/article/prognozirovanie-ottoka-klientov-so-scikit-learn/ # In[ ]: # -, # # . # , # , # ( 5 20 ). # : # 1. , # , # 2. , # , # . # 3. A , # , . # , # , , # , , , # . # In[ ]: # datset src: https://raw.githubusercontent.com/michaelulin/churn/master/work/churn_model/data/churn.csv # In[88]: # Load libraries import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') import pandas as pd import numpy as np from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score, confusion_matrix, precision_recall_fscore_support from sklearn.model_selection import KFold, train_test_split from sklearn.ensemble import RandomForestClassifier from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier # In[3]: # Load dataset raw_churn_df = pd.read_csv('churn.csv') # In[17]: display(raw_churn_df.shape) display(raw_churn_df.head(), raw_churn_df.tail()) display(raw_churn_df.columns.values) display(raw_churn_df.dtypes) display(raw_churn_df.isnull().sum()) # In[78]: # Isolate target data y = raw_churn_df['Churn?'] X = raw_churn_df.drop('Churn?', axis=1) # In[79]: # Drop irrelevant features features_to_drop = ['State', 'Area Code', 'Phone'] X = X.drop(features_to_drop, axis=1) # In[80]: # Encode yes/no with 1/0 values X["Int'l Plan"] = X["Int'l Plan"].map({'no': 0, 'yes': 1}) X["VMail Plan"] = X["VMail Plan"].map({'no': 0, 'yes': 1}) # In[81]: # Scale everything std_scaler = StandardScaler(with_mean=True) X = std_scaler.fit_transform(X) display(X.shape) # In[90]: # Perform CV for SVM, random forest and kNN try_clf(X, y, SVC(gamma='scale')) try_clf(X, y, RandomForestClassifier(n_estimators=100, n_jobs=-1)) try_clf(X, y, KNeighborsClassifier()) # std scaler with_mean=False accuracies: # 0.9256594724220624 # 0.9484412470023981 # 0.8896882494004796 # std scaler with_mean=True accuracies: # 0.9256594724220624 # 0.9496402877697842 # 0.8896882494004796 # In[86]: # Recall # # ? # Precision # # ? # In[101]: # # Predict probabilities # def try_probab(X, y, clf_nofit): # X_tr, X_val, y_tr, y_val = train_test_split(X, y, random_state=42) # clf = clf_nofit.fit(X_tr, y_tr) # y_prob = clf.predict_proba(X_val) # # for i in range(len(X)): # # display("y_true={0}, Predicted={1}".format(y[i], y_prob[i])) # display(pd.value_counts(y_prob[:, 1])) # try_probab(X, y, SVC(gamma='scale', probability=True)) # # try_probab(X, y, RandomForestClassifier(n_estimators=100, n_jobs=-1)) # # try_probab(X, y, KNeighborsClassifier()) # # for i in range(len(Xnew)): # # print("X=%s, Predicted=%s" % (Xnew[i], ynew[i])) # In[ ]: # todo: calibration and discrimination # https://github.com/ghuiber/churn/blob/master/churn_measurements.py # from churn_measurements import calibration, discrimination
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 2, 554, 58, 16, 5974, 628, 198, 2, 12351, 25, 2638, 1378, 19608, 533, 1177, 13, 10951, 14, 20205, 14, 1676, 70, 3919, 89, 7058, 10438, 4...
2.185501
1,407
# MIT License # # Copyright (c) 2020 Airbyte # # 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, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import annotations from typing import List, Optional from pydantic import BaseModel, Extra, Field
[ 2, 17168, 13789, 198, 2, 198, 2, 15069, 357, 66, 8, 12131, 3701, 26327, 198, 2, 198, 2, 2448, 3411, 318, 29376, 7520, 11, 1479, 286, 3877, 11, 284, 597, 1048, 16727, 257, 4866, 198, 2, 286, 428, 3788, 290, 3917, 10314, 3696, 357, ...
3.846395
319
""" A simple python api wrapper for https://opentdb.com/ """ from aiohttp import ClientSession from requests import get from pytrivia.__helpers import decode_dict, get_token, make_request from pytrivia.enums import *
[ 37811, 198, 32, 2829, 21015, 40391, 29908, 329, 3740, 1378, 404, 298, 9945, 13, 785, 14, 198, 37811, 198, 198, 6738, 257, 952, 4023, 1330, 20985, 36044, 198, 6738, 7007, 1330, 651, 198, 198, 6738, 12972, 28461, 8869, 13, 834, 16794, 3...
3.384615
65
import requests import tarfile import os
[ 11748, 7007, 198, 11748, 13422, 7753, 198, 11748, 28686 ]
4.444444
9
import shlex from os import path from itertools import imap, ifilter from urlparse import urljoin from .css import CSSParser, iter_events def get_spritemap_url(self, fname): "Get output image URL for spritemap *fname*." return self.absurl(path.relpath(fname, self.root)) def get_css_out(self, fname): "Get output image filename for spritemap directory *fname*." (dirn, base) = path.split(fname) if "output_css" in self._data: (base, ext) = path.splitext(base) names = dict(filename=fname, dirname=dirn, basename=base, extension=ext) return self.normpath(self._data["output_css"].format(**names)) else: return path.join(dirn, "sm_" + base) def print_config(fname): from pprint import pprint from .css import CSSParser with open(fname, "rb") as fp: print "%s\n%s\n" % (fname, "=" * len(fname)) pprint(dict(iter_css_config(CSSParser.read_file(fp)))) print def main(): import sys for fn in sys.argv[1:]: print_config(fn) if __name__ == "__main__": main()
[ 11748, 427, 2588, 198, 6738, 28686, 1330, 3108, 198, 6738, 340, 861, 10141, 1330, 545, 499, 11, 611, 346, 353, 198, 6738, 19016, 29572, 1330, 19016, 22179, 198, 6738, 764, 25471, 1330, 9429, 4303, 28198, 11, 11629, 62, 31534, 628, 220, ...
2.196154
520
""" A bar graph. (c) September 2017 by Daniel Seita """ import argparse from collections import defaultdict from keras.models import Sequential from keras.layers import Dense, Activation import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import sys np.set_printoptions(suppress=True, linewidth=200) # Some matplotlib settings. plt.style.use('seaborn-darkgrid') titlesize = 21 labelsize = 17 legendsize = 15 ticksize = 15 bar_width = 0.80 opacity = 1.0 error_config = {'ecolor': '0.0', 'linewidth':3.0} def deprecated(): """ This is a deprecated method, only to show how to possibly combine these into one plot. However, I find this unwieldly. """ fig, ax = plt.subplots() bar_width = 0.80 opacity = 0.5 error_config = {'ecolor': '0.3'} rects1 = plt.bar(np.array([0,1]), means_lin, bar_width, alpha=opacity, color='b', yerr=std_lin, error_kw=error_config, label='Lin') rects2 = plt.bar(np.array([3,4,5,6,7]), means_rfs, bar_width, alpha=opacity, color='r', yerr=std_rfs, error_kw=error_config, label='RF') rects3 = plt.bar(np.array([9,10]), means_dnn, bar_width, alpha=opacity, color='y', yerr=std_dnn, error_kw=error_config, label='DNN') plt.xticks(np.arange(11) + bar_width / 2, ('A','B','','D','E','F','G','','','J','K')) plt.xlabel('Group') plt.ylabel('Scores') plt.title('Scores by group and gender') plt.tight_layout() plt.legend() plt.savefig('figures/validation_set_results.png') if __name__ == "__main__": pp = argparse.ArgumentParser() pp.add_argument('--version', type=int) pp.add_argument('--kfolds', type=int, default=10) args = pp.parse_args() assert args.version is not None VERSION = str(args.version).zfill(2) file_name = 'results/results_kfolds10_v'+VERSION+'.npy' results = np.load(file_name)[()] print("results has keys: {}".format(results.keys())) plot(results, VERSION)
[ 37811, 317, 2318, 4823, 13, 198, 198, 7, 66, 8, 2693, 2177, 416, 7806, 1001, 5350, 198, 37811, 198, 198, 11748, 1822, 29572, 198, 6738, 17268, 1330, 4277, 11600, 198, 6738, 41927, 292, 13, 27530, 1330, 24604, 1843, 198, 6738, 41927, 2...
2.042895
1,119
#!/usr/bin/env python from setuptools import find_packages, setup import os import re ROOT = os.path.dirname(__file__) VERSION_RE = re.compile(r'''__version__ = \'([0-9.]+)\'''') setup( name='groceries-api', version=get_version(), license='MIT', packages=find_packages(), include_package_data=True, install_requires=[ 'alembic==0.7.5.post2', 'APScheduler==3.1.0', 'Flask==0.10.1', 'Flask-Cors==2.0.0', 'Flask-SQLAlchemy==2.0', 'gunicorn==19.3.0', 'psycopg2==2.6.1', 'PyJWT==1.1.0', 'requests==2.8.1', 'six==1.9.0', ], extras_require={ 'dev': { 'coverage==3.7.1', 'coveralls==0.5', 'flake8==2.4.0', 'mock==1.0.1', 'pytest==2.7.0', 'tox==2.1.1', }, }, )
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 6738, 900, 37623, 10141, 1330, 1064, 62, 43789, 11, 9058, 198, 11748, 28686, 198, 11748, 302, 628, 198, 13252, 2394, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 8, 198, ...
1.728916
498
from direct.showbase.ShowBase import * from direct.interval.IntervalGlobal import * from toontown.battle.BattleProps import * from direct.distributed.ClockDelta import * from direct.showbase.PythonUtil import Functor from direct.showbase.PythonUtil import StackTrace from direct.gui.DirectGui import * from panda3d.core import * from libotp import * from direct.fsm import FSM from direct.fsm import ClassicFSM from direct.fsm import State from direct.directnotify import DirectNotifyGlobal from toontown.toonbase import ToontownGlobals from toontown.toonbase import ToontownBattleGlobals import DistributedBossCog from toontown.toonbase import TTLocalizer import SuitDNA from toontown.toon import Toon from toontown.battle import BattleBase from direct.directutil import Mopath from direct.showutil import Rope from toontown.distributed import DelayDelete from toontown.battle import MovieToonVictory from toontown.building import ElevatorUtils from toontown.battle import RewardPanel from toontown.toon import NPCToons from direct.task import Task import random import math from toontown.coghq import CogDisguiseGlobals from toontown.building import ElevatorConstants from toontown.toonbase import ToontownTimer OneBossCog = None
[ 6738, 1277, 13, 12860, 8692, 13, 15307, 14881, 1330, 1635, 198, 6738, 1277, 13, 3849, 2100, 13, 9492, 2100, 22289, 1330, 1635, 198, 6738, 284, 756, 593, 13, 38471, 13, 24064, 2964, 862, 1330, 1635, 198, 6738, 1277, 13, 17080, 6169, 13...
3.431755
359
# SPDX-License-Identifier: Apache-2.0 """Unit Tests for custom rnns.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf from tensorflow.python.ops import init_ops from backend_test_base import Tf2OnnxBackendTestBase from common import * # pylint: disable=wildcard-import, unused-wildcard-import from tf2onnx.tf_loader import is_tf2 # pylint: disable=missing-docstring,invalid-name,unused-argument,using-constant-test # pylint: disable=abstract-method,arguments-differ if is_tf2(): BasicLSTMCell = tf.compat.v1.nn.rnn_cell.BasicLSTMCell LSTMCell = tf.compat.v1.nn.rnn_cell.LSTMCell GRUCell = tf.compat.v1.nn.rnn_cell.GRUCell RNNCell = tf.compat.v1.nn.rnn_cell.RNNCell MultiRNNCell = tf.compat.v1.nn.rnn_cell.MultiRNNCell dynamic_rnn = tf.compat.v1.nn.dynamic_rnn bidirectional_dynamic_rnn = tf.compat.v1.nn.bidirectional_dynamic_rnn else: LSTMBlockCell = tf.contrib.rnn.LSTMBlockCell LSTMCell = tf.nn.rnn_cell.LSTMCell GRUCell = tf.nn.rnn_cell.LSTMCell RNNCell = tf.nn.rnn_cell.RNNCell MultiRNNCell = tf.contrib.rnn.MultiRNNCell dynamic_rnn = tf.nn.dynamic_rnn bidirectional_dynamic_rnn = tf.nn.bidirectional_dynamic_rnn if __name__ == '__main__': unittest_main()
[ 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 628, 198, 37811, 26453, 30307, 329, 2183, 374, 77, 5907, 526, 15931, 198, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, ...
2.359155
568
#!/user/bin/env python3 # -*- coding: utf-8 -*- #!/user/bin/env python3 # -*- coding: utf-8 -*- # @Author: Kevin Brgisser # @Email:kevin.buergisser@edu.hefr.ch # @Date: 04.2020 # Context: CHARMPROJECT- Harzard perception """ Module documentation. """ # Imports import sys #import os # Global variables # Class declarations # Function declarations # Main body if __name__ == '__main__': main()
[ 2, 48443, 7220, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 48443, 7220, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, ...
2.579618
157
import numpy
[ 11748, 299, 32152, 628 ]
3.5
4
import traceback try: raise Exception('This is the error message.') except: errorFile = open('./Chapter 10/errorInfo.txt', 'w') errorFile.write(traceback.format_exc()) errorFile.close() print('The traceback info was written to errorInfo.txt')
[ 11748, 12854, 1891, 198, 28311, 25, 198, 220, 220, 220, 5298, 35528, 10786, 1212, 318, 262, 4049, 3275, 2637, 8, 198, 16341, 25, 198, 220, 220, 220, 4049, 8979, 796, 1280, 7, 4458, 14, 14126, 838, 14, 18224, 12360, 13, 14116, 3256, ...
2.977273
88
# Databricks notebook source from pyspark.sql.types import * from pyspark.sql import functions as F import base64 import array # COMMAND ---------- # s is a base64 encoded float[] with first element being the magnitude # Register udf functions so that it could be used in dataframe # # Perform same computation as cosineSimilarity() # # COMMAND ---------- # MAGIC %md **NetworkSimilarity** class to compute Network Similarity # COMMAND ---------- # Parameters: # resource: resource stream path # container: container name in Azure Storage (AS) account # account: Azure Storage (AS) account # sas: complete 'Blob service SAS URL' of the shared access signature (sas) for the container # key: access key for the container, if sas is specified, key is ignored # # Note: # resource does not have header # you need to provide value for either sas or key # class NetworkSimilarity(AzureStorageAccess): # constructor def __init__(self, resource, container, account, sas='', key=''): AzureStorageAccess.__init__(self, container, account, sas, key) schema = StructType() schema.add(StructField('EntityId', LongType(), False)) schema.add(StructField('EntityType', StringType(), False)) schema.add(StructField('Data', StringType(), False)) self.df = spark.read.format('csv').options(header='false', delimiter='\t').schema(schema).load(self.getFullpath(resource)) def getDataframe(self): return self.df def raiseErrorIfNotFound(self, row, e): if row is None: raise KeyError('entity ' + str(e) + ' not found')
[ 2, 16092, 397, 23706, 20922, 2723, 198, 6738, 279, 893, 20928, 13, 25410, 13, 19199, 1330, 1635, 198, 6738, 279, 893, 20928, 13, 25410, 1330, 5499, 355, 376, 198, 11748, 2779, 2414, 198, 11748, 7177, 198, 198, 2, 22240, 6981, 24200, 4...
3.184739
498
print("Press q to quit") quit = False while quit is False: in_val = input("Please enter a positive integer.\n > ") if in_val is 'q': quit = True elif int(in_val) % 3 == 0 and int(in_val) % 5 == 0: print("FizzBuzz") elif int(in_val) % 5 == 0: print("Buzz") elif int(in_val) % 3 == 0: print("Fizz") else: pass
[ 4798, 7203, 13800, 10662, 284, 11238, 4943, 198, 47391, 796, 10352, 198, 198, 4514, 11238, 318, 10352, 25, 198, 220, 220, 220, 287, 62, 2100, 796, 5128, 7203, 5492, 3802, 257, 3967, 18253, 13, 59, 77, 1875, 366, 8, 198, 220, 220, 22...
2.083799
179
from lesson14_projects.pen.data.const import ( A, E_A, E_AN, E_IS, E_OVER, E_PEN, E_PIN, E_THAT, E_THIS, E_WAS, INIT, IS, PEN, THIS, ) pen_transition_doc_v19 = { "title": "This is a pen", "entry_state": INIT, "data": { INIT: { E_OVER: [INIT], E_THAT: [INIT], E_THIS: [INIT, THIS], THIS: { E_OVER: [INIT], E_WAS: [INIT], E_IS: [INIT, THIS, IS], IS: { E_OVER: [INIT], E_AN: [INIT], E_A: [INIT, THIS, IS, A], A: { E_OVER: [INIT], E_PIN: [INIT], E_PEN: [PEN], }, }, }, }, PEN: { E_OVER: None, }, }, }
[ 6738, 11483, 1415, 62, 42068, 13, 3617, 13, 7890, 13, 9979, 1330, 357, 198, 220, 220, 220, 317, 11, 198, 220, 220, 220, 412, 62, 32, 11, 198, 220, 220, 220, 412, 62, 1565, 11, 198, 220, 220, 220, 412, 62, 1797, 11, 198, 220, 2...
1.38003
671
import gd,os,time from Html import Animation_Html from Iteration import Animation_Iteration from Write import Animation_Write from Base import * from Canvas2 import * from Canvas2 import Canvas2 from Image import Image from HTML import HTML __Canvas__=None
[ 11748, 308, 67, 11, 418, 11, 2435, 198, 198, 6738, 367, 20369, 1330, 23535, 62, 39, 20369, 198, 6738, 40806, 341, 1330, 23535, 62, 29993, 341, 198, 6738, 19430, 1330, 23535, 62, 16594, 198, 198, 6738, 7308, 1330, 1635, 198, 6738, 1680...
3.513514
74
#! /usr/bin/env python3 from .base_miner import BasePostGradientMiner import torch from ..utils import loss_and_miner_utils as lmu # adapted from # https://github.com/chaoyuaw/incubator-mxnet/blob/master/example/gluon/ # /embedding_learning/model.py
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 764, 8692, 62, 1084, 263, 1330, 7308, 6307, 42731, 1153, 44, 7274, 198, 11748, 28034, 198, 6738, 11485, 26791, 1330, 2994, 62, 392, 62, 1084, 263, 62, 26791, 355, 30...
2.75
92
# -*- coding: utf-8 -*- from .Alarm.alarm import Alarm from .DeliveryView.bolus import Bolus from .DeliveryView.info import Info from .DeliveryView.infusion import Infusion from .DeliveryView.infusion_parameter import InfusionParameter from .DeliveryView.priming import Priming from .HardwareControl.motor import Motor from .MenuSettings.device_report import DeviceReport from .MenuSettings.history_log import HistoryLog from .MenuSettings.infusion_setting import InfusionSetting from .MenuSettings.maintenance import Maintenance from .MenuSettings.safety_setting import SafetySetting from .MenuSettings.system_setting import SystemSetting from .SensorControl.sensor import Sensor __all__ = ["Alarm", "Bolus", "Info", "Infusion", "InfusionParameter", "Priming", "Motor", "DeviceReport", "HistoryLog", "InfusionSetting", "Maintenance", "SafetySetting", "SystemSetting", "Sensor", ]
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 764, 2348, 1670, 13, 282, 1670, 1330, 978, 1670, 198, 6738, 764, 33129, 7680, 13, 28984, 385, 1330, 10797, 385, 198, 6738, 764, 33129, 7680, 13, 10951, 1330, ...
2.645408
392
# --------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # ---------------------------------------------------------
[ 2, 20368, 22369, 12, 198, 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 20368, 22369, 12, 628, 628 ]
7.625
24
from functools import partial from pulsar import Connection, Pool, get_actor from pulsar.utils.pep import to_string from pulsar.apps.data import RemoteStore from pulsar.apps.ds import redis_parser from .client import RedisClient, Pipeline, Consumer, ResponseError from .pubsub import RedisPubSub, RedisChannels def client(self): '''Get a :class:`.RedisClient` for the Store''' return RedisClient(self) def pipeline(self): '''Get a :class:`.Pipeline` for the Store''' return Pipeline(self) def pubsub(self, protocol=None): return RedisPubSub(self, protocol=protocol) def channels(self, protocol=None, **kw): return RedisChannels(self.pubsub(protocol=protocol), **kw) def ping(self): return self.client().ping() def flush(self): return self.execute('flushdb') def close(self): '''Close all open connections.''' return self._pool.close() def has_query(self, query_type): return query_type in self.supported_queries def basekey(self, meta, *args): key = '%s%s' % (self.namespace, meta.table_name) postfix = ':'.join((to_string(p) for p in args if p is not None)) return '%s:%s' % (key, postfix) if postfix else key def meta(self, meta): '''Extract model metadata for lua script stdnet/lib/lua/odm.lua''' # indices = dict(((idx.attname, idx.unique) for idx in meta.indices)) data = meta.as_dict() data['namespace'] = self.basekey(meta) return data class CompiledQuery: def __init__(self, pipe, query): self.pipe = pipe
[ 6738, 1257, 310, 10141, 1330, 13027, 198, 198, 6738, 22271, 283, 1330, 26923, 11, 19850, 11, 651, 62, 11218, 198, 6738, 22271, 283, 13, 26791, 13, 431, 79, 1330, 284, 62, 8841, 198, 6738, 22271, 283, 13, 18211, 13, 7890, 1330, 21520, ...
2.516923
650
# Generated by Django 3.0.7 on 2020-06-16 05:23 from django.db import migrations, models import django.utils.timezone
[ 2, 2980, 515, 416, 37770, 513, 13, 15, 13, 22, 319, 12131, 12, 3312, 12, 1433, 8870, 25, 1954, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 42625, 14208, 13, 26791, 13, 2435, 11340, 628 ]
2.926829
41
# Copyright (c) 2019 - The Procedural Generation for Gazebo authors # For information on the respective copyright owner see the NOTICE file # # 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, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from . import XMLBase import collections
[ 2, 15069, 357, 66, 8, 13130, 532, 383, 23652, 1523, 16588, 329, 21347, 1765, 78, 7035, 198, 2, 1114, 1321, 319, 262, 11756, 6634, 4870, 766, 262, 28536, 2393, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, ...
4.005495
182
import mock import pytest from werkzeug.exceptions import NotFound import app.main.helpers as helpers from dmcontent.content_loader import ContentLoader from dmtestutils.api_model_stubs import BriefStub, FrameworkStub, LotStub content_loader = ContentLoader('tests/fixtures/content') content_loader.load_manifest('dos', 'data', 'edit_brief') questions_builder = content_loader.get_manifest('dos', 'edit_brief')
[ 11748, 15290, 198, 11748, 12972, 9288, 198, 6738, 266, 9587, 2736, 1018, 13, 1069, 11755, 1330, 1892, 21077, 198, 198, 11748, 598, 13, 12417, 13, 16794, 364, 355, 49385, 198, 6738, 288, 76, 11299, 13, 11299, 62, 29356, 1330, 14041, 1740...
3.242188
128
import deephaven.TableTools as tt import deephaven.Plot as plt t = tt.emptyTable(50)\ .update("X = i + 5", "XLow = X -1", "XHigh = X + 1", "Y = Math.random() * 5", "YLow = Y - 1", "YHigh = Y + 1", "USym = i % 2 == 0 ? `AAPL` : `MSFT`") p = plt.plot("S1", t, "X", "Y").lineColor("black").show() p2 = plt.plot("S1", t, "X", "Y").plotStyle("bar").gradientVisible(True).show() p3 = plt.plot("S1", t, "X", "Y").plotStyle("scatter").pointColor("black").pointSize(2).show() p4 = plt.plot("S1", t, "X", "Y").plotStyle("area").seriesColor("red").show() p4 = plt.plot3d("S1", t, "X", "X", "Y").show() pBy = plt.plotBy("S1", t, "X", "Y", "USym").show() pBy = plt.plot3dBy("S1", t, "X", "X", "Y", "USym").show() cp = plt.catPlot("S1", t, "X", "Y").lineColor("black").show() cp2 = plt.catPlot("S1", t, "X", "Y").plotStyle("bar").gradientVisible(True).show() cp3 = plt.catPlot("S1", t, "X", "Y").plotStyle("scatter").pointColor("black").pointSize(2).show() cp4 = plt.catPlot("S1", t, "X", "Y").plotStyle("area").seriesColor("red").show() cp = plt.catPlot3d("S1", t, "X", "X", "Y").show() cpBy = plt.catPlotBy("S1", t, "X", "Y", "USym").show() cpBy = plt.catPlot3dBy("S1", t, "X", "X", "Y", "USym").show() pp = plt.piePlot("S1", t, "X", "Y") chp = plt.catHistPlot("S1", t, "X").show() hp = plt.histPlot("S1", t, "X", 5).show() hp = plt.histPlot("S1", t, "X", 0, 10, 5).show() ep = plt.errorBarXY("S1", t, "X", "XLow", "XHigh", "Y", "YLow", "YHigh").show() epBy = plt.errorBarXYBy("S1", t, "X", "XLow", "XHigh", "Y", "YLow", "YHigh", "USym").show() ep2 = plt.errorBarX("S1", t, "X", "XLow", "XHigh", "Y").show() epBy2 = plt.errorBarXBy("S1", t, "X", "XLow", "XHigh", "Y", "USym").show() ep3 = plt.errorBarY("S1", t, "X", "Y", "YLow", "YHigh").show() epBy3 = plt.errorBarYBy("S1", t, "X", "Y", "YLow", "YHigh", "USym").show() doubles = [3, 4, 3, 5, 4, 5] time = 1491946585000000000 t = tt.newTable(tt.col("USym", ["A", "B", "A", "B", "A", "B"]), tt.doubleCol("Open", doubles), tt.doubleCol("High", doubles), tt.doubleCol("Low", doubles), tt.doubleCol("Close", doubles)) t = t.updateView("Time = new DBDateTime(time + (MINUTE * i))") ohlc = plt.ohlcPlot("Test1", t, "Time", "Open", "High", "Low", "Close") ohlcPlotBy = plt.figure().newChart(0)\ .chartTitle("Chart Title")\ .newAxes()\ .xLabel("X")\ .yLabel("Y")\ .ohlcPlotBy("Test1", t, "Time", "Open", "High", "Low", "Close", "USym") categories = ["Samsung", "Others", "Nokia", "Apple", "MSFT"] valuesD = [27.8, 55.3, 16.8, 17.1, 23.1] valuesI = [27, 55, 16, 17, 15] ap = plt.plot("S1", valuesD, valuesI).show() ap = plt.plot3d("S1", valuesI, valuesI, valuesI).show() acp = plt.catPlot("S1", categories, valuesI).show() acp2 = plt.catPlot3d("S1", categories, categories, valuesD).show() achp = plt.catHistPlot("S1", categories).show() app = plt.figure().xLabel("X").yLabel("Y").piePlot("S1", categories, valuesI).pointLabelFormat("{0}").show() aep = plt.errorBarXY("S1", valuesD, valuesD, valuesD, valuesD, valuesD, valuesD).show() aep2 = plt.errorBarX("S1", valuesD, valuesD, valuesD, valuesD).show() aep3 = plt.errorBarY("S1", valuesD, valuesD, valuesD, valuesD).show() hp = plt.histPlot("S1", valuesD, 5).show() hp = plt.histPlot("S1", valuesD, 0, 10, 5).show() hp = plt.histPlot("S1", valuesI, 5).show()
[ 11748, 2769, 39487, 13, 10962, 33637, 355, 256, 83, 198, 11748, 2769, 39487, 13, 43328, 355, 458, 83, 628, 198, 83, 796, 256, 83, 13, 28920, 10962, 7, 1120, 19415, 198, 220, 220, 220, 764, 19119, 7203, 55, 796, 1312, 1343, 642, 1600...
2.191573
1,519
# Copyright 2019 Arie Bregman # # 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, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. from __future__ import absolute_import from flask import current_app as app from flask import render_template from flask import url_for import logging LOG = logging.getLogger(__name__) from rhoci.test import bp # noqa
[ 2, 15069, 13130, 317, 5034, 347, 2301, 805, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, 2393, 2845, 287, 11846...
3.393443
244
from .read import ( read_request_head, read_response_head, connection_close, expected_http_body_size, validate_headers, ) from .assemble import ( assemble_request, assemble_request_head, assemble_response, assemble_response_head, assemble_body, ) __all__ = [ "read_request_head", "read_response_head", "connection_close", "expected_http_body_size", "validate_headers", "assemble_request", "assemble_request_head", "assemble_response", "assemble_response_head", "assemble_body", ]
[ 6738, 764, 961, 1330, 357, 198, 220, 220, 220, 1100, 62, 25927, 62, 2256, 11, 198, 220, 220, 220, 1100, 62, 26209, 62, 2256, 11, 198, 220, 220, 220, 4637, 62, 19836, 11, 198, 220, 220, 220, 2938, 62, 4023, 62, 2618, 62, 7857, 11...
2.6
210
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2017-05-21 19:33 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2980, 515, 416, 37770, 352, 13, 940, 319, 2177, 12, 2713, 12, 2481, 678, 25, 2091, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 198, 6738, ...
2.791045
67
#4 lines: Fibonacci, tuple assignment parents, babies = (1, 1) while babies < 100: print ('This generation has {0} babies'.format(babies)) parents, babies = (babies, parents + babies)
[ 2, 19, 3951, 25, 41566, 261, 44456, 11, 46545, 16237, 198, 23743, 11, 11903, 796, 357, 16, 11, 352, 8, 198, 4514, 11903, 1279, 1802, 25, 198, 220, 220, 220, 3601, 19203, 1212, 5270, 468, 1391, 15, 92, 11903, 4458, 18982, 7, 65, 43...
3.131148
61
import typing from .core import Component _Controller = typing.TypeVar('_Controller') _ControllerType = typing.Type[_Controller] ControllerFactory = typing.NewType('ControllerFactory', typing.Callable[[typing.Type], object]) _controller_factory: typing.Optional[ControllerFactory] = None
[ 11748, 19720, 198, 198, 6738, 764, 7295, 1330, 35100, 198, 198, 62, 22130, 796, 19720, 13, 6030, 19852, 10786, 62, 22130, 11537, 198, 62, 22130, 6030, 796, 19720, 13, 6030, 29795, 22130, 60, 198, 22130, 22810, 796, 19720, 13, 3791, 6030...
3.868421
76
# Copyright 2014 The Bazel 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Public definitions for Go rules. All public Go rules, providers, and other definitions are imported and re-exported in this file. This allows the real location of definitions to change for easier maintenance. Definitions outside this file are private unless otherwise noted, and may change without notice. """ load( "//go/private:context.bzl", _go_context = "go_context", ) load( "//go/private:providers.bzl", _GoArchive = "GoArchive", _GoArchiveData = "GoArchiveData", _GoLibrary = "GoLibrary", _GoPath = "GoPath", _GoSDK = "GoSDK", _GoSource = "GoSource", ) load( "//go/private/rules:sdk.bzl", _go_sdk = "go_sdk", ) load( "//go/private:go_toolchain.bzl", _declare_toolchains = "declare_toolchains", _go_toolchain = "go_toolchain", ) load( "//go/private/rules:wrappers.bzl", _go_binary_macro = "go_binary_macro", _go_library_macro = "go_library_macro", _go_test_macro = "go_test_macro", ) load( "//go/private/rules:source.bzl", _go_source = "go_source", ) load( "//extras:embed_data.bzl", _go_embed_data = "go_embed_data", ) load( "//go/private/tools:path.bzl", _go_path = "go_path", ) load( "//go/private/rules:library.bzl", _go_tool_library = "go_tool_library", ) load( "//go/private/rules:nogo.bzl", _nogo = "nogo_wrapper", ) # TOOLS_NOGO is a list of all analysis passes in # golang.org/x/tools/go/analysis/passes. # This is not backward compatible, so use caution when depending on this -- # new analyses may discover issues in existing builds. TOOLS_NOGO = [ "@org_golang_x_tools//go/analysis/passes/asmdecl:go_default_library", "@org_golang_x_tools//go/analysis/passes/assign:go_default_library", "@org_golang_x_tools//go/analysis/passes/atomic:go_default_library", "@org_golang_x_tools//go/analysis/passes/atomicalign:go_default_library", "@org_golang_x_tools//go/analysis/passes/bools:go_default_library", "@org_golang_x_tools//go/analysis/passes/buildssa:go_default_library", "@org_golang_x_tools//go/analysis/passes/buildtag:go_default_library", # TODO(#2396): pass raw cgo sources to cgocall and re-enable. # "@org_golang_x_tools//go/analysis/passes/cgocall:go_default_library", "@org_golang_x_tools//go/analysis/passes/composite:go_default_library", "@org_golang_x_tools//go/analysis/passes/copylock:go_default_library", "@org_golang_x_tools//go/analysis/passes/ctrlflow:go_default_library", "@org_golang_x_tools//go/analysis/passes/deepequalerrors:go_default_library", "@org_golang_x_tools//go/analysis/passes/errorsas:go_default_library", "@org_golang_x_tools//go/analysis/passes/findcall:go_default_library", "@org_golang_x_tools//go/analysis/passes/httpresponse:go_default_library", "@org_golang_x_tools//go/analysis/passes/ifaceassert:go_default_library", "@org_golang_x_tools//go/analysis/passes/inspect:go_default_library", "@org_golang_x_tools//go/analysis/passes/loopclosure:go_default_library", "@org_golang_x_tools//go/analysis/passes/lostcancel:go_default_library", "@org_golang_x_tools//go/analysis/passes/nilfunc:go_default_library", "@org_golang_x_tools//go/analysis/passes/nilness:go_default_library", "@org_golang_x_tools//go/analysis/passes/pkgfact:go_default_library", "@org_golang_x_tools//go/analysis/passes/printf:go_default_library", "@org_golang_x_tools//go/analysis/passes/shadow:go_default_library", "@org_golang_x_tools//go/analysis/passes/shift:go_default_library", "@org_golang_x_tools//go/analysis/passes/sortslice:go_default_library", "@org_golang_x_tools//go/analysis/passes/stdmethods:go_default_library", "@org_golang_x_tools//go/analysis/passes/stringintconv:go_default_library", "@org_golang_x_tools//go/analysis/passes/structtag:go_default_library", "@org_golang_x_tools//go/analysis/passes/testinggoroutine:go_default_library", "@org_golang_x_tools//go/analysis/passes/tests:go_default_library", "@org_golang_x_tools//go/analysis/passes/unmarshal:go_default_library", "@org_golang_x_tools//go/analysis/passes/unreachable:go_default_library", "@org_golang_x_tools//go/analysis/passes/unsafeptr:go_default_library", "@org_golang_x_tools//go/analysis/passes/unusedresult:go_default_library", ] # Current version or next version to be tagged. Gazelle and other tools may # check this to determine compatibility. RULES_GO_VERSION = "0.30.0" declare_toolchains = _declare_toolchains go_context = _go_context go_embed_data = _go_embed_data go_sdk = _go_sdk go_tool_library = _go_tool_library go_toolchain = _go_toolchain nogo = _nogo # See go/providers.rst#GoLibrary for full documentation. GoLibrary = _GoLibrary # See go/providers.rst#GoSource for full documentation. GoSource = _GoSource # See go/providers.rst#GoPath for full documentation. GoPath = _GoPath # See go/providers.rst#GoArchive for full documentation. GoArchive = _GoArchive # See go/providers.rst#GoArchiveData for full documentation. GoArchiveData = _GoArchiveData # See go/providers.rst#GoSDK for full documentation. GoSDK = _GoSDK # See docs/go/core/rules.md#go_library for full documentation. go_library = _go_library_macro # See docs/go/core/rules.md#go_binary for full documentation. go_binary = _go_binary_macro # See docs/go/core/rules.md#go_test for full documentation. go_test = _go_test_macro # See docs/go/core/rules.md#go_test for full documentation. go_source = _go_source # See docs/go/core/rules.md#go_path for full documentation. go_path = _go_path
[ 2, 15069, 1946, 383, 347, 41319, 46665, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, ...
2.596121
2,372
#!/usr/bin/env python # -*- coding: utf-8 -*- import calendar import csv from datetime import datetime import os from flask_sqlalchemy import SQLAlchemy from sqlalchemy import and_ from ..constants import CONST from ..models import AccidentMarker from ..utilities import init_flask, decode_hebrew, open_utf8 from ..import importmail from xml.dom import minidom import math import requests import logging ############################################################################################ # United.py is responsible for the parsing and deployment of "united hatzala" data to the DB ############################################################################################ PROVIDER_CODE = CONST.UNITED_HATZALA_CODE TIME_ZONE = 2 # convert IMS hours code to hours RAIN_DURATION_CODE_TO_HOURS = {"1": 6, "2": 12, "3": 18, "4": 24, "/": 24, "5": 1, "6": 2, "7": 3, "8": 9, "9": 15} WEATHER = {"0": 1, "1": 2, "3": 3, "4": 4, "5": 5, "7": 6, "8": 6, "9": 7, "10": 8, "11": 9, "12": 10, "17": 11, "18": 12, "19": 13, "20": 14, "21": 15, "22": 16, "23": 17, "24": 18, "25": 19, "26": 20, "27": 21, "28": 22, "29": 23, "30": 24, "31": 24, "32": 24, "33": 7, "34": 7, "35": 7, "36": 25, "37": 25, "38": 25, "39": 25, "40": 26, "41": 27, "42": 28, "43": 29, "44": 9, "45": 30, "46": 30, "47": 30, "48": 31, "49": 32, "50": 33, "51": 34, "52": 33, "53": 35, "54": 36, "55": 37, "56": 38, "57": 39, "58": 37, "59": 37, "61": 37, "60": 36, "62": 40, "63": 15, "64": 41, "65": 19, "66": 42, "67": 43, "68": 44, "69": 45, "70": 46, "71": 47, "72": 48, "73": 16, "74": 50, "75": 51, "76": 52, "77": 53, "78": 54, "79": 55, "80": 56, "81": 57, "82": 58, "83": 59, "84": 60, "85": 61, "86": 62, "87": 63, "88": 64, "89": 65, "90": 66, "91": 67, "92": 68, "93": 69, "94": 70, "95": 71, "96": 72, "97": 73, "98": 74, "99": 75} def parse_date(created): """ :param created: Date & Time string from csv :return: Python datetime object """ global time global hour DATE_FORMATS = ['%m/%d/%Y %I:%M:%S', '%Y-%m-%d %H:%M:%S', '%Y/%m/%d %I:%M:%S', '%d/%m/%Y %I:%M', '%Y/%m/%d %I:%M', '%m/%d/%Y %I:%M'] for date_format in DATE_FORMATS: try: if date_format == '%Y-%m-%d %H:%M:%S': time = datetime.strptime(str(created)[:-4], date_format) hour = time.strftime('%H') hour = int(hour) else: time = datetime.strptime(str(created)[:-3], date_format) hour = time.strftime('%H') hour = int(hour) if str(created).endswith('AM') else int(hour) + 12 break except ValueError: pass return datetime(time.year, time.month, time.day, hour, time.minute, 0) CSVMAP = [ {"id": 0, "time": 1, "lat": 2, "long": 3, "street": 4, "city": 6, "comment": 7, "type": 8, "casualties": 9}, {"id": 0, "time": 1, "type": 2, "long": 3, "lat": 4, "city": 5, "street": 6, "comment": 7, "casualties": 8}, ] def import_to_db(collection, path): """ :param path: Local files directory ('united_path' on main() below) :return: length of DB entries after execution """ app = init_flask() db = SQLAlchemy(app) accidents = list(create_accidents(collection, path)) if not accidents: return 0 new_ids = [m["id"] for m in accidents if 0 == db.session.query(AccidentMarker).filter(and_(AccidentMarker.id == m["id"], AccidentMarker.provider_code == m["provider_code"])).count()] if not new_ids: logging.info("\t\tNothing loaded, all accidents already in DB") return 0 db.session.execute(AccidentMarker.__table__.insert(), [m for m in accidents if m["id"] in new_ids]) db.session.commit() return len(new_ids) def update_db(collection): """ :return: length of DB entries after execution """ app = init_flask() db = SQLAlchemy(app) united = db.session.query(AccidentMarker).filter(AccidentMarker.provider_code == 2) for accident in united: if not accident.weather: accident.weather = process_weather_data(collection, accident.latitude, accident.longitude) db.session.commit() logging.info("\tFinished commiting the changes") def main(light=True, username='', password='', lastmail=False): """ Calls importmail.py prior to importing to DB """ collection = retrieve_ims_xml() if not light: logging.info("Importing data from mail...") importmail.main(username, password, lastmail) united_path = "static/data/united/" total = 0 logging.info("Loading United accidents...") for united_file in os.listdir(united_path): if united_file.endswith(".csv"): total += import_to_db(collection, united_path + united_file) logging.info("\tImported {0} items".format(total)) update_db(collection)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 11845, 198, 11748, 269, 21370, 198, 6738, 4818, 8079, 1330, 4818, 8079, 198, 11748, 28686, 198, 198, 6738, 42903, ...
2.271087
2,217
import unittest from numpy.testing import assert_array_equal import numpy as np from libact.base.dataset import Dataset from libact.models import LogisticRegression from libact.query_strategies import VarianceReduction from .utils import run_qs if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 198, 6738, 299, 32152, 13, 33407, 1330, 6818, 62, 18747, 62, 40496, 198, 11748, 299, 32152, 355, 45941, 198, 198, 6738, 9195, 529, 13, 8692, 13, 19608, 292, 316, 1330, 16092, 292, 316, 198, 6738, 9195, 529, ...
3.09375
96
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from builtins import open from builtins import str from future import standard_library standard_library.install_aliases() import os import re import json import copy import socket import msgpack import traceback import types import backoff from datetime import datetime from uuid import uuid4 from redis import BlockingConnectionPool, StrictRedis, RedisError from celery.utils.log import get_task_logger import hysds from hysds.celery import app from prov_es.model import get_uuid, ProvEsDocument # logger logger = get_task_logger(__name__) # redis connection pools JOB_STATUS_POOL = None JOB_INFO_POOL = None WORKER_STATUS_POOL = None EVENT_STATUS_POOL = None # job status key template JOB_STATUS_KEY_TMPL = "hysds-job-status-%s" # worker status key template WORKER_STATUS_KEY_TMPL = "hysds-worker-status-%s" # task worker key template TASK_WORKER_KEY_TMPL = "hysds-task-worker-%s" def backoff_max_value(): """Return max value for backoff.""" return app.conf.BACKOFF_MAX_VALUE def backoff_max_tries(): """Return max tries for backoff.""" return app.conf.BACKOFF_MAX_TRIES def hard_time_limit_gap(): """Return minimum gap time after soft time limit.""" return app.conf.HARD_TIME_LIMIT_GAP def ensure_hard_time_limit_gap(soft_time_limit, time_limit): """Ensure hard time limit gap.""" gap = hard_time_limit_gap() if soft_time_limit is not None and (time_limit is None or time_limit <= soft_time_limit+gap): time_limit = soft_time_limit + gap return soft_time_limit, time_limit def set_redis_job_status_pool(): """Set redis connection pool for job status.""" global JOB_STATUS_POOL if JOB_STATUS_POOL is None: JOB_STATUS_POOL = BlockingConnectionPool.from_url( app.conf.REDIS_JOB_STATUS_URL) def set_redis_job_info_pool(): """Set redis connection pool for job info metrics.""" global JOB_INFO_POOL if JOB_INFO_POOL is None: JOB_INFO_POOL = BlockingConnectionPool.from_url( app.conf.REDIS_JOB_INFO_URL) def set_redis_worker_status_pool(): """Set redis connection pool for worker status.""" global WORKER_STATUS_POOL if WORKER_STATUS_POOL is None: WORKER_STATUS_POOL = BlockingConnectionPool.from_url( app.conf.REDIS_JOB_STATUS_URL) def set_redis_event_status_pool(): """Set redis connection pool for event status.""" global EVENT_STATUS_POOL if EVENT_STATUS_POOL is None: EVENT_STATUS_POOL = BlockingConnectionPool.from_url( app.conf.REDIS_JOB_STATUS_URL) def log_prov_es(job, prov_es_info, prov_es_file): """Log PROV-ES document. Create temp PROV-ES document to populate attributes that only the worker has access to (e.g. PID).""" # create PROV-ES doc to generate attributes that only verdi know ps_id = "hysds:%s" % get_uuid(job['job_id']) bundle_id = "hysds:%s" % get_uuid('bundle-%s' % job['job_id']) doc = ProvEsDocument() # get bundle #bndl = doc.bundle(bundle_id) bndl = None # create sofware agent sa_label = "hysds:pge_wrapper/%s/%d/%s" % (job['job_info']['execute_node'], job['job_info']['pid'], datetime.utcnow().isoformat()) sa_id = "hysds:%s" % get_uuid(sa_label) doc.softwareAgent(sa_id, str(job['job_info']['pid']), job['job_info']['execute_node'], role=job.get('username', None), label=sa_label, bundle=bndl) # create processStep doc.processStep(ps_id, job['job_info']['cmd_start'], job['job_info']['cmd_end'], [], sa_id, None, [], [], bundle=bndl, prov_type="hysds:%s" % job['type']) # get json pd = json.loads(doc.serialize()) # update software agent and process step if 'bundle' in prov_es_info: if len(prov_es_info['bundle']) == 1: bundle_id_orig = list(prov_es_info['bundle'].keys())[0] # update software agent prov_es_info['bundle'][bundle_id_orig].setdefault( 'agent', {}).update(pd['bundle'][bundle_id]['agent']) # update wasAssociatedWith prov_es_info['bundle'][bundle_id_orig].setdefault( 'wasAssociatedWith', {}).update(pd['bundle'][bundle_id]['wasAssociatedWith']) # update activity if 'activity' in prov_es_info['bundle'][bundle_id_orig]: if len(prov_es_info['bundle'][bundle_id_orig]['activity']) == 1: ps_id_orig = list( prov_es_info['bundle'][bundle_id_orig]['activity'].keys())[0] prov_es_info['bundle'][bundle_id_orig]['activity'][ps_id_orig][ 'prov:startTime'] = pd['bundle'][bundle_id]['activity'][ps_id]['prov:startTime'] prov_es_info['bundle'][bundle_id_orig]['activity'][ps_id_orig][ 'prov:endTime'] = pd['bundle'][bundle_id]['activity'][ps_id]['prov:endTime'] prov_es_info['bundle'][bundle_id_orig]['activity'][ps_id_orig]['hysds:job_id'] = job['job_id'] prov_es_info['bundle'][bundle_id_orig]['activity'][ps_id_orig]['hysds:job_type'] = job['type'] prov_es_info['bundle'][bundle_id_orig]['activity'][ps_id_orig]['hysds:job_url'] = job['job_info']['job_url'] prov_es_info['bundle'][bundle_id_orig]['activity'][ps_id_orig]['hysds:mozart_url'] = app.conf.MOZART_URL if 'prov:type' not in prov_es_info['bundle'][bundle_id_orig]['activity'][ps_id_orig]: prov_es_info['bundle'][bundle_id_orig]['activity'][ps_id_orig][ 'prov:type'] = pd['bundle'][bundle_id]['activity'][ps_id]['prov:type'] # update wasAssociatedWith activity ids for waw_id in prov_es_info['bundle'][bundle_id_orig]['wasAssociatedWith']: if prov_es_info['bundle'][bundle_id_orig]['wasAssociatedWith'][waw_id]['prov:activity'] == ps_id: prov_es_info['bundle'][bundle_id_orig]['wasAssociatedWith'][waw_id]['prov:activity'] = ps_id_orig else: prov_es_info['bundle'][bundle_id_orig]['activity'].update( pd['bundle'][bundle_id]['activity']) else: prov_es_info['bundle'][bundle_id_orig]['activity'] = pd['bundle'][bundle_id]['activity'] else: # update software agent prov_es_info.setdefault('agent', {}).update(pd['agent']) # update wasAssociatedWith prov_es_info.setdefault('wasAssociatedWith', {}).update( pd['wasAssociatedWith']) # update process step if 'activity' in prov_es_info: if len(prov_es_info['activity']) == 1: ps_id_orig = list(prov_es_info['activity'].keys())[0] prov_es_info['activity'][ps_id_orig]['prov:startTime'] = pd['activity'][ps_id]['prov:startTime'] prov_es_info['activity'][ps_id_orig]['prov:endTime'] = pd['activity'][ps_id]['prov:endTime'] prov_es_info['activity'][ps_id_orig]['hysds:job_id'] = job['job_id'] prov_es_info['activity'][ps_id_orig]['hysds:job_type'] = job['type'] prov_es_info['activity'][ps_id_orig]['hysds:job_url'] = job['job_info']['job_url'] prov_es_info['activity'][ps_id_orig]['hysds:mozart_url'] = app.conf.MOZART_URL if 'prov:type' not in prov_es_info['activity'][ps_id_orig]: prov_es_info['activity'][ps_id_orig]['prov:type'] = pd['activity'][ps_id]['prov:type'] # update wasAssociatedWith activity ids for waw_id in prov_es_info['wasAssociatedWith']: if prov_es_info['wasAssociatedWith'][waw_id]['prov:activity'] == ps_id: prov_es_info['wasAssociatedWith'][waw_id]['prov:activity'] = ps_id_orig else: prov_es_info['activity'].update(pd['activity']) else: prov_es_info['activity'] = pd['activity'] # write prov with open(prov_es_file, 'w') as f: json.dump(prov_es_info, f, indent=2) def log_publish_prov_es(prov_es_info, prov_es_file, prod_path, pub_urls, prod_metrics, objectid): """Log publish step in PROV-ES document.""" # create PROV-ES doc doc = ProvEsDocument(namespaces=prov_es_info['prefix']) # get bundle #bndl = doc.bundle(bundle_id) bndl = None # add input entity execute_node = socket.getfqdn() prod_url = "file://%s%s" % (execute_node, prod_path) input_id = "hysds:%s" % get_uuid(prod_url) input_ent = doc.granule(input_id, None, [prod_url], [], None, None, None, label=os.path.basename(prod_url), bundle=bndl) # add output entity output_id = "hysds:%s" % get_uuid(pub_urls[0]) output_ent = doc.product(output_id, None, [pub_urls[0]], [], None, None, None, label=objectid, bundle=bndl) # software and algorithm algorithm = "eos:product_publishing" software_version = hysds.__version__ software_title = "%s v%s" % (hysds.__description__, software_version) software = "eos:HySDS-%s" % software_version software_location = hysds.__url__ doc.software(software, [algorithm], software_version, label=software_title, location=software_location, bundle=bndl) # create sofware agent pid = os.getpid() sa_label = "hysds:publish_dataset/%s/%d/%s" % (execute_node, pid, prod_metrics['time_start']) sa_id = "hysds:%s" % get_uuid(sa_label) doc.softwareAgent(sa_id, str(pid), execute_node, role="invoked", label=sa_label, bundle=bndl) # create processStep job_id = "publish_dataset-%s" % os.path.basename(prod_path) doc.processStep("hysds:%s" % get_uuid(job_id), prod_metrics['time_start'], prod_metrics['time_end'], [software], sa_id, None, [input_id], [output_id], label=job_id, bundle=bndl, prov_type="hysds:publish_dataset") # get json pd = json.loads(doc.serialize()) # update input entity orig_ent = prov_es_info.get('entity', {}).get(input_id, {}) pd['entity'][input_id].update(orig_ent) # update output entity for attr in orig_ent: if attr in ('prov:location', 'prov:label', 'prov:type'): continue pd['entity'][output_id][attr] = orig_ent[attr] # write prov with open(prov_es_file, 'w') as f: json.dump(pd, f, indent=2)
[ 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 7297, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 628, 198, 6738, 3170, 1040, 1...
2.093696
5,251
# Copyright 2015, 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """API for the swift service. """ import os from django import forms from django.http import StreamingHttpResponse from django.utils.http import urlunquote from django.views.decorators.csrf import csrf_exempt from django.views import generic import six from horizon import exceptions from openstack_dashboard import api from openstack_dashboard.api.rest import urls from openstack_dashboard.api.rest import utils as rest_utils from openstack_dashboard.api import swift class UploadObjectForm(forms.Form): file = forms.FileField(required=False)
[ 2, 15069, 1853, 11, 37927, 13200, 11, 1294, 11, 3457, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 1378...
3.660256
312
'''Load image/class/box from a annotation file. The annotation file is organized as: image_name #obj xmin ymin xmax ymax class_index .. ''' from __future__ import print_function import os import sys import os.path import random import numpy as np import torch import torch.utils.data as data import torchvision.transforms as transforms from encoder import DataEncoder from PIL import Image, ImageOps
[ 7061, 6, 8912, 2939, 14, 4871, 14, 3524, 422, 257, 23025, 2393, 13, 198, 198, 464, 23025, 2393, 318, 8389, 355, 25, 198, 220, 220, 220, 2939, 62, 3672, 1303, 26801, 2124, 1084, 331, 1084, 2124, 9806, 331, 9806, 1398, 62, 9630, 11485...
3.474576
118
# Lint as: python3 # Copyright 2020 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 applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """A library to build composite layers. WARNING: The builder pattern is still experimental and we need to gain experience on when to use and when not to use. Please discuss w/ teammates before using it to build complicated layers. """ import functools from lingvo.core import activations from lingvo.core import builder_layers from lingvo.core import hyperparams from lingvo.core import layers from lingvo.core import py_utils from lingvo.core import tshape ###################################################################### # Layers to compose multiple layers. # # Sub-classes are discouraged to override these composition method. ###################################################################### def _Rep(self, name, repeat, *subs): r"""Connects sub-layers sequentially and repeat multiple times. E.g., _Rep('foo', 2, sa, sb, sc) constructs a layer with 6 layers sequentially connected: [sa1, sb1, sc1, sa2, sb2, sc2]. sa1 and sa2 have the same structure as the given sa, but sa1 and sa2 do not share the same weight. Args: name: The layer name. repeat: Repeat \*subs this many times in the compose layer. *subs: A list of sub-layers. Returns: The param for the composed layer. """ iterations = [] for i in range(repeat): iterations.append(self._Seq('iter_%03d' % i, *[p.Copy() for p in subs])) return self._Seq(name, *iterations) def _Seq(self, name, *subs): """Connects sub-layers sequentially.""" return builder_layers.SequentialLayer.Params().Set( name=name, sub=list(subs)) def _Graph(self, name, input_endpoints, output_endpoints, *signature_sub_param_list): """Connects sub-layers into a data flow graph.""" return builder_layers.GraphLayer.Params().Set( name=name, input_endpoints=input_endpoints, output_endpoints=output_endpoints, sub=list(signature_sub_param_list)) def _Id(self, name): """Identity. (t_1, ..., t_n) -> (t1, ..., t_n).""" return self._Seq(name) def _Arg(self, name, index): """Picks index-th element. (t_1, ..., t_n) -> (t_{index},).""" return builder_layers.ArgIndexLayer.Params().Set(name=name, idx=[index]) def _Par(self, name, *subs): """y = (f1, f2, ..., fn)(x). We feed the input tuple to all sub-layers and concatenates their output tuples into one tuple. Args: name: The layer name. *subs: A list of sub-layers. Returns: The param for the composed layer. """ return builder_layers.ParallelLayer.Params().Set( name=name, sub=list(subs), merge=ConcatTuples, merge_meta=ConcatMeta) def _Fn(self, name, fn, fn_out=None, fn_flops=None): """y = fn(x). Applies a fn: tuple(Tensor) -> a single Tensor or tuple(Tensor) to the input tuple. Typically, fn is a very simple python function. This layer can be used for prototyping but we advice to implement the logic as a sub-class of BaseLayer for all established layers as FnLayer can't be serialized. Args: name: The layer name. fn: A lambda tuple(Tensor) -> tuple(Tensor). fn_out: A lambda tuple(tshape.Shape) -> output tuple(tshape.Shape) fn_flops: A lambda tuple(tshape.Shape) -> estimated flops of fn. If None, we assume flops == sum of elements in the inputs. Returns: The param for the composed layer. """ def FnMeta(*shapes): """A lambda tuple(tshape.Shape) -> NestedMap{flops, out_shapes}.""" if fn_out: out_shapes = fn_out(*shapes) if isinstance(out_shapes, tshape.Shape): out_shapes = (out_shapes,) else: out_shapes = shapes if fn_flops: flops = fn_flops(*shapes) else: flops = sum([s.size for s in shapes]) return py_utils.NestedMap(flops=flops, out_shapes=out_shapes) return builder_layers.FnLayer.Params().Set(name=name, fn=fn, fn_meta=FnMeta) def _Save(self, name): """Returns a layer from which the activation and gradient can be accessed.""" return layers.FetchLayer.Params().Set(name=name) def _AddFetches(self, name, body, fetches): """Fetches saved activations in the body sub-layer. E.g.: _AddFetches('foo', _Seq( 'stack', _Layer('layer1', ...), _Save('layer1_out', ...), _Layer('layer2', ...), _Save('layer2_out', ...), _Output('output', ...)), ['layer1_out', 'layer2_out']) The layer returns the stack's final output together with intermediate activations from layer1_out and layer2_out. Args: name: This layer's name. body: The sub-layer. fetches: A list of fetch names inside the sub-layer body. Returns: A layer whose outputs correspond to the activations of fetch points in the sub-layer body. [input1, input2, ..., inputN, fetch1, ..., fetchM]. """ return builder_layers.BranchLayer.Params().Set( name=name, body=body, fetches=fetches) def _Rematerialize(self, name, body): """Forces rematerialization on FProp of the body layer.""" return builder_layers.RematerializationLayer.Params().Set( name=name, body=body) def _BatchParallel(self, name, sub): """Splits the batch and compute the forward pass on multiple devices. Args: name: This layer's name. sub: The sub-layer. Returns: A BatchParallel layer which splits the batch and computes the forward pass on multiple devices. """ return builder_layers.BatchParallelLayer.Params().Set(name=name, sub=sub) def _PrintShape(self, name): """Print FProp input shape information.""" return builder_layers.PrintShapeLayer.Params().Set(name=name) def _CreateNestedMap(self, name, keys): """Returns a NestedMap with keys from fprop args.""" return builder_layers.CreateNestedMapLayer.Params().Set( name=name, keys=keys) ########################################################################### # Basic nn layers. # # The following method returns a layer param, whose FProp takes a single # Tensor and returns a single Tensor. # # These methods are designed to have minimal knobs. Sub-classes which needs to # be flexible can override these methods with different options. E.g., a # sub-class builder can override _BN() to tune the decay option. ########################################################################### def _BN(self, name, dims): """Batch norm.""" return layers.BatchNormLayer.Params().Set(name=name, dim=dims, decay=0.99) def _LN(self, name, dims, use_fused_layernorm=False): """Layer norm.""" return layers.LayerNorm.Params().Set( name=name, input_dim=dims, use_fused_layernorm=use_fused_layernorm, fprop_dtype=self.params.fprop_dtype) def _Dropout(self, name, keep_prob, noise_shape_broadcast_dims=None): """Returns a DropoutLayer Params.""" if self.params.deterministic_dropout: return layers.DeterministicDropoutLayer.Params().Set( name=name, keep_prob=keep_prob, noise_shape_broadcast_dims=noise_shape_broadcast_dims) return layers.DropoutLayer.Params().Set( name=name, keep_prob=keep_prob, noise_shape_broadcast_dims=noise_shape_broadcast_dims, fprop_dtype=self.params.fprop_dtype) def _Linear(self, name, idims, odims, device_mesh=None, weight_split_dims_mapping=None, qdomain=None): """Linear layer. y = matmul([..., idims], [idims, odims]).""" p = builder_layers.LinearLayer.Params() p.name = name p.input_dims = idims p.output_dims = odims p.fprop_dtype = self.params.fprop_dtype p.device_mesh = device_mesh p.weight_split_dims_mapping = weight_split_dims_mapping p.qdomain.default = qdomain return p def _Bias(self, name, dims, device_mesh=None, weight_split_dims_mapping=None): """Bias layer. The bias is added to the last dimension of the input.""" return builder_layers.BiasLayer.Params().Set( name=name, dims=dims, fprop_dtype=self.params.fprop_dtype, device_mesh=device_mesh, weight_split_dims_mapping=weight_split_dims_mapping) def _Activation(self, name, fn='RELU'): """Activation layer.""" return activations.ActivationLayer.Params().Set(activation=fn, name=name) def _FC(self, name, idims, odims, act='RELU'): """Feed-forward fully connected. y = act(matmul(x, w) + b).""" # pyformat: disable return self._Seq( name, self._Linear('linear', idims, odims), self._Bias('bias', odims), self._Activation('act', fn=act)) def _MLP(self, name, dims, act='RELU'): """Multiple layers of feed-forward fully connected. Args: name: The layer name. dims: A list of int. i-th layer has dims[i] as its input dimension, and dims[i+1] as its output dimensions. act: The activation function. Returns: The param for the composed layer. """ l = [] for n, (i, o) in enumerate(zip(dims[:-1], dims[1:])): l += [self._FC('l%03d' % n, i, o, act)] return self._Seq(name, *l) def _Conv2D(self, name, filter_shape, filter_stride): """Conv2D layer.""" return layers.Conv2DLayerNoPadding.Params().Set( name=name, filter_shape=filter_shape, filter_stride=filter_stride, fprop_dtype=self.params.fprop_dtype) def _Reshape(self, name, shape): """Reshape inputs to the shape provided.""" return builder_layers.ReshapeLayer.Params().Set(name=name, shape=shape)
[ 2, 406, 600, 355, 25, 21015, 18, 198, 2, 15069, 12131, 383, 309, 22854, 37535, 46665, 13, 1439, 6923, 33876, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743...
2.619623
3,975
# Copyright (c) 2010 by Cisco Systems, Inc. """ Manage the tool plugins and use them appropriately. """ import os TOOLNAME_PLUGIN_PREFIX = "toolname"
[ 2, 15069, 357, 66, 8, 3050, 416, 28289, 11998, 11, 3457, 13, 198, 37811, 198, 5124, 496, 262, 2891, 20652, 290, 779, 606, 20431, 13, 198, 37811, 198, 11748, 28686, 198, 198, 10468, 3535, 20608, 62, 6489, 7340, 1268, 62, 47, 31688, 1...
3.081633
49
import time from http import HTTPStatus from itertools import count from typing import Sequence import gevent import grequests import pytest import structlog from eth_utils import to_canonical_address from flask import url_for from raiden.api.python import RaidenAPI from raiden.api.rest import APIServer, RestAPI from raiden.constants import RoutingMode from raiden.message_handler import MessageHandler from raiden.network.transport import MatrixTransport from raiden.raiden_event_handler import RaidenEventHandler from raiden.raiden_service import RaidenService from raiden.settings import RestApiConfig from raiden.tests.integration.api.utils import wait_for_listening_port from raiden.tests.integration.fixtures.raiden_network import RestartNode from raiden.tests.utils.detect_failure import raise_on_failure from raiden.tests.utils.protocol import HoldRaidenEventHandler from raiden.tests.utils.transfer import ( assert_synced_channel_state, wait_assert, watch_for_unlock_failures, ) from raiden.transfer import views from raiden.ui.startup import RaidenBundle from raiden.utils.formatting import to_checksum_address from raiden.utils.typing import ( Address, BlockNumber, Host, Iterator, List, Port, TokenAddress, TokenAmount, TokenNetworkAddress, Tuple, ) log = structlog.get_logger(__name__) def iwait_and_get(items: Sequence[gevent.Greenlet]) -> None: """Iteratively wait and get on passed greenlets. This ensures exceptions in the greenlets are re-raised as soon as possible. """ for item in gevent.iwait(items): item.get() def restart_network_and_apiservers( raiden_network: List[RaidenService], restart_node: RestartNode, api_servers: List[APIServer], port_generator: Iterator[Port], ) -> Tuple[List[RaidenService], List[APIServer]]: """Stop an app and start it back""" for rest_api in api_servers: rest_api.stop() new_network = restart_network(raiden_network, restart_node) new_servers = start_apiserver_for_network(new_network, port_generator) return (new_network, new_servers) def stress_send_serial_transfers( rest_apis: List[APIServer], token_address: TokenAddress, identifier_generator: Iterator[int], deposit: TokenAmount, ) -> None: """Send `deposit` transfers of value `1` one at a time, without changing the initial capacity. """ pairs = list(zip(rest_apis, rest_apis[1:] + [rest_apis[0]])) # deplete the channels in one direction for server_from, server_to in pairs: sequential_transfers( server_from=server_from, server_to=server_to, number_of_transfers=deposit, token_address=token_address, identifier_generator=identifier_generator, ) # deplete the channels in the backwards direction for server_to, server_from in pairs: sequential_transfers( server_from=server_from, server_to=server_to, number_of_transfers=deposit * 2, token_address=token_address, identifier_generator=identifier_generator, ) # reset the balances balances by sending the "extra" deposit forward for server_from, server_to in pairs: sequential_transfers( server_from=server_from, server_to=server_to, number_of_transfers=deposit, token_address=token_address, identifier_generator=identifier_generator, ) def stress_send_parallel_transfers( rest_apis: List[APIServer], token_address: TokenAddress, identifier_generator: Iterator[int], deposit: TokenAmount, ) -> None: """Send `deposit` transfers in parallel, without changing the initial capacity.""" pairs = list(zip(rest_apis, rest_apis[1:] + [rest_apis[0]])) # deplete the channels in one direction iwait_and_get( [ gevent.spawn( sequential_transfers, server_from=server_from, server_to=server_to, number_of_transfers=deposit, token_address=token_address, identifier_generator=identifier_generator, ) for server_from, server_to in pairs ] ) # deplete the channels in the backwards direction iwait_and_get( [ gevent.spawn( sequential_transfers, server_from=server_from, server_to=server_to, number_of_transfers=deposit * 2, token_address=token_address, identifier_generator=identifier_generator, ) for server_to, server_from in pairs ] ) # reset the balances balances by sending the "extra" deposit forward iwait_and_get( [ gevent.spawn( sequential_transfers, server_from=server_from, server_to=server_to, number_of_transfers=deposit, token_address=token_address, identifier_generator=identifier_generator, ) for server_from, server_to in pairs ] ) def stress_send_and_receive_parallel_transfers( rest_apis: List[APIServer], token_address: TokenAddress, identifier_generator: Iterator[int], deposit: TokenAmount, ) -> None: """Send transfers of value one in parallel""" pairs = list(zip(rest_apis, rest_apis[1:] + [rest_apis[0]])) forward_transfers = [ gevent.spawn( sequential_transfers, server_from=server_from, server_to=server_to, number_of_transfers=deposit, token_address=token_address, identifier_generator=identifier_generator, ) for server_from, server_to in pairs ] backwards_transfers = [ gevent.spawn( sequential_transfers, server_from=server_from, server_to=server_to, number_of_transfers=deposit, token_address=token_address, identifier_generator=identifier_generator, ) for server_to, server_from in pairs ] iwait_and_get(forward_transfers + backwards_transfers)
[ 11748, 640, 198, 6738, 2638, 1330, 14626, 19580, 198, 6738, 340, 861, 10141, 1330, 954, 198, 6738, 19720, 1330, 45835, 198, 198, 11748, 4903, 1151, 198, 11748, 308, 8897, 3558, 198, 11748, 12972, 9288, 198, 11748, 2878, 6404, 198, 6738, ...
2.341255
2,693
# -*- coding: utf-8 -*- # file: preprocess.py # author: jackie # Copyright (C) 2021. All Rights Reserved. import os import pandas as pd import argparse import emoji import re from sklearn.model_selection import train_test_split parser = argparse.ArgumentParser() parser.add_argument("--inpath", type=str, required=True, default='./raw_data/data1.csv') parser.add_argument("--folder_name", type=str, required=False, default='./custom') parser.add_argument("--task", type=str, required=False, default='aptepc') args = parser.parse_args() main(args.inpath, args.folder_name, args.task)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 2393, 25, 662, 14681, 13, 9078, 198, 2, 1772, 25, 14509, 494, 198, 2, 15069, 357, 34, 8, 33448, 13, 1439, 6923, 33876, 13, 198, 198, 11748, 28686, 198, 11748, 197...
2.984848
198
import os import shutil import requests
[ 11748, 28686, 198, 11748, 4423, 346, 198, 198, 11748, 7007, 628, 628 ]
3.666667
12
from __future__ import absolute_import, division, print_function from fnmatch import fnmatch from glob import glob import os import uuid from warnings import warn import pandas as pd from toolz import merge from .io import _link from ...base import get_scheduler from ..core import DataFrame, new_dd_object from ... import config, multiprocessing from ...base import tokenize, compute_as_if_collection from ...bytes.utils import build_name_function from ...compatibility import PY3 from ...delayed import Delayed, delayed from ...utils import get_scheduler_lock def _pd_to_hdf(pd_to_hdf, lock, args, kwargs=None): """ A wrapper function around pd_to_hdf that enables locking""" if lock: lock.acquire() try: pd_to_hdf(*args, **kwargs) finally: if lock: lock.release() return None def to_hdf(df, path, key, mode='a', append=False, get=None, scheduler=None, name_function=None, compute=True, lock=None, dask_kwargs={}, **kwargs): """ Store Dask Dataframe to Hierarchical Data Format (HDF) files This is a parallel version of the Pandas function of the same name. Please see the Pandas docstring for more detailed information about shared keyword arguments. This function differs from the Pandas version by saving the many partitions of a Dask DataFrame in parallel, either to many files, or to many datasets within the same file. You may specify this parallelism with an asterix ``*`` within the filename or datapath, and an optional ``name_function``. The asterix will be replaced with an increasing sequence of integers starting from ``0`` or with the result of calling ``name_function`` on each of those integers. This function only supports the Pandas ``'table'`` format, not the more specialized ``'fixed'`` format. Parameters ---------- path: string Path to a target filename. May contain a ``*`` to denote many filenames key: string Datapath within the files. May contain a ``*`` to denote many locations name_function: function A function to convert the ``*`` in the above options to a string. Should take in a number from 0 to the number of partitions and return a string. (see examples below) compute: bool Whether or not to execute immediately. If False then this returns a ``dask.Delayed`` value. lock: Lock, optional Lock to use to prevent concurrency issues. By default a ``threading.Lock``, ``multiprocessing.Lock`` or ``SerializableLock`` will be used depending on your scheduler if a lock is required. See dask.utils.get_scheduler_lock for more information about lock selection. **other: See pandas.to_hdf for more information Examples -------- Save Data to a single file >>> df.to_hdf('output.hdf', '/data') # doctest: +SKIP Save data to multiple datapaths within the same file: >>> df.to_hdf('output.hdf', '/data-*') # doctest: +SKIP Save data to multiple files: >>> df.to_hdf('output-*.hdf', '/data') # doctest: +SKIP Save data to multiple files, using the multiprocessing scheduler: >>> df.to_hdf('output-*.hdf', '/data', scheduler='processes') # doctest: +SKIP Specify custom naming scheme. This writes files as '2000-01-01.hdf', '2000-01-02.hdf', '2000-01-03.hdf', etc.. >>> from datetime import date, timedelta >>> base = date(year=2000, month=1, day=1) >>> def name_function(i): ... ''' Convert integer 0 to n to a string ''' ... return base + timedelta(days=i) >>> df.to_hdf('*.hdf', '/data', name_function=name_function) # doctest: +SKIP Returns ------- None: if compute == True delayed value: if compute == False See Also -------- read_hdf: to_parquet: """ name = 'to-hdf-' + uuid.uuid1().hex pd_to_hdf = getattr(df._partition_type, 'to_hdf') single_file = True single_node = True # if path is string, format using i_name if isinstance(path, str): if path.count('*') + key.count('*') > 1: raise ValueError("A maximum of one asterisk is accepted in file " "path and dataset key") fmt_obj = lambda path, i_name: path.replace('*', i_name) if '*' in path: single_file = False else: if key.count('*') > 1: raise ValueError("A maximum of one asterisk is accepted in " "dataset key") fmt_obj = lambda path, _: path if '*' in key: single_node = False if 'format' in kwargs and kwargs['format'] not in ['t', 'table']: raise ValueError("Dask only support 'table' format in hdf files.") if mode not in ('a', 'w', 'r+'): raise ValueError("Mode must be one of 'a', 'w' or 'r+'") if name_function is None: name_function = build_name_function(df.npartitions - 1) # we guarantee partition order is preserved when its saved and read # so we enforce name_function to maintain the order of its input. if not (single_file and single_node): formatted_names = [name_function(i) for i in range(df.npartitions)] if formatted_names != sorted(formatted_names): warn("To preserve order between partitions name_function " "must preserve the order of its input") # If user did not specify scheduler and write is sequential default to the # sequential scheduler. otherwise let the _get method choose the scheduler if (get is None and not config.get('get', None) and scheduler is None and not config.get('scheduler', None) and single_node and single_file): scheduler = 'single-threaded' # handle lock default based on whether we're writing to a single entity _actual_get = get_scheduler(get=get, collections=[df], scheduler=scheduler) if lock is None: if not single_node: lock = True elif not single_file and _actual_get is not multiprocessing.get: # if we're writing to multiple files with the multiprocessing # scheduler we don't need to lock lock = True else: lock = False if lock: lock = get_scheduler_lock(get, df, scheduler=scheduler) kwargs.update({'format': 'table', 'mode': mode, 'append': append}) dsk = dict() i_name = name_function(0) dsk[(name, 0)] = (_pd_to_hdf, pd_to_hdf, lock, [(df._name, 0), fmt_obj(path, i_name), key.replace('*', i_name)], kwargs) kwargs2 = kwargs.copy() if single_file: kwargs2['mode'] = 'a' if single_node: kwargs2['append'] = True filenames = [] for i in range(0,df.npartitions): i_name = name_function(i) filenames.append(fmt_obj(path, i_name)) for i in range(1, df.npartitions): i_name = name_function(i) task = (_pd_to_hdf, pd_to_hdf, lock, [(df._name, i), fmt_obj(path, i_name), key.replace('*', i_name)], kwargs2) if single_file: link_dep = i - 1 if single_node else 0 task = (_link, (name, link_dep), task) dsk[(name, i)] = task dsk = merge(df.dask, dsk) if single_file and single_node: keys = [(name, df.npartitions - 1)] else: keys = [(name, i) for i in range(df.npartitions)] if compute: compute_as_if_collection(DataFrame, dsk, keys, get=get, scheduler=scheduler, **dask_kwargs) return filenames else: return delayed([Delayed(k, dsk) for k in keys]) dont_use_fixed_error_message = """ This HDFStore is not partitionable and can only be use monolithically with pandas. In the future when creating HDFStores use the ``format='table'`` option to ensure that your dataset can be parallelized""" read_hdf_error_msg = """ The start and stop keywords are not supported when reading from more than one file/dataset. The combination is ambiguous because it could be interpreted as the starting and stopping index per file, or starting and stopping index of the global dataset.""" def _read_single_hdf(path, key, start=0, stop=None, columns=None, chunksize=int(1e6), sorted_index=False, lock=None, mode='a'): """ Read a single hdf file into a dask.dataframe. Used for each file in read_hdf. """ def get_keys_stops_divisions(path, key, stop, sorted_index, chunksize): """ Get the "keys" or group identifiers which match the given key, which can contain wildcards. This uses the hdf file identified by the given path. Also get the index of the last row of data for each matched key. """ with pd.HDFStore(path, mode=mode) as hdf: keys = [k for k in hdf.keys() if fnmatch(k, key)] stops = [] divisions = [] for k in keys: storer = hdf.get_storer(k) if storer.format_type != 'table': raise TypeError(dont_use_fixed_error_message) if stop is None: stops.append(storer.nrows) elif stop > storer.nrows: raise ValueError("Stop keyword exceeds dataset number " "of rows ({})".format(storer.nrows)) else: stops.append(stop) if sorted_index: division = [storer.read_column('index', start=start, stop=start + 1)[0] for start in range(0, storer.nrows, chunksize)] division_end = storer.read_column('index', start=storer.nrows - 1, stop=storer.nrows)[0] division.append(division_end) divisions.append(division) else: divisions.append(None) return keys, stops, divisions def one_path_one_key(path, key, start, stop, columns, chunksize, division, lock): """ Get the data frame corresponding to one path and one key (which should not contain any wildcards). """ empty = pd.read_hdf(path, key, mode=mode, stop=0) if columns is not None: empty = empty[columns] token = tokenize((path, os.path.getmtime(path), key, start, stop, empty, chunksize, division)) name = 'read-hdf-' + token if empty.ndim == 1: base = {'name': empty.name, 'mode': mode} else: base = {'columns': empty.columns, 'mode': mode} if start >= stop: raise ValueError("Start row number ({}) is above or equal to stop " "row number ({})".format(start, stop)) dsk = dict(((name, i), (_pd_read_hdf, path, key, lock, update(s))) for i, s in enumerate(range(start, stop, chunksize))) if division: divisions = division else: divisions = [None] * (len(dsk) + 1) return new_dd_object(dsk, name, empty, divisions) keys, stops, divisions = get_keys_stops_divisions(path, key, stop, sorted_index, chunksize) if (start != 0 or stop is not None) and len(keys) > 1: raise NotImplementedError(read_hdf_error_msg) from ..multi import concat return concat([one_path_one_key(path, k, start, s, columns, chunksize, d, lock) for k, s, d in zip(keys, stops, divisions)]) def _pd_read_hdf(path, key, lock, kwargs): """ Read from hdf5 file with a lock """ if lock: lock.acquire() try: result = pd.read_hdf(path, key, **kwargs) finally: if lock: lock.release() return result def read_hdf(pattern, key, start=0, stop=None, columns=None, chunksize=1000000, sorted_index=False, lock=True, mode='a'): """ Read HDF files into a Dask DataFrame Read hdf files into a dask dataframe. This function is like ``pandas.read_hdf``, except it can read from a single large file, or from multiple files, or from multiple keys from the same file. Parameters ---------- pattern : string, list File pattern (string), buffer to read from, or list of file paths. Can contain wildcards. key : group identifier in the store. Can contain wildcards start : optional, integer (defaults to 0), row number to start at stop : optional, integer (defaults to None, the last row), row number to stop at columns : list of columns, optional A list of columns that if not None, will limit the return columns (default is None) chunksize : positive integer, optional Maximal number of rows per partition (default is 1000000). sorted_index : boolean, optional Option to specify whether or not the input hdf files have a sorted index (default is False). lock : boolean, optional Option to use a lock to prevent concurrency issues (default is True). mode : {'a', 'r', 'r+'}, default 'a'. Mode to use when opening file(s). 'r' Read-only; no data can be modified. 'a' Append; an existing file is opened for reading and writing, and if the file does not exist it is created. 'r+' It is similar to 'a', but the file must already exist. Returns ------- dask.DataFrame Examples -------- Load single file >>> dd.read_hdf('myfile.1.hdf5', '/x') # doctest: +SKIP Load multiple files >>> dd.read_hdf('myfile.*.hdf5', '/x') # doctest: +SKIP >>> dd.read_hdf(['myfile.1.hdf5', 'myfile.2.hdf5'], '/x') # doctest: +SKIP Load multiple datasets >>> dd.read_hdf('myfile.1.hdf5', '/*') # doctest: +SKIP """ if lock is True: lock = get_scheduler_lock() key = key if key.startswith('/') else '/' + key if isinstance(pattern, str): paths = sorted(glob(pattern)) else: paths = pattern if (start != 0 or stop is not None) and len(paths) > 1: raise NotImplementedError(read_hdf_error_msg) if chunksize <= 0: raise ValueError("Chunksize must be a positive integer") if (start != 0 or stop is not None) and sorted_index: raise ValueError("When assuming pre-partitioned data, data must be " "read in its entirety using the same chunksizes") from ..multi import concat return concat([_read_single_hdf(path, key, start=start, stop=stop, columns=columns, chunksize=chunksize, sorted_index=sorted_index, lock=lock, mode=mode) for path in paths]) if PY3: from ..core import _Frame _Frame.to_hdf.__doc__ = to_hdf.__doc__
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 11, 7297, 11, 3601, 62, 8818, 198, 198, 6738, 24714, 15699, 1330, 24714, 15699, 198, 6738, 15095, 1330, 15095, 198, 11748, 28686, 198, 11748, 334, 27112, 198, 6738, 14601, 1330, 9828, 198, ...
2.356103
6,456
# -*- coding: utf-8 -*- """ media info manager module. """ from pyrin.core.mixin import HookMixin from pyrin.core.structs import Manager import pyrin.utils.path as path_utils from charma.media_info import MediaInfoPackage from charma.media_info.interface import AbstractMediaInfoProvider from charma.media_info.exceptions import InvalidMediaInfoProviderTypeError
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 11431, 7508, 4706, 8265, 13, 198, 37811, 198, 198, 6738, 279, 2417, 259, 13, 7295, 13, 19816, 259, 1330, 18531, 35608, 259, 198, 6738, 279, 2417, 259, 13, ...
3.306306
111
import unittest from boxrec.parsers import FightParser
[ 11748, 555, 715, 395, 198, 6738, 3091, 8344, 13, 79, 945, 364, 1330, 10480, 46677, 628, 628 ]
3.411765
17
from datetime import datetime, timedelta from bson.objectid import ObjectId WORK_TIMEOUT = 600
[ 6738, 4818, 8079, 1330, 4818, 8079, 11, 28805, 12514, 198, 198, 6738, 275, 1559, 13, 15252, 312, 1330, 9515, 7390, 198, 198, 33249, 62, 34694, 12425, 796, 10053, 628 ]
3.37931
29
# -*- coding: utf-8 -*- # 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"); 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, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import sys import ssl from mock import Mock, call from libcloud.test import unittest from libcloud.common.base import Connection from libcloud.common.base import LoggingConnection if __name__ == '__main__': sys.exit(unittest.main())
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 49962, 284, 262, 24843, 10442, 5693, 357, 1921, 37, 8, 739, 530, 393, 517, 198, 2, 18920, 5964, 11704, 13, 220, 4091, 262, 28536, 2393, 9387, 351, 198, 2, 428, 67...
3.779783
277
import os import sys import bpy script_dir = os.path.dirname(os.path.abspath(__file__)) utils_dir = os.path.join(script_dir, "../../blender_utils") sys.path.append(utils_dir) from utils import bake_model, clean_unused, export_ig_object, import_obj_folder ############################################# # Parse command line arguments ############################################# should_bake = "--bake" in sys.argv axis = ["X", "Y", "Z", "-X", "-Y", "-Z"] import_axis_up = get_arg(sys.argv, "--up", default="Z") if import_axis_up not in axis: raise ValueError("Axis up not supported: {} (should be among X,Y,Z,-X,-Y,-Z)".format(import_axis_up)) import_axis_forward = get_arg(sys.argv, "--forward", default="X") if import_axis_forward not in axis: raise ValueError("Axis forward not supported: {} (should be among X,Y,Z,-X,-Y,-Z)".format(import_axis_forward)) source_dir = get_arg(sys.argv, "--source_dir") if source_dir is None: raise ValueError("Source directory not specified.") dest_dir = get_arg(sys.argv, "--dest_dir") if dest_dir is None: raise ValueError("Destination directory not specified.") os.makedirs(dest_dir, exist_ok=True) model_id = os.path.basename(source_dir) ############################################# # Importing obj files from source dir ############################################# for on in bpy.context.scene.objects.keys(): obj = bpy.context.scene.objects[on] bpy.data.objects.remove(obj) clean_unused() import_obj_folder(model_id, source_dir, up=import_axis_up, forward=import_axis_forward) ############################################# # Optional UV Unwrapping # This only needed if baking will be performed ############################################# if should_bake: uv_unwrapped = True for o in bpy.context.scene.objects: if not o.data.uv_layers: uv_unwrapped = False if not uv_unwrapped: bpy.ops.object.mode_set(mode="OBJECT") vl = bpy.context.view_layer bpy.ops.object.select_all(action="DESELECT") for on in bpy.context.scene.objects.keys(): obj = bpy.context.scene.objects[on] new_uv = bpy.context.scene.objects[on].data.uv_layers.new(name="obj_uv") vl.objects.active = obj obj.select_set(True) bpy.ops.object.editmode_toggle() bpy.ops.mesh.select_all(action="SELECT") bpy.ops.uv.smart_project(angle_limit=66, island_margin=0.02) bpy.context.tool_settings.mesh_select_mode = (False, False, True) bpy.ops.object.mode_set(mode="OBJECT") ############################################# # Export models ############################################# export_ig_object(dest_dir, save_material=not should_bake) ############################################# # Optional Texture Baking ############################################# if should_bake: mat_dir = os.path.join(dest_dir, "material") os.makedirs(mat_dir, exist_ok=True) # bpy.ops.wm.open_mainfile(filepath=blend_path) # import_ig_object(model_root, import_mat=True) for obj in bpy.context.scene.objects: obj.select_set(True) bpy.context.view_layer.objects.active = obj bpy.ops.object.select_all(action="SELECT") bpy.ops.object.join() channels = { "DIFFUSE": (2048, 32), "ROUGHNESS": (1024, 16), "METALLIC": (1024, 16), "NORMAL": (1024, 16), } bake_model(mat_dir, channels, overwrite=True) bpy.ops.wm.quit_blender()
[ 11748, 28686, 198, 11748, 25064, 198, 198, 11748, 275, 9078, 198, 198, 12048, 62, 15908, 796, 28686, 13, 6978, 13, 15908, 3672, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 834, 7753, 834, 4008, 198, 26791, 62, 15908, 796, 28686, 13, 69...
2.636639
1,321
# Copyright 2012 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """ Base utilities to build API operation managers and objects on top of. """ import copy from ceilometerclient.apiclient import base from ceilometerclient.apiclient import exceptions from ceilometerclient import exc def getid(obj): """Extracts object ID. Abstracts the common pattern of allowing both an object or an object's ID (UUID) as a parameter when dealing with relationships. """ try: return obj.id except AttributeError: return obj
[ 2, 15069, 2321, 4946, 25896, 5693, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 220, 407, 779, 428, ...
3.328402
338
import json import os import re import subprocess from base64 import b64decode from enum import Enum from math import ceil, floor from pathlib import Path from urllib.error import HTTPError from urllib.request import urlopen import yaml from charmhelpers.core import hookenv from charmhelpers.core.unitdata import kv from charms.layer import status ENTITY_PREFIX = 'charm.azure' MODEL_UUID = os.environ['JUJU_MODEL_UUID'] MAX_ROLE_NAME_LEN = 64 MAX_POLICY_NAME_LEN = 128 # When debugging hooks, for some reason HOME is set to /home/ubuntu, whereas # during normal hook execution, it's /root. Set it here to be consistent. os.environ['HOME'] = '/root' def get_credentials(): """ Get the credentials from either the config or the hook tool. Prefers the config so that it can be overridden. """ no_creds_msg = 'missing credentials; set credentials config' config = hookenv.config() # try to use Juju's trust feature try: result = subprocess.run(['credential-get'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) creds = yaml.load(result.stdout.decode('utf8')) creds_data = creds['credential']['attributes'] login_cli(creds_data) return True except FileNotFoundError: pass # juju trust not available except subprocess.CalledProcessError as e: if 'permission denied' not in e.stderr.decode('utf8'): raise no_creds_msg = 'missing credentials access; grant with: juju trust' # try credentials config if config['credentials']: try: creds_data = b64decode(config['credentials']).decode('utf8') login_cli(creds_data) return True except Exception: status.blocked('invalid value for credentials config') return False # no creds provided status.blocked(no_creds_msg) return False def login_cli(creds_data): """ Use the credentials to authenticate the Azure CLI. """ app_id = creds_data['application-id'] app_pass = creds_data['application-password'] sub_id = creds_data['subscription-id'] tenant_id = _get_tenant_id(sub_id) try: log('Forcing logout of Azure CLI') _azure('logout') except AzureError: pass try: log('Logging in to Azure CLI') _azure('login', '--service-principal', '-u', app_id, '-p', app_pass, '-t', tenant_id) # cache the subscription ID for use in roles kv().set('charm.azure.sub-id', sub_id) except AzureError as e: # redact the credential info from the exception message stderr = re.sub(app_id, '<app-id>', e.args[0]) stderr = re.sub(app_pass, '<app-pass>', stderr) stderr = re.sub(tenant_id, '<tenant-id>', stderr) # from None suppresses the previous exception from the stack trace raise AzureError(stderr) from None def send_additional_metadata(request): """ Get additional info about the requesting instance via the API that isn't available from the metadata server. """ res_grp = _azure('group', 'show', '--name', request.resource_group) # hard-code most of these because with Juju, they're always the same # and the queries required to look them up are a PITA request.send_additional_metadata( resource_group_location=res_grp['location'], vnet_name='juju-internal-network', vnet_resource_group=request.resource_group, subnet_name='juju-internal-subnet', security_group_name='juju-internal-nsg', ) def tag_instance(request): """ Tag the given instance with the given tags. """ log('Tagging instance with: {}', request.instance_tags) _azure('vm', 'update', '--name', request.vm_name, '--resource-group', request.resource_group, '--set', *['tags.{}={}'.format(tag, value) for tag, value in request.instance_tags.items()]) def enable_instance_inspection(request): """ Enable instance inspection access for the given application. """ log('Enabling instance inspection') _assign_role(request, _get_role('vm-reader')) def enable_network_management(request): """ Enable network management for the given application. """ log('Enabling network management') _assign_role(request, StandardRole.NETWORK_MANAGER) def enable_security_management(request): """ Enable security management for the given application. """ log('Enabling security management') _assign_role(request, StandardRole.SECURITY_MANAGER) def enable_block_storage_management(request): """ Enable block storage (disk) management for the given application. """ log('Enabling block storage management') _assign_role(request, _get_role('disk-manager')) def enable_dns_management(request): """ Enable DNS management for the given application. """ log('Enabling DNS management') _assign_role(request, StandardRole.DNS_MANAGER) def enable_object_storage_access(request): """ Enable object storage read-only access for the given application. """ log('Enabling object storage read') _assign_role(request, StandardRole.OBJECT_STORE_READER) def enable_object_storage_management(request): """ Enable object storage management for the given application. """ log('Enabling object store management') _assign_role(request, StandardRole.OBJECT_STORE_MANAGER) def cleanup(): """ Perform cleanup. """ pass # Internal helpers def _elide(s, max_len, ellipsis='...'): """ Elide s in the middle to ensure it is under max_len. That is, shorten the string, inserting an ellipsis where the removed characters were to show that they've been removed. """ if len(s) > max_len: hl = (max_len - len(ellipsis)) / 2 headl, taill = floor(hl), ceil(hl) s = s[:headl] + ellipsis + s[-taill:] return s def _get_tenant_id(subscription_id): """ Translate the subscription ID into a tenant ID by making an unauthorized request to the API and extracting the tenant ID from the WWW-Authenticate header in the error response. """ url = ('https://management.azure.com/subscriptions/' '{}?api-version=2018-03-01-01.6.1'.format(subscription_id)) try: urlopen(url) log_err('Error getting tenant ID: did not get "unauthorized" response') return None except HTTPError as e: if 'WWW-Authenticate' not in e.headers: log_err('Error getting tenant ID: missing WWW-Authenticate header') return None www_auth = e.headers['WWW-Authenticate'] match = re.search(r'authorization_uri="[^"]*/([^/"]*)"', www_auth) if not match: log_err('Error getting tenant ID: unable to find in {}', www_auth) return None return match.group(1) def _azure(cmd, *args, return_stderr=False): """ Call the azure-cli tool. """ cmd = ['az', cmd] cmd.extend(args) result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) stdout = result.stdout.decode('utf8').strip() stderr = result.stderr.decode('utf8').strip() if result.returncode != 0: raise AzureError.get(stderr) if return_stderr: return stderr if stdout: stdout = json.loads(stdout) return stdout def _get_msi(vm_id): """ Get the Managed System Identity for the VM. """ vm_identities = kv().get('charm.azure.vm-identities', {}) return vm_identities.get(vm_id) def _get_role(role_name): """ Translate short role name into a full role name and ensure that the custom role is loaded. The custom roles have to be applied to a specific subscription ID, but the subscription ID applies to the entire credential, so will almost certainly be reused, so there's not much danger in hitting the 2k custom role limit. """ known_roles = kv().get('charm.azure.roles', {}) if role_name in known_roles: return known_roles[role_name] sub_id = kv().get('charm.azure.sub-id') role_file = Path('files/roles/{}.json'.format(role_name)) role_data = json.loads(role_file.read_text()) role_fullname = role_data['Name'].format(sub_id) scope = role_data['AssignableScopes'][0].format(sub_id) role_data['Name'] = role_fullname role_data['AssignableScopes'][0] = scope try: log('Ensuring role {}', role_fullname) _azure('role', 'definition', 'create', '--role-definition', json.dumps(role_data)) except AzureError as e: if 'already exists' not in e.args[0]: raise known_roles[role_name] = role_fullname return role_fullname
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 850, 14681, 198, 6738, 2779, 2414, 1330, 275, 2414, 12501, 1098, 198, 6738, 33829, 1330, 2039, 388, 198, 6738, 10688, 1330, 2906, 346, 11, 4314, 198, 6738, 3108, 8019, 1330, ...
2.465649
3,668
import socket import csv import traceback import threading s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) usrpass={} ihost=socket.gethostname() host=socket.gethostbyname(ihost) ihost=socket.gethostname() host=socket.gethostbyname(ihost) iport=[] hostfile="host.csv" with open(hostfile,'r')as host_file: csv_hfile = csv.reader(host_file, delimiter=",") for row in csv_hfile: iport.append(row[1]) port=int(iport[4]) # def checkusr(username): # if username in usrpass: # return 1 # else: # print("Invalid Username") # return -1 main()
[ 11748, 17802, 198, 11748, 269, 21370, 198, 11748, 12854, 1891, 198, 11748, 4704, 278, 198, 198, 82, 28, 44971, 13, 44971, 7, 44971, 13, 8579, 62, 1268, 2767, 11, 44971, 13, 50, 11290, 62, 2257, 32235, 8, 198, 14629, 6603, 34758, 92, ...
2.037037
324
from itertools import product from sklearn.base import clone from sklearn.preprocessing import FunctionTransformer from sklearn.model_selection import ParameterGrid from imblearn.pipeline import Pipeline from rlearn.utils import check_random_states def check_pipelines(objects_list, random_state, n_runs): """Extract estimators and parameters grids.""" # Create random states random_states = check_random_states(random_state, n_runs) pipelines = [] param_grid = [] for comb, rs in product(product(*objects_list), random_states): name = "|".join([i[0] for i in comb]) # name, object, sub grid comb = [ (nm, ob, ParameterGrid(sg)) if ob is not None else (nm, FunctionTransformer(), ParameterGrid(sg)) for nm, ob, sg in comb ] # Create estimator if name not in [n[0] for n in pipelines]: est = Pipeline([(nm, ob) for nm, ob, _ in comb]) pipelines.append((name, est)) # Create intermediate parameter grids sub_grids = [ [{f"{nm}__{k}": v for k, v in param_def.items()} for param_def in sg] for nm, obj, sg in comb ] # Create parameter grids for sub_grid in product(*sub_grids): param_prefix = "" if len(comb) == 1 else f"{name}__" grid = {"est_name": [name]} grid.update( {f"{param_prefix}{k}": [v] for d in sub_grid for k, v in d.items()} ) random_states = { f"{param_prefix}{param}": [rs] for param in est.get_params() if "random_state" in param } grid.update(random_states) # Avoid multiple runs over pipelines without random state if grid not in param_grid: param_grid.append(grid) return pipelines, param_grid
[ 6738, 340, 861, 10141, 1330, 1720, 198, 6738, 1341, 35720, 13, 8692, 1330, 17271, 198, 6738, 1341, 35720, 13, 3866, 36948, 1330, 15553, 8291, 16354, 198, 6738, 1341, 35720, 13, 19849, 62, 49283, 1330, 25139, 2357, 41339, 198, 6738, 545, ...
2.237485
859
from mushroom_rl.utils.plots import PlotItemBuffer, DataBuffer from mushroom_rl.utils.plots.plot_item_buffer import PlotItemBufferLimited
[ 6738, 28520, 62, 45895, 13, 26791, 13, 489, 1747, 1330, 28114, 7449, 28632, 11, 6060, 28632, 198, 6738, 28520, 62, 45895, 13, 26791, 13, 489, 1747, 13, 29487, 62, 9186, 62, 22252, 1330, 28114, 7449, 28632, 37214, 628, 628, 628 ]
3.575
40
# -*- coding: utf-8 -*- # # test/test_metadata.py # Part of python-daemon, an implementation of PEP 3143. # # This is free software, and you are welcome to redistribute it under # certain conditions; see the end of this file for copyright # information, grant of license, and disclaimer of warranty. """ Unit test for _metadata private module. """ from __future__ import (absolute_import, unicode_literals) import collections import errno import functools import json import re try: # Python 3 standard library. import urllib.parse as urlparse except ImportError: # Python 2 standard library. import urlparse import mock import pkg_resources import testtools.helpers import testtools.matchers from . import scaffold from .scaffold import unicode import daemon._metadata as metadata FakeYearRange = collections.namedtuple('FakeYearRange', ['begin', 'end']) try: FileNotFoundError except NameError: # Python 2 uses IOError. FileNotFoundError = functools.partial(IOError, errno.ENOENT) version_info_filename = "version_info.json" def fake_func_has_metadata(testcase, resource_name): """ Fake the behaviour of pkg_resources.Distribution.has_metadata. """ if ( resource_name != testcase.version_info_filename or not hasattr(testcase, 'test_version_info')): return False return True def fake_func_get_metadata(testcase, resource_name): """ Fake the behaviour of pkg_resources.Distribution.get_metadata. """ if not fake_func_has_metadata(testcase, resource_name): error = FileNotFoundError(resource_name) raise error content = testcase.test_version_info return content def fake_func_get_distribution(testcase, distribution_name): """ Fake the behaviour of pkg_resources.get_distribution. """ if distribution_name != metadata.distribution_name: raise pkg_resources.DistributionNotFound if hasattr(testcase, 'get_distribution_error'): raise testcase.get_distribution_error mock_distribution = testcase.mock_distribution mock_distribution.has_metadata.side_effect = functools.partial( fake_func_has_metadata, testcase) mock_distribution.get_metadata.side_effect = functools.partial( fake_func_get_metadata, testcase) return mock_distribution # Copyright 20082018 Ben Finney <ben+python@benfinney.id.au> # # This is free software: you may copy, modify, and/or distribute this work # under the terms of the GNU General Public License as published by the # Free Software Foundation; version 3 of that license or any later version. # No warranty expressed or implied. See the file LICENSE.GPL-3 for details. # Local variables: # coding: utf-8 # mode: python # End: # vim: fileencoding=utf-8 filetype=python :
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 1332, 14, 9288, 62, 38993, 13, 9078, 198, 2, 2142, 286, 21015, 12, 6814, 7966, 11, 281, 7822, 286, 350, 8905, 513, 21139, 13, 198, 2, 198, 2, 770, 318, ...
3.039046
922
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. from typing import Union, List from .purpose import * from .trait_reference import TraitReference from cdm.utilities import JObject
[ 2, 15069, 357, 66, 8, 5413, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 49962, 739, 262, 17168, 13789, 13, 4091, 13789, 13, 14116, 287, 262, 1628, 6808, 329, 5964, 1321, 13, 198, 198, 6738, 19720, 1330, 4479, 11, 7343, 198, 198, 6738,...
4.202899
69
import re from typing import Union, List import nltk from bs4 import BeautifulSoup
[ 11748, 302, 198, 6738, 19720, 1330, 4479, 11, 7343, 198, 198, 11748, 299, 2528, 74, 198, 6738, 275, 82, 19, 1330, 23762, 50, 10486, 198 ]
3.36
25
""" For backwards-compatibility. keep this file. (Many people are going to have key bindings that rely on this file.) """ from __future__ import unicode_literals from .app import * __all__ = [ # Old names. 'HasArg', 'HasCompletions', 'HasFocus', 'HasSelection', 'HasValidationError', 'IsDone', 'IsReadOnly', 'IsMultiline', 'RendererHeightIsKnown', 'InEditingMode', 'InPasteMode', 'ViMode', 'ViNavigationMode', 'ViInsertMode', 'ViInsertMultipleMode', 'ViReplaceMode', 'ViSelectionMode', 'ViWaitingForTextObjectMode', 'ViDigraphMode', 'EmacsMode', 'EmacsInsertMode', 'EmacsSelectionMode', 'IsSearching', 'HasSearch', 'ControlIsSearchable', ] # Keep the original classnames for backwards compatibility. HasValidationError = lambda: has_validation_error HasArg = lambda: has_arg IsDone = lambda: is_done RendererHeightIsKnown = lambda: renderer_height_is_known ViNavigationMode = lambda: vi_navigation_mode InPasteMode = lambda: in_paste_mode EmacsMode = lambda: emacs_mode EmacsInsertMode = lambda: emacs_insert_mode ViMode = lambda: vi_mode IsSearching = lambda: is_searching HasSearch = lambda: is_searching ControlIsSearchable = lambda: control_is_searchable EmacsSelectionMode = lambda: emacs_selection_mode ViDigraphMode = lambda: vi_digraph_mode ViWaitingForTextObjectMode = lambda: vi_waiting_for_text_object_mode ViSelectionMode = lambda: vi_selection_mode ViReplaceMode = lambda: vi_replace_mode ViInsertMultipleMode = lambda: vi_insert_multiple_mode ViInsertMode = lambda: vi_insert_mode HasSelection = lambda: has_selection HasCompletions = lambda: has_completions IsReadOnly = lambda: is_read_only IsMultiline = lambda: is_multiline HasFocus = has_focus # No lambda here! (Has_focus is callable that returns a callable.) InEditingMode = in_editing_mode
[ 37811, 198, 1890, 16196, 12, 5589, 25901, 13, 1394, 428, 2393, 13, 198, 7, 7085, 661, 389, 1016, 284, 423, 1994, 34111, 326, 8814, 319, 428, 2393, 2014, 198, 37811, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198,...
2.852359
657
#spaces.py ''' AlgoHack Genetic Algorithm for University Semaster Planning Version 0.03 2018 Niranjan Meegammana Shilpasayura.org ''' import xdb if __name__ == "__main__": delay=0.05 conn=xdb.opendb('genetic56.db') cursor =conn.cursor() # create a cursor object success=crt_spaces_table(cursor, True) # create spaces table #dedicated lecture hall, lab for group and semaster success, count =insert_spaces(cursor,1,1,1,1,delay) # generate records xdb.commit(conn) xdb.closedb(conn)
[ 2, 2777, 2114, 13, 9078, 201, 198, 7061, 6, 201, 198, 2348, 2188, 32833, 42295, 978, 42289, 329, 2059, 12449, 1603, 21913, 201, 198, 14815, 657, 13, 3070, 2864, 201, 198, 45, 343, 272, 13881, 337, 1453, 28483, 805, 64, 911, 346, 444...
2.429864
221
import urllib.request import cv2 import numpy as np import time import threading
[ 11748, 2956, 297, 571, 13, 25927, 198, 11748, 269, 85, 17, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 640, 198, 11748, 4704, 278, 198 ]
3.24
25
#! /usr/bin/python3 import time import random import json import os from pprint import pprint from kubernetes.client.rest import ApiException from pint import UnitRegistry from collections import defaultdict from kubernetes import client, config, watch from timeloop import Timeloop from datetime import timedelta config.load_kube_config() #config.load_incluster_config() # doing this computation within a k8s cluster #k8s.config.load_incluster_config() core_api = client.CoreV1Api() apis_api = client.AppsV1Api() #sdclient = SdcClient(<Your Sysdig API token>) sysdig_metric = "net.http.request.time" metrics = [{ "id": sysdig_metric, "aggregations": { "time": "timeAvg", "group": "avg" } }] #scheduler_name = "Ec2SpotK8sScheduler" CustomSchedulerName ='K8SCustomScheduler' ureg = UnitRegistry() ureg.load_definitions('kubernetes_units.txt') pendingPodsList = [] failedPodsList = [] runningPodsList =[] nodesListPerNodeLabel = {} Q_ = ureg.Quantity #tl = Timeloop() #@tl.job(interval=timedelta(seconds=10)) __all__ = ["get_node_available_nodes_list"] if __name__ == '__main__': #ready_nodes = nodes_available() #pprint(ready_nodes) #name='review-v1-787d8fbfbb-ltdzt' node='ip-10-0-3-253.ec2.internal' #namespace='ecommerce' #ret=scheduler(name, node, namespace) #pprint(ret) #main() #test() #testpod() #check_node_resources(node) #RunEc2SpotCustomScheduler() #getPodsListForDeployment(' ') #lifecycle = 'OnDemand' #lifecycle = 'Ec2Spot' #get_node_available_nodes_list(lifecycle) #RunEc2SpotCustomScheduler() #NumOfPodsToDeleted = 1 #podsAlreadyRunningOnNodeLabelList = [] #d ={'name':'nginx-66cb875766-vx6bp'} #podsAlreadyRunningOnNodeLabelList.append(d) #deletePods(NumOfPodsToDeleted, podsAlreadyRunningOnNodeLabelList) #deploymentName='nginx' #deploymentName = 'kube-ops-view' #getPodsListForDeployment(deploymentName) #testlist() #tl.start(block=True) while True: RunEc2SpotCustomScheduler() time.sleep(10)
[ 2, 0, 1220, 14629, 14, 8800, 14, 29412, 18, 198, 198, 11748, 640, 198, 11748, 4738, 198, 11748, 33918, 198, 11748, 28686, 198, 6738, 279, 4798, 1330, 279, 4798, 198, 6738, 479, 18478, 3262, 274, 13, 16366, 13, 2118, 1330, 5949, 72, ...
2.272727
957
#!/usr/bin/env python3 # -*- coding: utf-8 -*- from clean_transcript import clean_transcript ALPHABET_FILE_PATH = "/DeepSpeech/bin/bangor_welsh/alphabet.txt"
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 3424, 62, 7645, 6519, 1330, 3424, 62, 7645, 6519, 198, 198, 1847, 11909, 6242, 2767, 62, 25664, 62, 34...
2.461538
65
# Copyright (c) 2019-2020, NVIDIA CORPORATION. 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from typing import List, Optional import functools import torch import torch.nn as nn import torch.nn.functional as F def _init_weight(weight, d : int, init_scale : Optional[float], default=None): assert init_scale or default if init_scale is None: std = default else: std = init_scale * (d ** -0.5) nn.init.normal_(weight, mean=0, std=std) _init_embed = functools.partial(_init_weight, default=0.02) _init_proj = functools.partial(_init_weight, default=0.01) ### Just for this codebase, we need to squeeze the last dimension because inputs are always given as (B, L, D) instead of (B, L) import src.models.nn.utils as U # AdaptiveEmbedding = U.Squeeze(AdaptiveEmbedding)
[ 2, 15069, 357, 66, 8, 13130, 12, 42334, 11, 15127, 23929, 44680, 6234, 13, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428...
3.171838
419
import json import csv import sys import os import re import codecs import logging from logging.config import dictConfig import click import yaml from sqlalchemy import create_engine from jsontableschema_sql import Storage from smart_open import smart_open from . import postgres from . import carto csv.field_size_limit(sys.maxsize)
[ 11748, 33918, 198, 11748, 269, 21370, 198, 11748, 25064, 198, 11748, 28686, 198, 11748, 302, 198, 11748, 40481, 82, 198, 11748, 18931, 198, 6738, 18931, 13, 11250, 1330, 8633, 16934, 198, 198, 11748, 3904, 198, 11748, 331, 43695, 198, 673...
3.510417
96
# Copyright (c) 2020, NVIDIA CORPORATION. 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 agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This script is based on speech_to_text_infer.py and allows you to score the hypotheses with sclite. A local installation from https://github.com/usnistgov/SCTK is required. Hypotheses and references are first saved in trn format and are scored after applying a glm file (if provided). """ import errno import json import os import subprocess from argparse import ArgumentParser import torch from nemo.collections.asr.metrics.wer import WER from nemo.collections.asr.models import EncDecCTCModel from nemo.utils import logging try: from torch.cuda.amp import autocast except ImportError: from contextlib import contextmanager can_gpu = torch.cuda.is_available() if __name__ == '__main__': main() # noqa pylint: disable=no-value-for-parameter
[ 2, 15069, 357, 66, 8, 12131, 11, 15127, 23929, 44680, 6234, 13, 220, 1439, 2489, 10395, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, 345, 743, 407, 779, 428, 2393...
3.45
400
from manimlib.imports import * from manimlib.utils import bezier import numpy as np
[ 6738, 582, 320, 8019, 13, 320, 3742, 1330, 1635, 198, 6738, 582, 320, 8019, 13, 26791, 1330, 307, 89, 959, 198, 11748, 299, 32152, 355, 45941 ]
3.192308
26
from setuptools import setup setup(name='rapid_plotly', version='0.1', description='Convenience functions to rapidly create beautiful Plotly graphs', author='Joseph Dasenbrock', author_email='dasenbrockjw@gmail.com', packages=['rapid_plotly'], zip_safe=False)
[ 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 40406, 7, 3672, 11639, 2416, 312, 62, 29487, 306, 3256, 198, 220, 220, 220, 220, 220, 2196, 11639, 15, 13, 16, 3256, 198, 220, 220, 220, 220, 220, 6764, 11639, 3103, 574, 1240, 5499, 28...
2.582609
115
#! /usr/bin/doit -f # https://pydoit.org # `pip install [--user] doit` adds `doit.exe` to the PATH # - Note `doit auto`, the file watcher only works on Linux/Mac # - All commands are relative to dodo.py (doit runs in the working dir of dodo.py # even if ran from a different directory `doit -f path/to/dodo.py`) from glob import glob import json from os import environ from os.path import abspath, basename, dirname, exists, expanduser, join, splitext from shutil import copyfile from typing import Iterator, List, NewType, Optional from doit.tools import title_with_actions Path = NewType("Path", str) home = Path(expanduser("~")) bml_tools_dir = Path(environ.get("BML_TOOLS_DIRECTORY", join(home, "dev/bml"))) bml_includes_cache_file = ".include-deps.json" def task_bmlcss(): """Copy the bml CSS style sheet to this directory.""" css_basename = "bml.css" src_css_file = Path(join(bml_tools_dir, css_basename)) return { 'actions': [copy_file], 'file_dep': [src_css_file], 'targets': [css_basename], 'title': title_with_actions }
[ 2, 0, 1220, 14629, 14, 8800, 14, 4598, 270, 532, 69, 198, 2, 3740, 1378, 9078, 4598, 270, 13, 2398, 198, 2, 4600, 79, 541, 2721, 685, 438, 7220, 60, 466, 270, 63, 6673, 4600, 4598, 270, 13, 13499, 63, 284, 262, 46490, 198, 2, ...
2.62201
418
filenames = ["myfile1", "nonExistent", "emptyFile", "myfile2"] for file in filenames: try: f = open(file, 'r') line = f.readline() if line == "": f.close() raise EmptyFileError("%s: is empty" % file) # except IOError as error: # print("%s: could not be opened: %s" % (file, error.strerror) ## except EmptyFileError as error: # print(error) # else: # print("%s: %s" % (file, f.readline())) # finally: # print("Done processing", file)
[ 10379, 268, 1047, 796, 14631, 1820, 7753, 16, 1600, 366, 13159, 3109, 7609, 1600, 366, 28920, 8979, 1600, 366, 1820, 7753, 17, 8973, 198, 1640, 2393, 287, 1226, 268, 1047, 25, 198, 220, 220, 220, 1949, 25, 198, 220, 220, 220, 220, 2...
1.926667
300
# Crumbling In # Like randomised coloured dots and then they # increase on both sides getting closer and closer into the middle. import sys, traceback, random from numpy import array,full
[ 2, 3864, 14739, 554, 198, 2, 4525, 4738, 1417, 34746, 22969, 290, 788, 484, 198, 2, 2620, 319, 1111, 5389, 1972, 5699, 290, 5699, 656, 262, 3504, 13, 198, 198, 11748, 25064, 11, 12854, 1891, 11, 4738, 198, 6738, 299, 32152, 1330, 71...
4.108696
46
from __future__ import division from unittest import skipIf, TestCase import os from pandas import DataFrame import numpy as np from numpy.testing import assert_array_equal BACKEND_AVAILABLE = os.environ.get("ETS_TOOLKIT", "qt4") != "null" if BACKEND_AVAILABLE: from app_common.apptools.testing_utils import assert_obj_gui_works from pybleau.app.plotting.plot_config import HeatmapPlotConfigurator, \ HEATMAP_PLOT_TYPE, HistogramPlotConfigurator, HIST_PLOT_TYPE, \ LinePlotConfigurator, BarPlotConfigurator, ScatterPlotConfigurator, \ SCATTER_PLOT_TYPE, CMAP_SCATTER_PLOT_TYPE, LINE_PLOT_TYPE, \ BAR_PLOT_TYPE LEN = 16 TEST_DF = DataFrame({"a": [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4], "b": [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4], "c": [1, 2, 3, 4, 2, 3, 1, 1, 4, 4, 5, 6, 4, 4, 5, 6], "d": list("ababcabcdabcdeab"), "e": np.random.randn(LEN), "f": range(LEN), # Highly repetitive column to split the entire data into 2 "g": np.array(["0", "1"] * (LEN // 2)), "h": np.array([0, 1] * (LEN // 2), dtype=bool), })
[ 6738, 11593, 37443, 834, 1330, 7297, 198, 198, 6738, 555, 715, 395, 1330, 14267, 1532, 11, 6208, 20448, 198, 11748, 28686, 198, 6738, 19798, 292, 1330, 6060, 19778, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 299, 32152, 13, 33407, 1...
1.9375
656
import os.path from .. import *
[ 11748, 28686, 13, 6978, 198, 198, 6738, 11485, 1330, 1635, 628, 628 ]
3
12
from collections import namedtuple # Basic example Point = namedtuple('Point', ['x', 'y']) p = Point(11, y=22) print(p[0] + p[1]) x, y = p print(x, y) print(p.x + p.y) print(Point(x=11, y=22)) from collections import namedtuple import csv f = open("users.csv", "r") next(f) reader = csv.reader(f) student_list = [] for row in reader: student_list.append(row) print(row) print(student_list) columns = ["user_id", "integration_id", "login_id", "password", "first_name", "last_name", "full_name", "sortable_name", "short_name", "email", "status"] Student = namedtuple('Student', columns) student_namedtupe_list = [] for row in student_list: student = Student(*row) student_namedtupe_list.append(student) print(student_namedtupe_list[0]) print(student_namedtupe_list[0].full_name)
[ 6738, 17268, 1330, 3706, 83, 29291, 198, 198, 2, 14392, 1672, 198, 12727, 796, 3706, 83, 29291, 10786, 12727, 3256, 37250, 87, 3256, 705, 88, 6, 12962, 198, 79, 796, 6252, 7, 1157, 11, 331, 28, 1828, 8, 198, 4798, 7, 79, 58, 15, ...
2.472892
332
# Profile mitmdump with apachebench and # yappi (https://code.google.com/p/yappi/) # # Requirements: # - Apache Bench "ab" binary # - pip install click yappi from mitmproxy.main import mitmdump from os import system from threading import Thread import time import yappi import click if __name__ == '__main__': main()
[ 2, 13118, 10255, 9132, 931, 351, 2471, 4891, 26968, 290, 198, 2, 331, 1324, 72, 357, 5450, 1378, 8189, 13, 13297, 13, 785, 14, 79, 14, 88, 1324, 72, 34729, 198, 2, 198, 2, 24422, 25, 198, 2, 532, 24843, 25187, 366, 397, 1, 13934...
3
109
# -*- coding: utf-8 -*- """ Various plots """ import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation, FFMpegWriter import xarray as xr import os def quiver(data, arrScale = 25.0, threshold = None, nthArr = 1, contourLevels = None, colbar = True, logscale = False, aspectratio='equal', colbar_orient = 'vertical', units = None): """ Generates a quiver plot of a 'data' xarray DataArray object (single frame from a dataset) Inputs: data - xarray DataArray of the type defined in pivpy, one of the frames in the Dataset selected by default using .isel(t=0) threshold - values above the threshold will be set equal to threshold arrScale - use to change arrow scales nthArr - use to plot only every nth arrow from the array contourLevels - use to specify the maximum value (abs) of contour plots colbar - True/False wether to generate a colorbar or not logscale - if true then colorbar is on log scale aspectratio - set auto or equal for the plot's apearence colbar_orient - 'horizontal' or 'vertical' orientation of the colorbar (if colbar is True) Outputs: none Usage: graphics.quiver(data, arrScale = 0.2, threshold = Inf, n) """ data = dataset_to_array(data) x = data.x y = data.y u = data.u v = data.v if units is not None: lUnits = units[0] # ['m' 'm' 'mm/s' 'mm/s'] velUnits = units[2] tUnits = velUnits.split('/')[1] # make it 's' or 'dt' else: lUnits, velUnits, tUnits = '', '', '' if threshold is not None: data['u'] = xr.where(data['u']>threshold, threshold, data['u']) data['v'] = xr.where(data['v']>threshold, threshold, data['v']) S = np.array(np.sqrt(u**2 + v**2)) fig = plt.get_fignums() if len(fig) == 0: # if no figure is open fig, ax = plt.subplots() # open a new figure else: ax = plt.gca() if contourLevels is None: levels = np.linspace(0, np.max(S.flatten()), 30) # default contour levels up to max of S else: levels = np.linspace(0, contourLevels, 30) if logscale: c = ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap("Blues"), levels = levels, norm = plt.colors.LogNorm()) else: c = ax.contourf(x,y,S,alpha=0.8, cmap = plt.get_cmap("Blues"), levels=levels) if colbar: cbar = plt.colorbar(c, orientation=colbar_orient) cbar.set_label(r'$\left| \, V \, \right|$ ['+ lUnits +' $\cdot$ '+ tUnits +'$^{-1}$]') ax.quiver(x[::nthArr],y[::nthArr], u[::nthArr,::nthArr],v[::nthArr,::nthArr],units='width', scale = np.max(S*arrScale),headwidth=2) ax.set_xlabel('x (' + lUnits + ')') ax.set_ylabel('y (' + lUnits + ')') ax.set_aspect(aspectratio) return fig,ax def histogram(data, normed = False): """ this function will plot a normalized histogram of the velocity data. Input: data : xarray DataSet with ['u','v'] attrs['units'] normed : (optional) default is False to present normalized histogram """ u = np.asarray(data.u).flatten() v = np.asarray(data.v).flatten() units = data.attrs['units'] f,ax = plt.subplots(2) ax[0].hist(u,bins=np.int(np.sqrt(len(u))*0.5),density=normed) ax[0].set_xlabel('u ['+units[2]+']') ax[1] = plt.subplot2grid((2,1),(1,0)) ax[1].hist(v,bins=np.int(np.sqrt(len(v)*0.5)),density=normed) ax[1].set_xlabel('v ['+units[2]+']') plt.tight_layout() return f, ax def contour_plot(data, threshold = None, contourLevels = None, colbar = True, logscale = False, aspectration='equal', units=None): """ contourf ajusted for the xarray PIV dataset, creates a contour map for the data['w'] property. Input: data : xarray PIV DataArray, converted automatically using .isel(t=0) threshold : a threshold value, default is None (no data clipping) contourLevels : number of contour levels, default is None colbar : boolean (default is True) show/hide colorbar logscale : boolean (True is default) create in linear/log scale aspectration : string, 'equal' is the default """ data = dataset_to_array(data) if units is not None: lUnits = units[0] # ['m' 'm' 'mm/s' 'mm/s'] # velUnits = units[2] # tUnits = velUnits.split('/')[1] # make it 's' or 'dt' else: # lUnits, velUnits = '', '' lUnits = '' f,ax = plt.subplots() if threshold is not None: data['w'] = xr.where(data['w']>threshold, threshold, data['w']) m = np.amax(abs(data['w'])) if contourLevels == None: levels = np.linspace(-m, m, 30) else: levels = np.linspace(-contourLevels, contourLevels, 30) if logscale: c = ax.contourf(data.x,data.y,np.abs(data['w']), levels=levels, cmap = plt.get_cmap('RdYlBu'), norm=plt.colors.LogNorm()) else: c = ax.contourf(data.x,data.y,data['w'], levels=levels, cmap = plt.get_cmap('RdYlBu')) plt.xlabel('x [' + lUnits + ']') plt.ylabel('y [' + lUnits + ']') if colbar: cbar = plt.colorbar(c) cbar.set_label(r'$\omega$ [s$^{-1}$]') ax.set_aspect(aspectration) return f,ax def showf(data, variables=None, units=None, fig=None): """ showf(data, var, units) Arguments: data : xarray.DataSet that contains dimensions of t,x,y and variables u,v and maybe w (scalar) """ if variables is None: xlabel = ' ' ylabel = ' ' else: xlabel = variables[0] ylabel = variables[1] if units is not None: xlabel += ' ' + units[0] ylabel += ' ' + units[1] fig = plt.figure(None if fig is None else fig.number) for t in data['t']: d = data.isel(t=t) plt.quiver(d['x'],d['y'],d['u'],d['v'],d['u']**2 + d['v']**2) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.draw() plt.pause(0.1) plt.show() def showscal(data, property='ken'): """ showf(data, var, units) Arguments: data : xarray.DataSet that contains dimensions of t,x,y and a variable w (scalar) """ # fig = plt.figure(None if fig is None else fig.number) # import pdb; pdb.set_trace() # xlabel = (None if var is None else var[0]) + ' [' + (None if units is None else units[0])+']' # ylabel = (None if var is None else var[1]) + ' [' + (None if units is None else units[1])+']' data = data.piv.vec2scal(property=property) contour_plot(data) def animate(data, arrowscale=1, savepath=None): """ animates the quiver plot for the dataset (multiple frames) Input: data : xarray PIV type of DataSet arrowscale : [optional] integer, default is 1 savepath : [optional] path to save the MP4 animation, default is None Output: if savepath is None, then only an image display of the animation if savepath is an existing path, a file named im.mp4 is saved """ X, Y = data.x, data.y U, V = data.u[:,:,0], data.v[:,:,0] # first frame fig, ax = plt.subplots(1,1) M = np.sqrt(U**2 + V**2) Q = ax.quiver(X[::3,::3], Y[::3,::3], U[::3,::3], V[::3,::3], M[::3,::3], units='inches', scale=arrowscale) cb = plt.colorbar(Q) units = data.attrs['units'] cb.ax.set_ylabel('velocity (' + units[2] + ')') text = ax.text(0.2,1.05, '1/'+str(len(data.t)), ha='center', va='center', transform=ax.transAxes) anim = FuncAnimation(fig, update_quiver, fargs=(Q,data,text), frames = len(data.t), blit=False) mywriter = FFMpegWriter() if savepath: p = os.getcwd() os.chdir(savepath) anim.save('im.mp4', writer=mywriter) os.chdir(p) else: anim.save('im.mp4', writer=mywriter) def dataset_to_array(data,N=0): """ converts xarray Dataset to array """ if 't' in data.dims: print('Warning: function for a single frame, using first frame, supply data.isel(t=N)') data = data.isel(t=N) return data
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 40009, 21528, 198, 198, 37811, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, 198, 6738, 2603, 29487, ...
2.058153
4,213
# model settings norm_cfg = dict(type='BN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained='pretrain/vit_base_patch16_224.pth', backbone=dict( type='VisionTransformer', img_size=(224, 224), patch_size=16, in_channels=3, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4, # out_indices=(2, 5, 8, 11), qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.0, with_cls_token=True, norm_cfg=dict(type='LN', eps=1e-6), act_cfg=dict(type='GELU'), norm_eval=False, interpolate_mode='bicubic'), neck=None, decode_head=dict( type='ASPPHead', in_channels=768, # in_index=3, channels=512, dilations=(1, 6, 12, 18), dropout_ratio=0.1, num_classes=21, contrast=True, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), auxiliary_head=None, # model training and testing settings train_cfg=dict(), test_cfg=dict(mode='whole')) # yapf: disable
[ 2, 2746, 6460, 198, 27237, 62, 37581, 796, 8633, 7, 4906, 11639, 15766, 3256, 4433, 62, 9744, 28, 17821, 8, 198, 19849, 796, 8633, 7, 198, 220, 220, 220, 2099, 11639, 27195, 12342, 10707, 12342, 3256, 198, 220, 220, 220, 2181, 13363, ...
1.88785
642
#!/usr/bin/python # Copyright (c) 2019 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. # flake8: noqa: E501 from __future__ import absolute_import, division, print_function __metaclass__ = type import json from distutils.version import LooseVersion import yaml from ansible.module_utils.basic import AnsibleModule from ansible.module_utils._text import to_bytes, to_native ANSIBLE_METADATA = { 'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community' } DOCUMENTATION = """ module: podman_container author: - "Sagi Shnaidman (@sshnaidm)" version_added: '2.9' short_description: Manage podman containers notes: [] description: - Start, stop, restart and manage Podman containers requirements: - "Podman installed on host" options: name: description: - Name of the container required: True type: str executable: description: - Path to C(podman) executable if it is not in the C($PATH) on the machine running C(podman) default: 'podman' type: str state: description: - I(absent) - A container matching the specified name will be stopped and removed. - I(present) - Asserts the existence of a container matching the name and any provided configuration parameters. If no container matches the name, a container will be created. If a container matches the name but the provided configuration does not match, the container will be updated, if it can be. If it cannot be updated, it will be removed and re-created with the requested config. Image version will be taken into account when comparing configuration. Use the recreate option to force the re-creation of the matching container. - I(started) - Asserts there is a running container matching the name and any provided configuration. If no container matches the name, a container will be created and started. Use recreate to always re-create a matching container, even if it is running. Use force_restart to force a matching container to be stopped and restarted. - I(stopped) - Asserts that the container is first I(present), and then if the container is running moves it to a stopped state. type: str default: started choices: - absent - present - stopped - started image: description: - Repository path (or image name) and tag used to create the container. If an image is not found, the image will be pulled from the registry. If no tag is included, C(latest) will be used. - Can also be an image ID. If this is the case, the image is assumed to be available locally. type: str annotation: description: - Add an annotation to the container. The format is key value, multiple times. type: dict authfile: description: - Path of the authentication file. Default is ``${XDG_RUNTIME_DIR}/containers/auth.json`` (Not available for remote commands) You can also override the default path of the authentication file by setting the ``REGISTRY_AUTH_FILE`` environment variable. ``export REGISTRY_AUTH_FILE=path`` type: path blkio_weight: description: - Block IO weight (relative weight) accepts a weight value between 10 and 1000 type: int blkio_weight_device: description: - Block IO weight (relative device weight, format DEVICE_NAME[:]WEIGHT). type: dict cap_add: description: - List of capabilities to add to the container. type: list elements: str cap_drop: description: - List of capabilities to drop from the container. type: list elements: str cgroup_parent: description: - Path to cgroups under which the cgroup for the container will be created. If the path is not absolute, the path is considered to be relative to the cgroups path of the init process. Cgroups will be created if they do not already exist. type: path cgroupns: description: - Path to cgroups under which the cgroup for the container will be created. type: str cgroups: description: - Determines whether the container will create CGroups. Valid values are enabled and disabled, which the default being enabled. The disabled option will force the container to not create CGroups, and thus conflicts with CGroup options cgroupns and cgroup-parent. type: str choices: - default - disabled cidfile: description: - Write the container ID to the file type: path cmd_args: description: - Any additionl command options you want to pass to podman command, cmd_args - ['--other-param', 'value'] Be aware module doesn't support idempotency if this is set. type: list elements: str conmon_pidfile: description: - Write the pid of the conmon process to a file. conmon runs in a separate process than Podman, so this is necessary when using systemd to restart Podman containers. type: path command: description: - Override command of container. Can be a string or a list. type: raw cpu_period: description: - Limit the CPU real-time period in microseconds type: int cpu_rt_period: description: - Limit the CPU real-time period in microseconds. Limit the container's Real Time CPU usage. This flag tell the kernel to restrict the container's Real Time CPU usage to the period you specify. type: int cpu_rt_runtime: description: - Limit the CPU real-time runtime in microseconds. This flag tells the kernel to limit the amount of time in a given CPU period Real Time tasks may consume. type: int cpu_shares: description: - CPU shares (relative weight) type: int cpus: description: - Number of CPUs. The default is 0.0 which means no limit. type: str cpuset_cpus: description: - CPUs in which to allow execution (0-3, 0,1) type: str cpuset_mems: description: - Memory nodes (MEMs) in which to allow execution (0-3, 0,1). Only effective on NUMA systems. type: str detach: description: - Run container in detach mode type: bool default: True debug: description: - Return additional information which can be helpful for investigations. type: bool default: False detach_keys: description: - Override the key sequence for detaching a container. Format is a single character or ctrl-value type: str device: description: - Add a host device to the container. The format is <device-on-host>[:<device-on-container>][:<permissions>] (e.g. device /dev/sdc:/dev/xvdc:rwm) type: list elements: str device_read_bps: description: - Limit read rate (bytes per second) from a device (e.g. device-read-bps /dev/sda:1mb) type: list device_read_iops: description: - Limit read rate (IO per second) from a device (e.g. device-read-iops /dev/sda:1000) type: list device_write_bps: description: - Limit write rate (bytes per second) to a device (e.g. device-write-bps /dev/sda:1mb) type: list device_write_iops: description: - Limit write rate (IO per second) to a device (e.g. device-write-iops /dev/sda:1000) type: list dns: description: - Set custom DNS servers type: list elements: str dns_option: description: - Set custom DNS options type: str dns_search: description: - Set custom DNS search domains (Use dns_search with '' if you don't wish to set the search domain) type: str entrypoint: description: - Overwrite the default ENTRYPOINT of the image type: str env: description: - Set environment variables. This option allows you to specify arbitrary environment variables that are available for the process that will be launched inside of the container. type: dict env_file: description: - Read in a line delimited file of environment variables type: path env_host: description: - Use all current host environment variables in container. Defaults to false. type: bool etc_hosts: description: - Dict of host-to-IP mappings, where each host name is a key in the dictionary. Each host name will be added to the container's ``/etc/hosts`` file. type: dict aliases: - add_hosts expose: description: - Expose a port, or a range of ports (e.g. expose "3300-3310") to set up port redirection on the host system. type: list elements: str aliases: - exposed - exposed_ports force_restart: description: - Force restart of container. type: bool default: False aliases: - restart gidmap: description: - Run the container in a new user namespace using the supplied mapping. type: str group_add: description: - Add additional groups to run as type: list healthcheck: description: - Set or alter a healthcheck command for a container. type: str healthcheck_interval: description: - Set an interval for the healthchecks (a value of disable results in no automatic timer setup) (default "30s") type: str healthcheck_retries: description: - The number of retries allowed before a healthcheck is considered to be unhealthy. The default value is 3. type: int healthcheck_start_period: description: - The initialization time needed for a container to bootstrap. The value can be expressed in time format like 2m3s. The default value is 0s type: str healthcheck_timeout: description: - The maximum time allowed to complete the healthcheck before an interval is considered failed. Like start-period, the value can be expressed in a time format such as 1m22s. The default value is 30s type: str hostname: description: - Container host name. Sets the container host name that is available inside the container. type: str http_proxy: description: - By default proxy environment variables are passed into the container if set for the podman process. This can be disabled by setting the http_proxy option to false. The environment variables passed in include http_proxy, https_proxy, ftp_proxy, no_proxy, and also the upper case versions of those. Defaults to true type: bool image_volume: description: - Tells podman how to handle the builtin image volumes. The options are bind, tmpfs, or ignore (default bind) type: str choices: - 'bind' - 'tmpfs' - 'ignore' image_strict: description: - Whether to compare images in idempotency by taking into account a full name with registry and namespaces. type: bool default: False init: description: - Run an init inside the container that forwards signals and reaps processes. type: str init_path: description: - Path to the container-init binary. type: str interactive: description: - Keep STDIN open even if not attached. The default is false. When set to true, keep stdin open even if not attached. The default is false. type: bool ip: description: - Specify a static IP address for the container, for example '10.88.64.128'. Can only be used if no additional CNI networks to join were specified via 'network:', and if the container is not joining another container's network namespace via 'network container:<name|id>'. The address must be within the default CNI network's pool (default 10.88.0.0/16). type: str ipc: description: - Default is to create a private IPC namespace (POSIX SysV IPC) for the container type: str kernel_memory: description: - Kernel memory limit (format <number>[<unit>], where unit = b, k, m or g) Note - idempotency is supported for integers only. type: str label: description: - Add metadata to a container, pass dictionary of label names and values type: dict label_file: description: - Read in a line delimited file of labels type: str log_driver: description: - Logging driver. Used to set the log driver for the container. For example log_driver "k8s-file". type: str choices: - k8s-file - journald - json-file log_opt: description: - Logging driver specific options. Used to set the path to the container log file. For example log_opt "path=/var/log/container/mycontainer.json" type: str aliases: - log_options memory: description: - Memory limit (format 10k, where unit = b, k, m or g) Note - idempotency is supported for integers only. type: str memory_reservation: description: - Memory soft limit (format 100m, where unit = b, k, m or g) Note - idempotency is supported for integers only. type: str memory_swap: description: - A limit value equal to memory plus swap. Must be used with the -m (--memory) flag. The swap LIMIT should always be larger than -m (--memory) value. By default, the swap LIMIT will be set to double the value of --memory Note - idempotency is supported for integers only. type: str memory_swappiness: description: - Tune a container's memory swappiness behavior. Accepts an integer between 0 and 100. type: int mount: description: - Attach a filesystem mount to the container. bind or tmpfs For example mount "type=bind,source=/path/on/host,destination=/path/in/container" type: str network: description: - Set the Network mode for the container * bridge create a network stack on the default bridge * none no networking * container:<name|id> reuse another container's network stack * host use the podman host network stack. * <network-name>|<network-id> connect to a user-defined network * ns:<path> path to a network namespace to join * slirp4netns use slirp4netns to create a user network stack. This is the default for rootless containers type: list elements: str aliases: - net no_hosts: description: - Do not create /etc/hosts for the container Default is false. type: bool oom_kill_disable: description: - Whether to disable OOM Killer for the container or not. Default is false. type: bool oom_score_adj: description: - Tune the host's OOM preferences for containers (accepts -1000 to 1000) type: int pid: description: - Set the PID mode for the container type: str pids_limit: description: - Tune the container's pids limit. Set -1 to have unlimited pids for the container. type: str pod: description: - Run container in an existing pod. If you want podman to make the pod for you, preference the pod name with "new:" type: str privileged: description: - Give extended privileges to this container. The default is false. type: bool publish: description: - Publish a container's port, or range of ports, to the host. Format - ip:hostPort:containerPort | ip::containerPort | hostPort:containerPort | containerPort type: list elements: str aliases: - ports - published - published_ports publish_all: description: - Publish all exposed ports to random ports on the host interfaces. The default is false. type: bool read_only: description: - Mount the container's root filesystem as read only. Default is false type: bool read_only_tmpfs: description: - If container is running in --read-only mode, then mount a read-write tmpfs on /run, /tmp, and /var/tmp. The default is true type: bool recreate: description: - Use with present and started states to force the re-creation of an existing container. type: bool default: False restart_policy: description: - Restart policy to follow when containers exit. Restart policy will not take effect if a container is stopped via the podman kill or podman stop commands. Valid values are * no - Do not restart containers on exit * on-failure[:max_retries] - Restart containers when they exit with a non-0 exit code, retrying indefinitely or until the optional max_retries count is hit * always - Restart containers when they exit, regardless of status, retrying indefinitely type: str rm: description: - Automatically remove the container when it exits. The default is false. type: bool aliases: - remove rootfs: description: - If true, the first argument refers to an exploded container on the file system. The dafault is false. type: bool security_opt: description: - Security Options. For example security_opt "seccomp=unconfined" type: list elements: str shm_size: description: - Size of /dev/shm. The format is <number><unit>. number must be greater than 0. Unit is optional and can be b (bytes), k (kilobytes), m(megabytes), or g (gigabytes). If you omit the unit, the system uses bytes. If you omit the size entirely, the system uses 64m type: str sig_proxy: description: - Proxy signals sent to the podman run command to the container process. SIGCHLD, SIGSTOP, and SIGKILL are not proxied. The default is true. type: bool stop_signal: description: - Signal to stop a container. Default is SIGTERM. type: int stop_timeout: description: - Timeout (in seconds) to stop a container. Default is 10. type: int subgidname: description: - Run the container in a new user namespace using the map with 'name' in the /etc/subgid file. type: str subuidname: description: - Run the container in a new user namespace using the map with 'name' in the /etc/subuid file. type: str sysctl: description: - Configure namespaced kernel parameters at runtime type: dict systemd: description: - Run container in systemd mode. The default is true. type: bool tmpfs: description: - Create a tmpfs mount. For example tmpfs "/tmp" "rw,size=787448k,mode=1777" type: dict tty: description: - Allocate a pseudo-TTY. The default is false. type: bool uidmap: description: - Run the container in a new user namespace using the supplied mapping. type: list ulimit: description: - Ulimit options type: list user: description: - Sets the username or UID used and optionally the groupname or GID for the specified command. type: str userns: description: - Set the user namespace mode for the container. It defaults to the PODMAN_USERNS environment variable. An empty value means user namespaces are disabled. type: str uts: description: - Set the UTS mode for the container type: str volume: description: - Create a bind mount. If you specify, volume /HOST-DIR:/CONTAINER-DIR, podman bind mounts /HOST-DIR in the host to /CONTAINER-DIR in the podman container. type: list elements: str aliases: - volumes volumes_from: description: - Mount volumes from the specified container(s). type: list elements: str workdir: description: - Working directory inside the container. The default working directory for running binaries within a container is the root directory (/). type: str """ EXAMPLES = """ - name: Run container podman_container: name: container image: quay.io/bitnami/wildfly state: started - name: Create a data container podman_container: name: mydata image: busybox volume: - /tmp/data - name: Re-create a redis container podman_container: name: myredis image: redis command: redis-server --appendonly yes state: present recreate: yes expose: - 6379 volumes_from: - mydata - name: Restart a container podman_container: name: myapplication image: redis state: started restart: yes etc_hosts: other: "127.0.0.1" restart_policy: "no" device: "/dev/sda:/dev/xvda:rwm" ports: - "8080:9000" - "127.0.0.1:8081:9001/udp" env: SECRET_KEY: "ssssh" BOOLEAN_KEY: "yes" - name: Container present podman_container: name: mycontainer state: present image: ubuntu:14.04 command: "sleep 1d" - name: Stop a container podman_container: name: mycontainer state: stopped - name: Start 4 load-balanced containers podman_container: name: "container{{ item }}" recreate: yes image: someuser/anotherappimage command: sleep 1d with_sequence: count=4 - name: remove container podman_container: name: ohno state: absent - name: Writing output podman_container: name: myservice image: busybox log_options: path=/var/log/container/mycontainer.json log_driver: k8s-file """ RETURN = """ container: description: - Facts representing the current state of the container. Matches the podman inspection output. - Note that facts are part of the registered vars since Ansible 2.8. For compatibility reasons, the facts are also accessible directly as C(podman_container). Note that the returned fact will be removed in Ansible 2.12. - Empty if C(state) is I(absent). returned: always type: dict sample: '{ "AppArmorProfile": "", "Args": [ "sh" ], "BoundingCaps": [ "CAP_CHOWN", ... ], "Config": { "Annotations": { "io.kubernetes.cri-o.ContainerType": "sandbox", "io.kubernetes.cri-o.TTY": "false" }, "AttachStderr": false, "AttachStdin": false, "AttachStdout": false, "Cmd": [ "sh" ], "Domainname": "", "Entrypoint": "", "Env": [ "PATH=/usr/sbin:/usr/bin:/sbin:/bin", "TERM=xterm", "HOSTNAME=", "container=podman" ], "Hostname": "", "Image": "docker.io/library/busybox:latest", "Labels": null, "OpenStdin": false, "StdinOnce": false, "StopSignal": 15, "Tty": false, "User": { "gid": 0, "uid": 0 }, "Volumes": null, "WorkingDir": "/" }, "ConmonPidFile": "...", "Created": "2019-06-17T19:13:09.873858307+03:00", "Dependencies": [], "Driver": "overlay", "EffectiveCaps": [ "CAP_CHOWN", ... ], "ExecIDs": [], "ExitCommand": [ "/usr/bin/podman", "--root", ... ], "GraphDriver": { ... }, "HostConfig": { ... }, "HostnamePath": "...", "HostsPath": "...", "ID": "...", "Image": "...", "ImageName": "docker.io/library/busybox:latest", "IsInfra": false, "LogPath": "/tmp/container/mycontainer.json", "MountLabel": "system_u:object_r:container_file_t:s0:c282,c782", "Mounts": [ ... ], "Name": "myservice", "Namespace": "", "NetworkSettings": { "Bridge": "", ... }, "Path": "sh", "ProcessLabel": "system_u:system_r:container_t:s0:c282,c782", "ResolvConfPath": "...", "RestartCount": 0, "Rootfs": "", "State": { "Dead": false, "Error": "", "ExitCode": 0, "FinishedAt": "2019-06-17T19:13:10.157518963+03:00", "Healthcheck": { "FailingStreak": 0, "Log": null, "Status": "" }, "OOMKilled": false, "OciVersion": "1.0.1-dev", "Paused": false, "Pid": 4083, "Restarting": false, "Running": false, "StartedAt": "2019-06-17T19:13:10.152479729+03:00", "Status": "exited" }, "StaticDir": "..." ... }' """ def ensure_image_exists(module, image): """If image is passed, ensure it exists, if not - pull it or fail. Arguments: module {obj} -- ansible module object image {str} -- name of image Returns: list -- list of image actions - if it pulled or nothing was done """ image_actions = [] module_exec = module.params['executable'] if not image: return image_actions rc, out, err = module.run_command([module_exec, 'image', 'exists', image]) if rc == 0: return image_actions rc, out, err = module.run_command([module_exec, 'image', 'pull', image]) if rc != 0: module.fail_json(msg="Can't pull image %s" % image, stdout=out, stderr=err) image_actions.append("pulled image %s" % image) return image_actions def _perform_action(self, action): """Perform action with container. Arguments: action {str} -- action to perform - start, create, stop, run, delete """ b_command = PodmanModuleParams(action, self.module.params, self.version, self.module, ).construct_command_from_params() full_cmd = " ".join([self.module.params['executable']] + [to_native(i) for i in b_command]) self.module.log("PODMAN-CONTAINER-DEBUG: %s" % full_cmd) self.actions.append(full_cmd) if not self.module.check_mode: rc, out, err = self.module.run_command( [self.module.params['executable'], b'container'] + b_command, expand_user_and_vars=False) self.stdout = out self.stderr = err if rc != 0: self.module.fail_json( msg="Can't %s container %s" % (action, self.name), stdout=out, stderr=err) def run(self): """Run the container.""" self._perform_action('run') def delete(self): """Delete the container.""" self._perform_action('delete') def stop(self): """Stop the container.""" self._perform_action('stop') def start(self): """Start the container.""" self._perform_action('start') def create(self): """Create the container.""" self._perform_action('create') def recreate(self): """Recreate the container.""" self.delete() self.run() def restart(self): """Restart the container.""" self.stop() self.run() class PodmanManager: """Module manager class. Defines according to parameters what actions should be applied to container """ def __init__(self, module): """Initialize PodmanManager class. Arguments: module {obj} -- ansible module object """ super(PodmanManager, self).__init__() self.module = module self.results = { 'changed': False, 'actions': [], 'container': {}, } self.name = self.module.params['name'] self.executable = \ self.module.get_bin_path(self.module.params['executable'], required=True) self.image = self.module.params['image'] image_actions = ensure_image_exists(self.module, self.image) self.results['actions'] += image_actions self.state = self.module.params['state'] self.restart = self.module.params['force_restart'] self.recreate = self.module.params['recreate'] self.container = PodmanContainer(self.module, self.name) def update_container_result(self, changed=True): """Inspect the current container, update results with last info, exit. Keyword Arguments: changed {bool} -- whether any action was performed (default: {True}) """ facts = self.container.get_info() if changed else self.container.info out, err = self.container.stdout, self.container.stderr self.results.update({'changed': changed, 'container': facts, 'podman_actions': self.container.actions}, stdout=out, stderr=err) if self.container.diff: self.results.update({'diff': self.container.diff}) if self.module.params['debug']: self.results.update({'podman_version': self.container.version}) self.module.exit_json(**self.results) def make_started(self): """Run actions if desired state is 'started'.""" if self.container.running and \ (self.container.different or self.recreate): self.container.recreate() self.results['actions'].append('recreated %s' % self.container.name) self.update_container_result() elif self.container.running and not self.container.different: if self.restart: self.container.restart() self.results['actions'].append('restarted %s' % self.container.name) self.update_container_result() self.update_container_result(changed=False) elif not self.container.exists: self.container.run() self.results['actions'].append('started %s' % self.container.name) self.update_container_result() elif self.container.stopped and self.container.different: self.container.recreate() self.results['actions'].append('recreated %s' % self.container.name) self.update_container_result() elif self.container.stopped and not self.container.different: self.container.start() self.results['actions'].append('started %s' % self.container.name) self.update_container_result() def make_stopped(self): """Run actions if desired state is 'stopped'.""" if not self.container.exists and not self.image: self.module.fail_json(msg='Cannot create container when image' ' is not specified!') if not self.container.exists: self.container.create() self.results['actions'].append('created %s' % self.container.name) self.update_container_result() if self.container.stopped: self.update_container_result(changed=False) elif self.container.running: self.container.stop() self.results['actions'].append('stopped %s' % self.container.name) self.update_container_result() def make_absent(self): """Run actions if desired state is 'absent'.""" if not self.container.exists: self.results.update({'changed': False}) elif self.container.exists: self.container.delete() self.results['actions'].append('deleted %s' % self.container.name) self.results.update({'changed': True}) self.results.update({'container': {}, 'podman_actions': self.container.actions}) self.module.exit_json(**self.results) def execute(self): """Execute the desired action according to map of actions & states.""" states_map = { 'present': self.make_started, 'started': self.make_started, 'absent': self.make_absent, 'stopped': self.make_stopped } process_action = states_map[self.state] process_action() self.module.fail_json(msg="Unexpected logic error happened, " "please contact maintainers ASAP!") if __name__ == '__main__': main()
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 15069, 357, 66, 8, 13130, 4946, 25896, 5693, 198, 2, 1439, 6923, 33876, 13, 198, 2, 198, 2, 220, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156,...
2.438889
13,860
#!/usr/bin/env python from setuptools import setup # Modified from http://stackoverflow.com/questions/2058802/ # how-can-i-get-the-version-defined-in-setup-py-setuptools-in-my-package # Explicitly list bin scripts to be installed, seeing as I have a few local # bin files that are not (yet) part of the distribution. scripts = [ 'bin/aa-info.py', 'bin/aa-to-dna.py', 'bin/aa-to-properties.py', 'bin/adaptor-distances.py', 'bin/alignment-panel-civ.py', 'bin/alignments-per-read.py', 'bin/bit-score-to-e-value.py', 'bin/cat-json-blast-records.py', 'bin/check-fasta-json-blast-consistency.py', 'bin/codon-distance.py', 'bin/compare-consensuses.py', 'bin/compare-sequences.py', 'bin/convert-blast-xml-to-json.py', 'bin/convert-diamond-to-json.py', 'bin/convert-diamond-to-sam.py', 'bin/convert-sam-to-fastq.sh', 'bin/create-newick-relabeling-output.py', 'bin/dark-matter-version.py', 'bin/describe-protein-database.py', 'bin/dna-to-aa.py', 'bin/download-genbank.sh', 'bin/e-value-to-bit-score.py', 'bin/extract-ORFs.py', 'bin/fasta-base-indices.py', 'bin/fasta-count.py', 'bin/fasta-diff.sh', 'bin/fasta-identity-table.py', 'bin/fasta-ids.py', 'bin/fasta-join.py', 'bin/fasta-lengths.py', 'bin/fasta-sequences.py', 'bin/fasta-sort.py', 'bin/fasta-split-by-id.py', 'bin/fasta-subset.py', 'bin/fasta-subtraction.py', 'bin/fasta-to-phylip.py', 'bin/fasta-variable-sites.py', 'bin/filter-fasta-by-complexity.py', 'bin/filter-fasta-by-taxonomy.py', 'bin/filter-fasta.py', 'bin/filter-hits-to-fasta.py', 'bin/filter-reads-alignments.py', 'bin/filter-sam.py', 'bin/find-hits.py', 'bin/format-fasta.py', 'bin/genome-protein-summary.py', 'bin/get-features.py', 'bin/get-hosts.py', 'bin/get-reads.py', 'bin/get-taxonomy.py', 'bin/graph-evalues.py', 'bin/local-align.py', 'bin/make-consensus.py', 'bin/make-fasta-database.py', 'bin/make-protein-database.py', 'bin/ncbi-fetch-id.py', 'bin/newick-to-ascii.py', 'bin/noninteractive-alignment-panel.py', 'bin/parse-genbank-flat-file.py', 'bin/position-summary.py', 'bin/pre-commit.sh', 'bin/print-blast-xml-for-derek.py', 'bin/print-blast-xml.py', 'bin/print-read-lengths.py', 'bin/proteins-to-pathogens.py', 'bin/proteins-to-pathogens-civ.py', 'bin/randomize-fasta.py', 'bin/read-blast-json.py', 'bin/read-blast-xml.py', 'bin/relabel-newick-tree.py', 'bin/run-bwa.py', 'bin/run-bowtie2.py', 'bin/sam-coverage.py', 'bin/sam-coverage-depth.py', 'bin/sam-to-fasta-alignment.py', 'bin/sam-reference-read-counts.py', 'bin/sam-references.py', 'bin/sff-to-fastq.py', 'bin/split-fasta-by-adaptors.py', 'bin/subset-protein-database.py', 'bin/summarize-fasta-bases.py', 'bin/summarize-reads.py', 'bin/trim-primers.py', 'bin/trim-reads.py', 'bin/write-htcondor-job-spec.py', ] setup(name='dark-matter', version=version(), packages=['dark', 'dark.blast', 'dark.diamond', 'dark.civ'], url='https://github.com/acorg/dark-matter', download_url='https://github.com/acorg/dark-matter', author='Terry Jones, Barbara Muehlemann, Tali Veith, Sophie Mathias', author_email='tcj25@cam.ac.uk', keywords=['virus discovery'], classifiers=[ 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Development Status :: 4 - Beta', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Topic :: Software Development :: Libraries :: Python Modules', ], license='MIT', description='Python classes for working with genetic sequence data', scripts=scripts, install_requires=[ 'biopython>=1.71', 'bz2file>=0.98', 'Cython>=0.29.16', 'ipython>=3.1.0', 'matplotlib>=1.4.3', 'mysql-connector-python==8.0.11', 'numpy>=1.14.2', 'pysam>=0.15.2', 'pyfaidx>=0.4.8.4', 'pyzmq>=14.3.1', 'requests>=2.18.4', 'cachetools>=3.1.0', 'simplejson>=3.5.3', 'six>=1.11.0', ])
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 628, 198, 2, 40499, 422, 2638, 1378, 25558, 2502, 11125, 13, 785, 14, 6138, 507, 14, 1238, 3365, 30863, 14, 198, 2, 703, 12, 5171, 12, 72, ...
2.044797
2,143
# ====================================================================================================================== # Fakulta informacnich technologii VUT v Brne # Bachelor thesis # Author: Filip Bali (xbalif00) # License: MIT # ====================================================================================================================== from django import template import datetime import time from portfolioApp.models import NotificationEvent register = template.Library() import pandas as pd register.filter(print_timestamp) register.filter(print_timestamp_analysis) register.filter(print_timestamp_notifications) register.filter(print_notification_text) register.filter(print_symbol_notifications) register.filter(print_type_notifications)
[ 2, 38093, 10052, 4770, 1421, 28, 198, 2, 376, 461, 586, 64, 4175, 330, 77, 488, 1579, 928, 4178, 569, 3843, 410, 1709, 710, 198, 2, 33399, 21554, 198, 2, 6434, 25, 24600, 347, 7344, 357, 87, 6893, 361, 405, 8, 198, 2, 13789, 25,...
4.612121
165
from pycfmodel.model.resources.properties.policy_document import PolicyDocument from pycfmodel.model.resources.properties.property import Property from pycfmodel.model.types import Resolvable, ResolvableStr
[ 6738, 12972, 12993, 19849, 13, 19849, 13, 37540, 13, 48310, 13, 30586, 62, 22897, 1330, 7820, 24941, 198, 6738, 12972, 12993, 19849, 13, 19849, 13, 37540, 13, 48310, 13, 26745, 1330, 14161, 198, 6738, 12972, 12993, 19849, 13, 19849, 13, ...
4.078431
51
from .stacking import StackingClassifier, stack_features from .multitask import MultiTaskEstimator
[ 6738, 764, 301, 5430, 1330, 520, 5430, 9487, 7483, 11, 8931, 62, 40890, 198, 6738, 764, 16680, 270, 2093, 1330, 15237, 25714, 22362, 320, 1352, 198 ]
3.807692
26
# Copyright (C) 2019 Intel Corporation. All rights reserved. # SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES") load( "@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl", "feature", "flag_group", "flag_set", "tool_path", ) all_compile_actions = [ ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ] all_link_actions = [ ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library, ] emsdk_toolchain_config = rule( implementation = _impl, attrs = {}, provides = [CcToolchainConfigInfo], )
[ 2, 15069, 357, 34, 8, 13130, 8180, 10501, 13, 1439, 2489, 10395, 13, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 13315, 27140, 15996, 12, 1069, 4516, 198, 198, 2220, 7203, 31, 65, 41319, 62, 31391, 10...
2.437276
279
from __future__ import print_function import json from typing import List from functools import lru_cache from cloud_storages.http_shortcuts import * from database.database import Database from models.models import StorageMetaInfo, Resource, Size from cloud_storages.storage import Storage from cloud_storages.gdrive.client_config import GOOGLE_DRIVE_CONFIG, SCOPES from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials GOOGLE_DRIVE_DB_KEY = 'google' def create_path(self, remote_path: List[str]) -> None: """ Creates the remote path on yandex disk """ print(f'[{__name__}] Trying to create directory {"/".join(remote_path)} on remote...') dir_to_create = [] for dir in remote_path: dir_to_create.append(dir) path_to_create = '/'.join(dir_to_create) response = put_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={path_to_create}', token=self.token) if 199 < response.status_code < 401: print(f'[{__name__}] Created directory {path_to_create}') continue elif response.status_code == 409 and ' ' in response.json().get('message', ''): continue return def save_resource_to_path(self, resource: Resource, remote_path: str, overwrite: bool, _rec_call:bool = False) -> Resource or None: """ Put an Item to the directory :param resource: resource on the local fs :param remote_path: string, path to resource on remote fs :param _rec_call: bool, a system parameter, whether or not this function was called as a recursive call :return: saved resource or raises exception """ upload_successful_flag = False response = get_with_OAuth( f'https://cloud-api.yandex.net/v1/disk/resources/upload?path={remote_path}&overwrite=${overwrite}', token=self.token ) if response.status_code == 200: response_read = response.json() upload_link = response_read['href'] with open(resource.path, 'rb') as f: files = f response = put_with_OAuth(upload_link, data=files) if 199 < response.status_code < 401: upload_successful_flag = True response = get_with_OAuth(f'https://cloud-api.yandex.net/v1/disk/resources?path={remote_path}', token=self.token) resource_metainfo = self._deserialize_resource(response.json()) if 199 < response.status_code < 401: return resource_metainfo elif upload_successful_flag: return resource # This dir is not present in the storage # We use _rec_call to tell that the next call was made as recursive call, so we don't cause SO elif response.status_code == 409 and not _rec_call: # We don't need to create a folder with the name equal to the filename, so we do [:-1] self.create_path(remote_path.split('/')[:-1]) return self.save_resource_to_path(resource, remote_path, overwrite, _rec_call=True) raise ValueError(f"Something went wrong with YD: Response: " f"{str(response.status_code)} {response.json().get('message', '')}") def main(): storage = GDriveStorage(None) db = Database('../storage.db') storage.auth(db) authed_storage = GDriveStorage(json.loads(db.get(GOOGLE_DRIVE_DB_KEY))['token']) result = authed_storage.list_resources_on_path('savezone') print(result) if __name__ == '__main__': main()
[ 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 198, 11748, 33918, 198, 6738, 19720, 1330, 7343, 198, 6738, 1257, 310, 10141, 1330, 300, 622, 62, 23870, 198, 198, 6738, 6279, 62, 301, 273, 1095, 13, 4023, 62, 19509, 23779, 1330, 1...
2.361214
1,614
from django.urls import re_path, include from . import views app_name='logged' # url mappings for the webapp. urlpatterns = [ re_path(r'^$', views.logged_count, name="logged_count"), re_path(r'^loggedusers/', views.logged, name="logged_users"), re_path(r'^settings/', views.user_settings, name="update_info"), re_path(r'^administrators/', views.post_alert, name="post_alert"), re_path(r'^alerts/$', views.list_alert, name="list_alert"), re_path(r'^alerts/(?P<slug>[\w-]+)/$', views.view_alert, name="view_alert"), re_path(r'^display/', views.display, name="display"), re_path(r'^doorselection/', views.doors_election, name="door_selecttion") ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 302, 62, 6978, 11, 2291, 198, 6738, 764, 1330, 5009, 198, 198, 1324, 62, 3672, 11639, 6404, 2004, 6, 198, 198, 2, 19016, 285, 39242, 329, 262, 3992, 1324, 13, 198, 6371, 33279, 82, 796, 685, ...
2.516729
269
# Copyright 2021 UW-IT, University of Washington # SPDX-License-Identifier: Apache-2.0 from scout.dao.space import get_spots_by_filter, _get_spot_filters, \ _get_extended_info_by_key import copy
[ 2, 15069, 33448, 33436, 12, 2043, 11, 2059, 286, 2669, 198, 2, 30628, 55, 12, 34156, 12, 33234, 7483, 25, 24843, 12, 17, 13, 15, 198, 198, 6738, 24490, 13, 67, 5488, 13, 13200, 1330, 651, 62, 2777, 1747, 62, 1525, 62, 24455, 11, ...
2.77027
74
#Scraper for Minnesota Court of Appeals Published Opinions #CourtID: minnctapp #Court Short Name: MN #Author: mlr #Date: 2016-06-03 from juriscraper.opinions.united_states.state import minn
[ 2, 3351, 38545, 329, 8919, 3078, 286, 20172, 26372, 8670, 259, 507, 198, 2, 36699, 2389, 25, 949, 77, 310, 1324, 198, 2, 36699, 10073, 6530, 25, 29060, 198, 2, 13838, 25, 285, 14050, 198, 2, 10430, 25, 1584, 12, 3312, 12, 3070, 62...
3.063492
63
from __future__ import absolute_import import os import errno from contextlib import contextmanager __author__ = 'Shyue Ping Ong' __copyright__ = 'Copyright 2013, The Materials Project' __version__ = '0.1' __maintainer__ = 'Shyue Ping Ong' __email__ = 'ongsp@ucsd.edu' __date__ = '1/24/14' def makedirs_p(path, **kwargs): """ Wrapper for os.makedirs that does not raise an exception if the directory already exists, in the fashion of "mkdir -p" command. The check is performed in a thread-safe way Args: path: path of the directory to create kwargs: standard kwargs for os.makedirs """ try: os.makedirs(path, **kwargs) except OSError as exc: if exc.errno == errno.EEXIST and os.path.isdir(path): pass else: raise
[ 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 198, 11748, 28686, 198, 11748, 11454, 3919, 198, 198, 6738, 4732, 8019, 1330, 4732, 37153, 198, 198, 834, 9800, 834, 796, 705, 2484, 88, 518, 34263, 48041, 6, 198, 834, 22163, 4766, ...
2.490798
326
import sys REQUIRED_PYTHON = "python3" required_major = 3 if __name__ == '__main__': main()
[ 11748, 25064, 198, 198, 2200, 10917, 37819, 62, 47, 56, 4221, 1340, 796, 366, 29412, 18, 1, 198, 35827, 62, 22478, 796, 513, 628, 628, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 220, 220, 1388, 3419, 19...
2.348837
43