content
stringlengths
1
1.05M
input_ids
listlengths
1
883k
ratio_char_token
float64
1
22.9
token_count
int64
1
883k
###################################################################################################################### # Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # # # Licensed under the Apache License Version 2.0 (the "License"). You may not use this file except in compliance # # with the License. A copy of the License is located at # # # # http://www.apache.org/licenses/ # # # # or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES # # OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions # # and limitations under the License. # ###################################################################################################################### import json import sys from collections import OrderedDict main(template_file=sys.argv[1], bucket=sys.argv[2], solution=sys.argv[3], version=sys.argv[4], region=sys.argv[5]) exit(0)
[ 29113, 29113, 29113, 14468, 4242, 2235, 198, 2, 220, 15069, 13130, 6186, 13, 785, 11, 3457, 13, 393, 663, 29116, 13, 1439, 6923, 33876, 13, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, 220, ...
1.886814
857
############################################################################### # file -- parse.py -- # Top contributors (to current version): # Nestan Tsiskaridze # This file is part of the configuration finder for the Stanford AHA project. # Copyright (c) 2021 by the authors listed in the file AUTHORS # in the top-level source directory) and their institutional affiliations. # All rights reserved. See the file LICENSE in the top-level source # directory for licensing information. # # Handles parsing of all input files. ############################################################################### import smt_switch as ss import smt_switch.primops as po import smt_switch.sortkinds as sk import argparse import pono as c import sys import re import time import copy import io #import timeit
[ 29113, 29113, 7804, 4242, 21017, 198, 2, 220, 2393, 1377, 21136, 13, 9078, 1377, 198, 2, 220, 5849, 20420, 357, 1462, 1459, 2196, 2599, 198, 2, 220, 220, 220, 21420, 272, 13146, 1984, 283, 312, 2736, 198, 2, 220, 770, 2393, 318, 636...
3.873832
214
from flask import Blueprint, render_template, redirect, url_for, request, flash, make_response from werkzeug.security import generate_password_hash from flask_login import login_required, current_user from . import db import datetime from .models import Visitor, User main = Blueprint('main', __name__)
[ 6738, 42903, 1330, 39932, 11, 8543, 62, 28243, 11, 18941, 11, 19016, 62, 1640, 11, 2581, 11, 7644, 11, 787, 62, 26209, 198, 6738, 266, 9587, 2736, 1018, 13, 12961, 1330, 7716, 62, 28712, 62, 17831, 198, 6738, 42903, 62, 38235, 1330, ...
3.8125
80
# Funes cabecalho = "SISTEMA DE CADASTRO DE FUNCIONARIO\n\n\n" rodape = "\n\n\n Obrigada pela preferencia"
[ 2, 376, 4015, 198, 198, 66, 397, 721, 282, 8873, 796, 366, 50, 8808, 27630, 5550, 37292, 1921, 5446, 46, 5550, 29397, 34, 2849, 1503, 9399, 59, 77, 59, 77, 59, 77, 1, 198, 198, 14892, 1758, 796, 37082, 77, 59, 77, 59, 77, 440, ...
1.963636
55
from node import Node
[ 6738, 10139, 1330, 19081, 201, 198, 201, 198, 197, 197, 201, 198, 201, 198, 201, 198 ]
2.0625
16
#!/usr/bin/env python3 # # Copyright (C) 2018 Linus Jahn <lnj@kaidan.im> # Copyright (C) 2019,2020 Hiroshi Miura <miurahr@linux.com> # Copyright (C) 2020, Aurlien Gteau # # 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. import concurrent.futures import os import pathlib import subprocess import sys import time from logging import getLogger import py7zr import requests from requests.adapters import HTTPAdapter from urllib3.util.retry import Retry from aqt.archives import QtPackage from aqt.helper import altlink, versiontuple from aqt.qtpatch import Updater from aqt.settings import Settings
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 2, 198, 2, 15069, 357, 34, 8, 2864, 5164, 385, 449, 15386, 1279, 18755, 73, 31, 74, 1698, 272, 13, 320, 29, 198, 2, 15069, 357, 34, 8, 13130, 11, 42334, 35763, 72, 13756, 533...
3.57461
449
from django.template import loader, RequestContext from django.http import Http404, HttpResponse from django.core.xheaders import populate_xheaders from django.core.paginator import ObjectPaginator, InvalidPage from django.core.exceptions import ObjectDoesNotExist def object_list(request, queryset, paginate_by=None, page=None, allow_empty=False, template_name=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): """ Generic list of objects. Templates: ``<app_label>/<model_name>_list.html`` Context: object_list list of objects is_paginated are the results paginated? results_per_page number of objects per page (if paginated) has_next is there a next page? has_previous is there a prev page? page the current page next the next page previous the previous page pages number of pages, total hits number of objects, total last_on_page the result number of the last of object in the object_list (1-indexed) first_on_page the result number of the first object in the object_list (1-indexed) """ if extra_context is None: extra_context = {} queryset = queryset._clone() if paginate_by: paginator = ObjectPaginator(queryset, paginate_by) if not page: page = request.GET.get('page', 1) try: page = int(page) object_list = paginator.get_page(page - 1) except (InvalidPage, ValueError): if page == 1 and allow_empty: object_list = [] else: raise Http404 c = RequestContext(request, { '%s_list' % template_object_name: object_list, 'is_paginated': paginator.pages > 1, 'results_per_page': paginate_by, 'has_next': paginator.has_next_page(page - 1), 'has_previous': paginator.has_previous_page(page - 1), 'page': page, 'next': page + 1, 'previous': page - 1, 'last_on_page': paginator.last_on_page(page - 1), 'first_on_page': paginator.first_on_page(page - 1), 'pages': paginator.pages, 'hits' : paginator.hits, }, context_processors) else: c = RequestContext(request, { '%s_list' % template_object_name: queryset, 'is_paginated': False }, context_processors) if not allow_empty and len(queryset) == 0: raise Http404 for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value if not template_name: model = queryset.model template_name = "%s/%s_list.html" % (model._meta.app_label, model._meta.object_name.lower()) t = template_loader.get_template(template_name) return HttpResponse(t.render(c), mimetype=mimetype) def object_detail(request, queryset, object_id=None, slug=None, slug_field=None, template_name=None, template_name_field=None, template_loader=loader, extra_context=None, context_processors=None, template_object_name='object', mimetype=None): """ Generic detail of an object. Templates: ``<app_label>/<model_name>_detail.html`` Context: object the object """ if extra_context is None: extra_context = {} model = queryset.model if object_id: queryset = queryset.filter(pk=object_id) elif slug and slug_field: queryset = queryset.filter(**{slug_field: slug}) else: raise AttributeError, "Generic detail view must be called with either an object_id or a slug/slug_field." try: obj = queryset.get() except ObjectDoesNotExist: raise Http404, "No %s found matching the query" % (model._meta.verbose_name) if not template_name: template_name = "%s/%s_detail.html" % (model._meta.app_label, model._meta.object_name.lower()) if template_name_field: template_name_list = [getattr(obj, template_name_field), template_name] t = template_loader.select_template(template_name_list) else: t = template_loader.get_template(template_name) c = RequestContext(request, { template_object_name: obj, }, context_processors) for key, value in extra_context.items(): if callable(value): c[key] = value() else: c[key] = value response = HttpResponse(t.render(c), mimetype=mimetype) populate_xheaders(request, response, model, getattr(obj, obj._meta.pk.name)) return response
[ 6738, 42625, 14208, 13, 28243, 1330, 40213, 11, 19390, 21947, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 26429, 11, 367, 29281, 31077, 198, 6738, 42625, 14208, 13, 7295, 13, 87, 50145, 1330, 48040, 62, 87, 50145, 198, 6738, 42...
2.213376
2,198
"""Utility Modules.""" from typing import Any, Callable, Dict, List, Optional, Sequence, TypeVar, Union import jax import jax.numpy as jnp from .module import Module, parameters_method T = TypeVar("T", bound=Module) O = TypeVar("O")
[ 37811, 18274, 879, 3401, 5028, 526, 15931, 628, 198, 6738, 19720, 1330, 4377, 11, 4889, 540, 11, 360, 713, 11, 7343, 11, 32233, 11, 45835, 11, 5994, 19852, 11, 4479, 198, 198, 11748, 474, 897, 198, 11748, 474, 897, 13, 77, 32152, 35...
3.0375
80
""" Backend to connect Open edX richie with an LMS """ import logging import re import requests from requests.auth import AuthBase from ..serializers import SyncCourseRunSerializer from .base import BaseLMSBackend logger = logging.getLogger(__name__) def split_course_key(key): """Split an OpenEdX course key by organization, course and course run codes. We first try splitting the key as a version 1 key (course-v1:org+course+run) and fallback the old version (org/course/run). """ if key.startswith("course-v1:"): organization, course, run = key[10:].split("+") else: organization, course, run = key.split("/") return organization, course, run
[ 37811, 198, 7282, 437, 284, 2018, 4946, 1225, 55, 5527, 494, 351, 281, 406, 5653, 198, 37811, 198, 11748, 18931, 198, 11748, 302, 198, 198, 11748, 7007, 198, 6738, 7007, 13, 18439, 1330, 26828, 14881, 198, 198, 6738, 11485, 46911, 11341...
3.030303
231
# by Greg Hazel import xmlrpclib from xmlrpclib2 import * from BTL import brpc old_PyCurlTransport = PyCurlTransport # -------------------------------------------------------------------- # request dispatcher # Double underscore is BAD! def new_server_proxy(url): c = cache_set.get_cache(PyCURL_Cache, url) t = PyCurlTransport(c) return BRPC_ServerProxy(url, transport=t) ServerProxy = new_server_proxy if __name__ == '__main__': s = ServerProxy('https://greg.mitte.bittorrent.com:7080/') ping(0, 1, 1, name="potato") ping(0, 1, 1, name="anime") ping("phish", 0, 1, 1) ping("games", 0, 1, 1)
[ 2, 416, 8547, 42805, 198, 198, 11748, 35555, 81, 79, 565, 571, 198, 6738, 35555, 81, 79, 565, 571, 17, 1330, 1635, 198, 6738, 347, 14990, 1330, 865, 14751, 198, 198, 727, 62, 20519, 34, 6371, 8291, 634, 796, 9485, 34, 6371, 8291, ...
2.59919
247
import base64 import mimetypes import os from django.conf import settings from django.http import Http404, HttpResponse from django.shortcuts import get_object_or_404 from django.views.decorators.cache import cache_control from django.views.static import serve as django_serve from database_files.models import File def serve_mixed(request, *args, **kwargs): """ First attempts to serve the file from the filesystem, then tries the database. """ name = kwargs.get('name') or kwargs.get('path') document_root = kwargs.get('document_root') document_root = document_root or settings.MEDIA_ROOT try: # First attempt to serve from filesystem. return django_serve(request, name, document_root) except Http404: # Then try serving from database. return serve(request, name)
[ 11748, 2779, 2414, 198, 11748, 17007, 2963, 12272, 198, 11748, 28686, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 4023, 1330, 367, 29281, 26429, 11, 367, 29281, 31077, 198, 6738, 42625, 14208, 13, 195...
2.923345
287
import numpy as np import pandas as pd from abc import ABC def _gen_random(self, seed: int = None): """[summary] Args: seed (int, optional): [description]. Defaults to 123. """ rng = np.random.default_rng(seed) for example in self._new_noise: self._labels.iloc[example] = rng.choice(list(self._label_types - set(self._labels.iloc[example])))
[ 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 450, 66, 1330, 9738, 628, 220, 220, 220, 220, 198, 220, 220, 220, 825, 4808, 5235, 62, 25120, 7, 944, 11, 9403, 25, 493, 796, 6045, 2599, 198, 220, 22...
2.186528
193
from wtforms import Form, TextField, PasswordField, SelectField, TextAreaField, BooleanField, validators, ValidationError, RadioField import re phone_regex = "(\+\d+-?)?((\(?\d{3}\)?)|(\d{3}))-?\d{3}-?\d{4}$" gender_choices = [ ("", "Gender"), ("male", "Male"), ("female", "Female"), ("other", "Other"), ("rns", "Rather Not Say") ] beginner_choices = [ ("", "Are you a beginner?"), ("yes", "Yes"), ("no", "No") ] ethnicity_choices = [ ("", "Ethnicity"), ("white", "White"), ("african_american", "African American"), ("asian_pacific", "Asian or Pacific Islander"), ("american_indian_alaskan_native", "American Indian or Alaskan Native"), ("multiracial", "Multiracial"), ("hispanic", "Hispanic origin"), ("other", "Other"), ("rns", "Rather Not Say") ] num_hackathons_choices = [ ("", "How many hackathons have you been to?"), ("0", "0"), ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5+") ] num_hackathons_choices_mentor = [ ("", "How many hackathons have you mentored at?"), ("0", "0"), ("1", "1"), ("2", "2"), ("3", "3"), ("4", "4"), ("5", "5+") ] grade_choices = [ ("", "What grade are you in?"), ("9", "9th"), ("10", "10th"), ("11", "11th"), ("12", "12th") ] shirt_sizes = [ ("", "What is your shirt size?"), ("XS", "Extra Small"), ("S", "Small"), ("M", "Medium"), ("L", "Large"), ("XL", "Extra Large") ] type_account_choices = [ ("hacker", "Hacker"), ("mentor", "Mentor") ] free_response1_prompt = "Why do you want to come to hackBCA?" free_response1_prompt_mentor = "Please list languages/frameworks/technologies that you would like to mentor students in." free_response2_prompt_mentor = "Would you like to run a workshop? If so, please briefly describe your ideas." attending_choices = [ ("Attending", "Yes, I will!"), ("Not Attending", "No, I won't.") ] # class MentorRsvpForm(Form): # attending = RadioField("Are you attending hackBCA III?", [validators.Required(message = "Please tell us if you are attending hackBCA III.")], choices = attending_choices) # phone = TextField("Phone Number", [ # validators.Required(message = "Confirm your preferred contact number."), # validators.Regexp(phone_regex, message = "Please enter a valid phone number.") # ], description = "Phone Number Confirmation") # t_shirt_size = SelectField("What is your shirt size?", [validators.Required(message = "You must select an option.")], choices = shirt_sizes, description = "What is your shirt size?") # food_allergies = TextAreaField("Allergies", [ # validators.optional(), # ], description = "Do you have any allergies?") # medical_information = TextAreaField("Medical Information", [ # validators.optional(), # ], description = "Are there any other medical issues that we should know about? (ex. Other allergies, illnesses, etc.)") # hackbca_rules = BooleanField("I agree",[ # validators.Required(message = "Please read and agree to our rules.") # ], description = "I agree to the rules set forth by hackBCA.", default = False) # mlh_terms = BooleanField("I agree",[ # validators.Required(message = "Please read and agree to the MLH Code of Conduct.") # ], description = "I agree to the MLH Code of Conduct.", default = False)
[ 6738, 266, 83, 23914, 1330, 5178, 11, 8255, 15878, 11, 30275, 15878, 11, 9683, 15878, 11, 8255, 30547, 15878, 11, 41146, 15878, 11, 4938, 2024, 11, 3254, 24765, 12331, 11, 8829, 15878, 198, 11748, 302, 628, 198, 4862, 62, 260, 25636, ...
2.62624
1,311
# coding: utf-8 ''' ''' from math import ceil import os from flask import json from flask import Flask from flask import request from flask import send_from_directory from flask import render_template # from json_loader import load_locations # from json_loader import prepare_locations from models import Location # LOCATION_ITEMS_PER_PAGE = 20 app = Flask(__name__) app.config['GOOGLE_API_KEY'] = os.environ['GOOGLE_API_KEY'] app.config['ROOT'] = (app.config['APPLICATION_ROOT'] if app.config['APPLICATION_ROOT'] else '')
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 7061, 6, 198, 7061, 6, 198, 198, 6738, 10688, 1330, 2906, 346, 198, 11748, 28686, 198, 198, 6738, 42903, 1330, 33918, 198, 6738, 42903, 1330, 46947, 198, 6738, 42903, 1330, 2581, 198, 6738, ...
2.776119
201
from __future__ import annotations from .base import CorkusBase from enum import Enum
[ 6738, 11593, 37443, 834, 1330, 37647, 198, 6738, 764, 8692, 1330, 25567, 385, 14881, 198, 6738, 33829, 1330, 2039, 388, 198 ]
4.095238
21
import pybrisk
[ 198, 11748, 12972, 1671, 1984, 198 ]
2.666667
6
import serial import serial.tools.list_ports from hale_hub.constants import STARTING_OUTLET_COMMAND, SERIAL_BAUD_RATE, SERIAL_TIMEOUT from hale_hub.ifttt_logger import send_ifttt_log _outlet_interface = _OutletInterface() set_outlet_serial_interface = _outlet_interface.set_serial_interface toggle_outlet = _outlet_interface.toggle_outlet turn_on_outlet = _outlet_interface.turn_on_outlet turn_off_outlet = _outlet_interface.turn_off_outlet get_outlets = _outlet_interface.get_outlets set_outlet_name = _outlet_interface.set_outlet_name
[ 11748, 11389, 198, 11748, 11389, 13, 31391, 13, 4868, 62, 3742, 198, 6738, 289, 1000, 62, 40140, 13, 9979, 1187, 1330, 33303, 2751, 62, 12425, 28882, 62, 9858, 44, 6981, 11, 18871, 12576, 62, 4339, 8322, 62, 49, 6158, 11, 18871, 12576...
2.78866
194
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import numpy as np def measure_twocores(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of two helical cores. - Interhelical distance vector between the centers. - Interhelical angle (0-90 degree) ''' # Obtain the centers... center_ref = np.nanmean(core_xyz_ref, axis = 0) center_tar = np.nanmean(core_xyz_tar, axis = 0) # Construct the interhelical distance vector... ih_dvec = center_tar - center_ref # Calculate the length of interhelical distance vector... norm_ih_dvec = np.linalg.norm(ih_dvec) # Obtain the helical core vectors... core_xyz_ref_nonan = remove_nan(core_xyz_ref) core_xyz_tar_nonan = remove_nan(core_xyz_tar) core_vec_ref = core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Calculate the interhelical angle... core_vec_ref_unit = core_vec_ref / np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar) ih_ang = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) return ih_dvec, norm_ih_dvec, core_vec_ref_unit, core_vec_tar_unit, ih_ang def calc_interangle(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of two helical cores. - Interhelical angle (0-90 degree) ''' # Obtain the helical core vectors... core_xyz_ref_nonan = remove_nan(core_xyz_ref) core_xyz_tar_nonan = remove_nan(core_xyz_tar) core_vec_ref = core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Calculate the interhelical angle... core_vec_ref_unit = core_vec_ref / np.linalg.norm(core_vec_ref) core_vec_tar_unit = core_vec_tar / np.linalg.norm(core_vec_tar) inter_angle = np.arccos( np.dot(core_vec_ref_unit, core_vec_tar_unit) ) if inter_angle > np.pi / 2.0: inter_angle = np.pi - inter_angle return inter_angle def calc_interdist(core_xyz_ref, core_xyz_tar): ''' Measure the following aspects of two helical cores. - Interhelical distance vector between the centers. Refers to http://geomalgorithms.com/a07-_distance.html for the method. Q is ref, P is tar. ''' # Obtain the helical core vectors... core_xyz_ref_nonan = remove_nan(core_xyz_ref) core_xyz_tar_nonan = remove_nan(core_xyz_tar) core_vec_ref = core_xyz_ref_nonan[-1] - core_xyz_ref_nonan[0] core_vec_tar = core_xyz_tar_nonan[-1] - core_xyz_tar_nonan[0] # Obtain the starting point... q0 = core_xyz_ref_nonan[0] p0 = core_xyz_tar_nonan[0] w0 = p0 - q0 # Obtain the directional vector with magnitude... v = core_vec_ref u = core_vec_tar # Math part... a = np.dot(u, u) b = np.dot(u, v) c = np.dot(v, v) d = np.dot(u, w0) e = np.dot(v, w0) de = a * c - b * b # Denominator if de == 0: sc, tc = 0, d / b else: sc, tc = (b * e - c * d) / de, (a * e - b * d) / de # Calculate distance... wc = w0 + sc * u - tc * v inter_dist = np.linalg.norm(wc) return inter_dist
[ 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, 11748, 299, 32152, 355, 45941, 628, 198, 198, 4299, 3953, 62, 4246, 420, 2850, 7, 7295, 62, 5431, 89, 62, ...
2.220898
1,426
from typing import List with open("dane/liczby.txt") as f: nums: List[int] = [] nums_9_chars: List[int] = [] for line in f: sline = line.strip() num = int(sline, 2) if len(sline) == 9: nums_9_chars.append(num) nums.append(num) count_even = 0 max_num = 0 for num in nums: if num % 2 == 0: count_even += 1 if num > max_num: max_num = num print(f"{count_even=}") print(f"max_num(10): {max_num}, max_num(2): {bin(max_num)[2:]}") sum_9_chars = 0 for num in nums_9_chars: sum_9_chars += num print(f"count of numbers with 9 digits: {len(nums_9_chars)}, their sum: {bin(sum_9_chars)[2:]}")
[ 6738, 19720, 1330, 7343, 198, 198, 4480, 1280, 7203, 67, 1531, 14, 677, 89, 1525, 13, 14116, 4943, 355, 277, 25, 198, 220, 220, 220, 997, 82, 25, 7343, 58, 600, 60, 796, 17635, 198, 220, 220, 220, 997, 82, 62, 24, 62, 354, 945, ...
1.979472
341
if __name__ == "__main__": print_fib(10) print print_fib2(10)
[ 198, 220, 220, 220, 220, 628, 198, 198, 361, 11593, 3672, 834, 6624, 366, 834, 12417, 834, 1298, 198, 220, 220, 220, 3601, 62, 69, 571, 7, 940, 8, 198, 220, 220, 220, 3601, 220, 198, 220, 220, 220, 3601, 62, 69, 571, 17, 7, 94...
1.75
48
import os from typing import List from src.model.Etape import Etape from src.model.Grille import Grille from src.model.ItemCase import ItemCase from src.model.PointMontage import PointMontage from src.model.Robot import Robot from src.model.Tache import Tache
[ 11748, 28686, 198, 6738, 19720, 1330, 7343, 198, 198, 6738, 12351, 13, 19849, 13, 36, 83, 1758, 1330, 17906, 1758, 198, 6738, 12351, 13, 19849, 13, 8642, 8270, 1330, 1902, 8270, 198, 6738, 12351, 13, 19849, 13, 7449, 20448, 1330, 9097, ...
3.38961
77
import os import sys import time import traceback import project1_Copy as p1 import numpy as np verbose = False if __name__ == "__main__": main()
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 640, 198, 11748, 12854, 1891, 198, 11748, 1628, 16, 62, 29881, 355, 279, 16, 198, 11748, 299, 32152, 355, 45941, 198, 198, 19011, 577, 796, 10352, 628, 628, 628, 628, 628, 628, 198, 198, 36...
2.827586
58
""" Unit tests for module `homework_1.tasks.task_3`. """ from tempfile import NamedTemporaryFile from typing import Tuple import pytest from homework_1.tasks.task_3 import find_maximum_and_minimum
[ 37811, 198, 26453, 5254, 329, 8265, 4600, 26452, 6433, 62, 16, 13, 83, 6791, 13, 35943, 62, 18, 44646, 198, 37811, 198, 198, 6738, 20218, 7753, 1330, 34441, 12966, 5551, 8979, 198, 6738, 19720, 1330, 309, 29291, 198, 198, 11748, 12972, ...
3.140625
64
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities from . import outputs from ._enums import * __all__ = ['BlobContainerArgs', 'BlobContainer'] def _internal_init(__self__, resource_name: str, opts: Optional[pulumi.ResourceOptions] = None, account_name: Optional[pulumi.Input[str]] = None, container_name: Optional[pulumi.Input[str]] = None, metadata: Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]] = None, public_access: Optional[pulumi.Input['PublicAccess']] = None, resource_group_name: Optional[pulumi.Input[str]] = None, __props__=None): if opts is None: opts = pulumi.ResourceOptions() if not isinstance(opts, pulumi.ResourceOptions): raise TypeError('Expected resource options to be a ResourceOptions instance') if opts.version is None: opts.version = _utilities.get_version() if opts.id is None: if __props__ is not None: raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource') __props__ = BlobContainerArgs.__new__(BlobContainerArgs) if account_name is None and not opts.urn: raise TypeError("Missing required property 'account_name'") __props__.__dict__["account_name"] = account_name __props__.__dict__["container_name"] = container_name __props__.__dict__["metadata"] = metadata __props__.__dict__["public_access"] = public_access if resource_group_name is None and not opts.urn: raise TypeError("Missing required property 'resource_group_name'") __props__.__dict__["resource_group_name"] = resource_group_name __props__.__dict__["etag"] = None __props__.__dict__["has_immutability_policy"] = None __props__.__dict__["has_legal_hold"] = None __props__.__dict__["immutability_policy"] = None __props__.__dict__["last_modified_time"] = None __props__.__dict__["lease_duration"] = None __props__.__dict__["lease_state"] = None __props__.__dict__["lease_status"] = None __props__.__dict__["legal_hold"] = None __props__.__dict__["name"] = None __props__.__dict__["type"] = None alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:storage/v20181101:BlobContainer"), pulumi.Alias(type_="azure-native:storage:BlobContainer"), pulumi.Alias(type_="azure-nextgen:storage:BlobContainer"), pulumi.Alias(type_="azure-native:storage/v20180201:BlobContainer"), pulumi.Alias(type_="azure-nextgen:storage/v20180201:BlobContainer"), pulumi.Alias(type_="azure-native:storage/v20180301preview:BlobContainer"), pulumi.Alias(type_="azure-nextgen:storage/v20180301preview:BlobContainer"), pulumi.Alias(type_="azure-native:storage/v20180701:BlobContainer"), pulumi.Alias(type_="azure-nextgen:storage/v20180701:BlobContainer"), pulumi.Alias(type_="azure-native:storage/v20190401:BlobContainer"), pulumi.Alias(type_="azure-nextgen:storage/v20190401:BlobContainer"), pulumi.Alias(type_="azure-native:storage/v20190601:BlobContainer"), pulumi.Alias(type_="azure-nextgen:storage/v20190601:BlobContainer"), pulumi.Alias(type_="azure-native:storage/v20200801preview:BlobContainer"), pulumi.Alias(type_="azure-nextgen:storage/v20200801preview:BlobContainer"), pulumi.Alias(type_="azure-native:storage/v20210101:BlobContainer"), pulumi.Alias(type_="azure-nextgen:storage/v20210101:BlobContainer"), pulumi.Alias(type_="azure-native:storage/v20210201:BlobContainer"), pulumi.Alias(type_="azure-nextgen:storage/v20210201:BlobContainer")]) opts = pulumi.ResourceOptions.merge(opts, alias_opts) super(BlobContainer, __self__).__init__( 'azure-native:storage/v20181101:BlobContainer', resource_name, __props__, opts)
[ 2, 19617, 28, 40477, 12, 23, 198, 2, 17202, 39410, 25, 428, 2393, 373, 7560, 416, 262, 21624, 12994, 26144, 35986, 13, 17202, 198, 2, 17202, 2141, 407, 4370, 416, 1021, 4556, 345, 821, 1728, 345, 760, 644, 345, 389, 1804, 0, 17202, ...
2.404444
1,800
# coding:utf-8 import app.admin.views.start import app.admin.views.book import app.admin.views.user import app.admin.views.site
[ 2, 19617, 25, 40477, 12, 23, 198, 198, 11748, 598, 13, 28482, 13, 33571, 13, 9688, 198, 11748, 598, 13, 28482, 13, 33571, 13, 2070, 198, 11748, 598, 13, 28482, 13, 33571, 13, 7220, 198, 11748, 598, 13, 28482, 13, 33571, 13, 15654, ...
2.931818
44
import os import chainer import chainer.links as L from net import SiameseNetwork import numpy as np import matplotlib.pyplot as plt # model = SiameseNetwork() chainer.serializers.load_npz(os.path.join('result', 'model.npz'), model) # _, test = chainer.datasets.get_mnist(ndim=3) test_data, test_label = test._datasets # 2 y = model.forward_once(test_data) feat = y.data # c = ['#ff0000', '#ffff00', '#00ff00', '#00ffff', '#0000ff', '#ff00ff', '#990000', '#999900', '#009900', '#009999'] # # # for i in range(10): f = feat[np.where(test_label == i)] plt.plot(f[:, 0], f[:, 1], '.', c=c[i]) plt.legend(['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']) plt.savefig(os.path.join('result', 'result.png'))
[ 11748, 28686, 198, 198, 11748, 6333, 263, 198, 11748, 6333, 263, 13, 28751, 355, 406, 198, 6738, 2010, 1330, 15638, 1047, 68, 26245, 198, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 2603, 29487, 8019, 13, 9078, 29487, 355, 458, 83, ...
2.189189
333
from random import randrange, random from time import time import logging from TwisterTempoGUI import TwisterTempoGUI
[ 6738, 4738, 1330, 43720, 9521, 11, 4738, 198, 6738, 640, 1330, 640, 198, 11748, 18931, 198, 6738, 1815, 1694, 12966, 7501, 40156, 1330, 1815, 1694, 12966, 7501, 40156, 628, 198 ]
4
30
# -*- coding: utf-8 -*- """ Panorama is a Pelican plugin to generate statistics from blog posts (number of posts per month, categories and so on) display them as beautiful charts. Project location: https://github.com/romainx/panorama """ __version__ = "0.2.0" __author__ = "romainx" from .panorama import *
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 37811, 198, 15730, 36161, 318, 257, 12903, 7490, 13877, 284, 7716, 7869, 422, 4130, 6851, 198, 7, 17618, 286, 6851, 583, 1227, 11, 9376, 290, 523, 319, 8, 3359, 6...
3.11
100
#!/usr/bin/python2.5 # Copyright (C) 2007 Google 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. from gtfsobjectbase import GtfsObjectBase import problems as problems_module import util
[ 2, 48443, 14629, 14, 8800, 14, 29412, 17, 13, 20, 198, 198, 2, 15069, 357, 34, 8, 4343, 3012, 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, ...
3.642105
190
from django.urls import path from . import views from . views import UserPostListView, PostDetailView, PostDeleteview, PostCreateView, PostUpdateView,CommentUpdateView, VideoCreateView, video_update urlpatterns = [ path('',views.base, name='base'), path('login',views.login, name='login'), path('register',views.register, name='register'), path('index',views.index, name='index'), path('logout',views.logout, name='logout'), path('like_post', views.like_post, name='like_post'), path('find_friends',views.find_friends, name='find_friends'), path('profile',views.profile, name='profile'), path('profile_update', views.profile_update, name='profile_update'), path('user/<str:username>', UserPostListView.as_view(), name='user_posts'), path('post/<int:pk>/',PostDetailView.as_view(), name='post_details' ), path('post/<int:pk>/delete/',PostDeleteview.as_view(), name='post_delete' ), path('profile_posts',views.profile_posts, name='profile_posts'), path('results',views.results, name='results'), path('post/new/',PostCreateView.as_view(), name='post-create' ), path('post_update',views.post_update, name='post_update'), path('post/<int:pk>/update',PostUpdateView.as_view(), name='post-update' ), path('profile_photos',views.profile_photos, name='profile_photos'), path('comment_update/<int:id>',views.comment_update, name='comment_update'), path('comment/<int:pk>/update',CommentUpdateView.as_view(), name='comment-update' ), path('delete/<int:id>',views.delete, name='delete'), path('favourite',views.favourite, name='favourite'), path('favourite_posts',views.favourite_posts, name='favourite_posts'), path('video/new/',VideoCreateView.as_view(), name='video-create' ), path('post/<int:pk>/video',video_update.as_view(), name='video_update' ), # path('<str:username>',views.userprofile, name='userprofile'), path('video_posts',views.video_posts, name='video_posts'), path('user_videos',views.user_videos,name='user_videos'), ]
[ 6738, 42625, 14208, 13, 6371, 82, 1330, 3108, 198, 6738, 764, 1330, 5009, 198, 6738, 764, 5009, 1330, 11787, 6307, 8053, 7680, 11, 2947, 11242, 603, 7680, 11, 2947, 38727, 1177, 11, 2947, 16447, 7680, 11, 2947, 10260, 7680, 11, 21357, ...
2.804613
737
''' compute_collision() will compute the collision of all the entities with a Point while compute_first_collision() will always return its first entry. Especially if a point is on an element edge this can be tricky. You may also want to compare with the Cell.contains(Point) tool. ''' # Script by Rudy at https://fenicsproject.discourse.group/t/ # any-function-to-determine-if-the-point-is-in-the-mesh/275/3 import dolfin from vtkplotter.dolfin import shapes, plot, printc n = 4 Px = 0.5 Py = 0.5 mesh = dolfin.UnitSquareMesh(n, n) bbt = mesh.bounding_box_tree() collisions = bbt.compute_collisions(dolfin.Point(Px, Py)) collisions1st = bbt.compute_first_entity_collision(dolfin.Point(Px, Py)) printc("collisions : ", collisions) printc("collisions 1st: ", collisions1st) for cell in dolfin.cells(mesh): contains = cell.contains(dolfin.Point(Px, Py)) printc("Cell", cell.index(), "contains P:", contains, c=contains) ########################################### pt = shapes.Point([Px, Py], c='blue') plot(mesh, pt, text=__doc__)
[ 7061, 6, 198, 5589, 1133, 62, 26000, 1166, 3419, 481, 24061, 262, 17661, 286, 477, 262, 12066, 351, 198, 64, 6252, 981, 24061, 62, 11085, 62, 26000, 1166, 3419, 481, 1464, 1441, 663, 717, 5726, 13, 198, 48464, 611, 257, 966, 318, 31...
2.766404
381
import datetime import os from alice_check_train.main import rasp_to_text from alice_check_train.rasp_api import get_rasp, filter_rasp if __name__ == '__main__': main()
[ 11748, 4818, 8079, 198, 11748, 28686, 198, 198, 6738, 435, 501, 62, 9122, 62, 27432, 13, 12417, 1330, 374, 5126, 62, 1462, 62, 5239, 198, 6738, 435, 501, 62, 9122, 62, 27432, 13, 81, 5126, 62, 15042, 1330, 651, 62, 81, 5126, 11, 8...
2.641791
67
# https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb # https://docs.aws.amazon.com/opensearch-service/latest/developerguide/knn.html import sys import requests import h5py import numpy as np import json import aiohttp import asyncio import time import httpx from requests.auth import HTTPBasicAuth from statistics import mean # if len(sys.argv) != 2: # print("Type in the efSearch!") # sys.exit() # path = '/tmp/sift-128-euclidean.hdf5.1M' # float dataset # path = '/tmp/sift-128-euclidean.hdf5' # float dataset path = '/home/ubuntu/sift-128-euclidean.hdf5' # float dataset output_csv = '/tmp/sift-es.csv' # url = 'http://127.0.0.1:9200/sift-index/' host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # single node # host = 'https://vpc-....ap-southeast-1.es.amazonaws.com/' # two nodes url = host + 'sift-index/' requestHeaders = {'content-type': 'application/json'} # https://stackoverflow.com/questions/51378099/content-type-header-not-supported auth = HTTPBasicAuth('admin', 'I#vu7bTAHB') # Build an index #https://stackoverflow.com/questions/17301938/making-a-request-to-a-restful-api-using-python # PUT sift-index data = '''{ "settings": { "index": { "knn": true, "knn.space_type": "l2", "knn.algo_param.m": 6, "knn.algo_param.ef_construction": 50, "knn.algo_param.ef_search": 50, "refresh_interval": -1, "translog.flush_threshold_size": "10gb", "number_of_replicas": 0 } }, "mappings": { "properties": { "sift_vector": { "type": "knn_vector", "dimension": 128 } } } }''' # https://medium.com/@kumon/how-to-realize-similarity-search-with-elasticsearch-3dd5641b9adb response = requests.put(url, data=data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) # response = requests.put(url, data=data, verify=False, headers=requestHeaders, auth=auth) assert response.status_code==requests.codes.ok # cluster_url = 'http://127.0.0.1:9200/_cluster/settings' cluster_url = host + '_cluster/settings' cluster_data = '''{ "persistent" : { "knn.algo_param.index_thread_qty": 16 } } ''' response = requests.put(cluster_url, data=cluster_data, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok # Bulkload into index bulk_template = '{ "index": { "_index": "sift-index", "_id": "%s" } }\n{ "sift_vector": [%s] }\n' hf = h5py.File(path, 'r') for key in hf.keys(): print("A key of hf is %s" % key) #Names of the groups in HDF5 file. vectors = np.array(hf["train"][:]) num_vectors, dim = vectors.shape print("num_vectors: %d" % num_vectors) print("dim: %d" % dim) bulk_data = "" start = time.time() for (id,vector) in enumerate(vectors): assert len(vector)==dim vector_str = "" for num in vector: vector_str += str(num) + ',' vector_str = vector_str[:-1] id_str = str(id) single_bulk_done = bulk_template % (id_str, vector_str) bulk_data += single_bulk_done if (id+1) % 100000 == 0: print(str(id+1)) # POST _bulk response = requests.put(url + '_bulk', data=bulk_data, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'), headers=requestHeaders) assert response.status_code==requests.codes.ok bulk_data = "" end = time.time() print("Insert Time: %d mins" % ((end - start) / 60.0)) # Unit: min # refresh_url = 'http://127.0.0.1:9200/sift-index/_settings' refresh_url = host + 'sift-index/_settings' refresh_data = '''{ "index" : { "refresh_interval": "1s" } } ''' response = requests.put(refresh_url, data=refresh_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) assert response.status_code==requests.codes.ok # response = requests.post('http://127.0.0.1:9200/sift-index/_refresh', verify=False, headers=requestHeaders) # assert response.status_code==requests.codes.ok # merge_url = 'http://127.0.0.1:9200/sift-index/_forcemerge?max_num_segments=1' merge_url = host + 'sift-index/_forcemerge?max_num_segments=1' merge_response = requests.post(merge_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'), timeout=600) assert merge_response.status_code==requests.codes.ok # warmup_url = 'http://127.0.0.1:9200/_opendistro/_knn/warmup/sift-index' warmup_url = host + '_opendistro/_knn/warmup/sift-index' warmup_response = requests.get(warmup_url, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) assert warmup_response.status_code==requests.codes.ok # Send queries total_time = 0 # in ms hits = 0 # for recall calculation query_template = ''' { "size": 50, "query": {"knn": {"sift_vector": {"vector": [%s],"k": 50}}} } ''' queries = np.array(hf["test"][:]) nq = len(queries) neighbors = np.array(hf["neighbors"][:]) # distances = np.array(hf["distances"][:]) num_queries, q_dim = queries.shape print("num_queries: %d" % num_queries) print("q_dim: %d" % q_dim) assert q_dim==dim ef_search_list = [50, 100, 150, 200, 250, 300] for ef_search in ef_search_list: ef_data = '''{ "index": { "knn.algo_param.ef_search": %d } }''' ef_data = ef_data % ef_search ### Update Index Setting: efSearch response = requests.put(url + '_settings', data=ef_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB')) assert response.status_code==requests.codes.ok total_time_list = [] hits_list = [] for count in range(5): total_time = 0 # in ms hits = 0 # for recall calculation query_template = ''' ''' single_query = '''{}\n{"size": 50, "query": {"knn": {"sift_vector": {"vector": [%s],"k": 50}}}}\n''' for (id,query) in enumerate(queries): assert len(query)==dim query_str = "" for num in query: query_str += str(num) + ',' query_str = query_str[:-1] # GET sift-index/_search single_query_done = single_query % (query_str) query_template += single_query_done query_data = query_template # print(query_data) response = requests.get(url + '_msearch', data=query_data, headers=requestHeaders, auth=HTTPBasicAuth('admin', 'I#vu7bTAHB'), stream=True) assert response.status_code==requests.codes.ok # print(response.text) result = json.loads(response.text) # QPS total_time = result['took'] # tooks = [] # for i in range(len(queries)): # for ele in result['responses']: # tooks.append(int(ele['took'])) for id in range(len(queries)): # Recall neighbor_id_from_result = [] for ele in result['responses'][id]['hits']['hits']: neighbor_id_from_result.append(int(ele['_id'])) assert len(neighbor_id_from_result)==50 # print("neighbor_id_from_result: ") # print(neighbor_id_from_result) neighbor_id_gt = neighbors[id][0:50] # topK=50 # print("neighbor_id_gt") # print(neighbor_id_gt) hits_q = len(list(set(neighbor_id_from_result) & set(neighbor_id_gt))) # print("# hits of this query with topk=50: %d" % hits_q) hits += hits_q total_time_list.append(total_time) hits_list.append(hits) print(total_time_list) total_time_avg = mean(total_time_list[2:-1]) hits_avg = mean(hits_list) QPS = 1.0 * nq / (total_time_avg / 1000.0) recall = 1.0 * hits_avg / (nq * 50) print(ef_search, QPS, recall)
[ 2, 3740, 1378, 24132, 13, 785, 14, 31, 74, 388, 261, 14, 4919, 12, 1462, 12, 5305, 1096, 12, 38610, 414, 12, 12947, 12, 4480, 12, 417, 3477, 12947, 12, 18, 1860, 20, 42759, 65, 24, 324, 65, 198, 2, 3740, 1378, 31628, 13, 8356, ...
2.387002
3,062
import platform import textwrap import pytest from . import test_projects, utils dockcross_only_project = test_projects.new_c_project( setup_py_add=textwrap.dedent(r''' import os, sys # check that we're running in the correct docker image as specified in the # environment options CIBW_MANYLINUX1_*_IMAGE if "linux" in sys.platform and not os.path.exists("/dockcross"): raise Exception( "/dockcross directory not found. Is this test running in the correct docker image?" ) ''') )
[ 11748, 3859, 198, 11748, 2420, 37150, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 764, 1330, 1332, 62, 42068, 11, 3384, 4487, 198, 198, 67, 735, 19692, 62, 8807, 62, 16302, 796, 1332, 62, 42068, 13, 3605, 62, 66, 62, 16302, 7, 198...
2.522321
224
# coding: utf-8 import math import dateutil import dateutil.parser import json from ChartBars import Chart from ChartUpdaterByCCWebsocket import ChartUpdaterByCoincheckWS from Util import BitcoinUtil # a class for one position
[ 2, 19617, 25, 3384, 69, 12, 23, 198, 198, 11748, 10688, 198, 11748, 3128, 22602, 198, 11748, 3128, 22602, 13, 48610, 198, 11748, 33918, 198, 198, 6738, 22086, 33, 945, 1330, 22086, 198, 6738, 22086, 4933, 67, 729, 3886, 4093, 1135, 14...
3.253521
71
from PiRelay8 import Relay import time r1 = Relay("RELAY1") r2 = Relay("RELAY2") r3 = Relay("RELAY3") r4 = Relay("RELAY4") r5 = Relay("RELAY5") r6 = Relay("RELAY6") r7 = Relay("RELAY7") r8 = Relay("RELAY8") r1.off() r2.off() r3.off() r4.off() r5.off() r6.off() r7.off() r8.off() r1.on() time.sleep(0.5) r1.off() time.sleep(0.5) r2.on() time.sleep(0.5) r2.off() time.sleep(0.5) r3.on() time.sleep(0.5) r3.off() time.sleep(0.5) r4.on() time.sleep(0.5) r4.off() time.sleep(0.5) r5.on() time.sleep(0.5) r5.off() time.sleep(0.5) r6.on() time.sleep(0.5) r6.off() time.sleep(0.5) r7.on() time.sleep(0.5) r7.off() time.sleep(0.5) r8.on() time.sleep(0.5) r8.off() time.sleep(0.5)
[ 6738, 13993, 6892, 323, 23, 1330, 4718, 323, 201, 198, 11748, 640, 201, 198, 201, 198, 81, 16, 796, 4718, 323, 7203, 16448, 4792, 16, 4943, 201, 198, 81, 17, 796, 4718, 323, 7203, 16448, 4792, 17, 4943, 201, 198, 81, 18, 796, 4718...
1.615217
460
import rs3clans import discord from discord.ext import commands from bot.bot_client import Bot from bot.utils.tools import separator from bot.utils.context import Context
[ 11748, 44608, 18, 565, 504, 201, 198, 11748, 36446, 201, 198, 6738, 36446, 13, 2302, 1330, 9729, 201, 198, 201, 198, 6738, 10214, 13, 13645, 62, 16366, 1330, 18579, 201, 198, 6738, 10214, 13, 26791, 13, 31391, 1330, 2880, 1352, 201, 1...
3.267857
56
# 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. # import json import uuid from datetime import datetime from openstackclient.tests.functional import base
[ 2, 220, 220, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 345, 743, 198, 2, 220, 220, 407, 779, 428, 2393, 2845, 287, 11846, 351, 262, 13789, 13, 921, 743, 7330, 198, 2, 220, 220, 257, 4866,...
3.560847
189
import unittest from typing import Set, Optional, Dict, List from uuid import uuid4 from StructNoSQL import BaseField, MapModel, TableDataModel from tests.components.playground_table_clients import PlaygroundDynamoDBBasicTable, TEST_ACCOUNT_ID if __name__ == '__main__': unittest.main()
[ 11748, 555, 715, 395, 198, 6738, 19720, 1330, 5345, 11, 32233, 11, 360, 713, 11, 7343, 198, 6738, 334, 27112, 1330, 334, 27112, 19, 198, 198, 6738, 32112, 2949, 17861, 1330, 7308, 15878, 11, 9347, 17633, 11, 8655, 6601, 17633, 198, 67...
3.148936
94
import unittest from test import test_support import base64 def test_main(): test_support.run_unittest(__name__) if __name__ == '__main__': test_main()
[ 11748, 555, 715, 395, 198, 6738, 1332, 1330, 1332, 62, 11284, 198, 11748, 2779, 2414, 628, 628, 628, 198, 200, 198, 4299, 1332, 62, 12417, 33529, 198, 220, 220, 220, 1332, 62, 11284, 13, 5143, 62, 403, 715, 395, 7, 834, 3672, 834, ...
2.6
65
import numpy as np from ctypes import c_void_p from .Shader import Shader from .transforms import * from OpenGL.GL import *
[ 11748, 299, 32152, 355, 45941, 198, 6738, 269, 19199, 1330, 269, 62, 19382, 62, 79, 198, 198, 6738, 764, 2484, 5067, 1330, 911, 5067, 198, 6738, 764, 7645, 23914, 1330, 1635, 198, 198, 6738, 30672, 13, 8763, 1330, 1635, 198, 220, 220,...
2.755102
49
from argparse import ( ArgumentParser ) from os import getcwd as os_getcwd DEFAULT_OUTPUT_FOLDER = os_getcwd() DEFAULT_SAMPLE_VOLUME = 10000
[ 6738, 1822, 29572, 1330, 357, 198, 220, 220, 220, 45751, 46677, 198, 220, 220, 220, 1267, 198, 6738, 28686, 1330, 651, 66, 16993, 355, 28686, 62, 1136, 66, 16993, 198, 198, 7206, 38865, 62, 2606, 7250, 3843, 62, 37, 3535, 14418, 796, ...
2.491803
61
import math x = float(input()) prop_2 = -(x**2) / math.factorial(2) prop_3 = (x**4) / math.factorial(4) prop_4 = -(x**6) / math.factorial(6) cos_x = float(1 + prop_2 + prop_3 + prop_4) print(prop_2) print(prop_3) print(prop_4) print(cos_x)
[ 11748, 10688, 198, 198, 87, 796, 12178, 7, 15414, 28955, 198, 198, 22930, 62, 17, 796, 532, 7, 87, 1174, 17, 8, 1220, 10688, 13, 22584, 5132, 7, 17, 8, 198, 198, 22930, 62, 18, 796, 357, 87, 1174, 19, 8, 1220, 10688, 13, 22584, ...
2.033058
121
import pytest from datagateway_api.src.common.exceptions import BadRequestError, FilterError from datagateway_api.src.datagateway_api.filter_order_handler import FilterOrderHandler from datagateway_api.src.datagateway_api.icat.filters import PythonICATWhereFilter
[ 11748, 12972, 9288, 198, 198, 6738, 4818, 37861, 1014, 62, 15042, 13, 10677, 13, 11321, 13, 1069, 11755, 1330, 7772, 18453, 12331, 11, 25853, 12331, 198, 6738, 4818, 37861, 1014, 62, 15042, 13, 10677, 13, 19608, 37861, 1014, 62, 15042, ...
3.410256
78
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://doc.scrapy.org/en/latest/topics/items.html import scrapy from scrapy.loader import ItemLoader from scrapy.loader.processors import TakeFirst # class SpiderItem(scrapy.Item): # # define the fields for your item here like: # # name = scrapy.Field() # pass # # # # class TorrentItem(scrapy.Item): # url = scrapy.Field() # name = scrapy.Field() # description = scrapy.Field() # size = scrapy.Field() # # import scrapy
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 2, 2896, 500, 994, 262, 4981, 329, 534, 15881, 276, 3709, 198, 2, 198, 2, 4091, 10314, 287, 25, 198, 2, 3740, 1378, 15390, 13, 1416, 2416, 88, 13, 2398, 14, 2...
2.615023
213
# # (C) Copyright 2013 Enthought, Inc., Austin, TX # All right reserved. # # This file is open source software distributed according to the terms in # LICENSE.txt # """ Context holding multiple subcontexts. """ from __future__ import absolute_import from itertools import chain from collections import MutableMapping as DictMixin from traits.api import (Bool, List, Str, Undefined, Supports, adapt, provides, on_trait_change) from .data_context import DataContext, ListenableMixin, PersistableMixin from .i_context import ICheckpointable, IDataContext, IRestrictedContext from .utils import safe_repr
[ 2, 198, 2, 357, 34, 8, 15069, 2211, 2039, 28895, 11, 3457, 1539, 9533, 11, 15326, 198, 2, 1439, 826, 10395, 13, 198, 2, 198, 2, 770, 2393, 318, 1280, 2723, 3788, 9387, 1864, 284, 262, 2846, 287, 198, 2, 38559, 24290, 13, 14116, ...
3.477273
176
"""A simple file to test the line_counter performance in python This is a multiline doctest """ __author__ = "Frederico Moeller" __copyright__ = "" __credits__ = ["Frederico Moeller"] __license__ = "MIT" __version__ = "1.0.1" __maintainer__ = "Frederico Moeller" __email__ = "" __status__ = "" #import things import math #define things def some_function(var_one, var_two, var_three): """This is a function that do things""" if var_one > var_two: if var_two*var_three > var_one: return "blab" #this happens else: return "blob" else: return "fish"
[ 37811, 32, 2829, 2393, 284, 1332, 262, 1627, 62, 24588, 2854, 287, 21015, 198, 1212, 318, 257, 1963, 346, 500, 10412, 395, 198, 37811, 198, 198, 834, 9800, 834, 796, 366, 30847, 263, 3713, 4270, 12368, 1, 198, 834, 22163, 4766, 834, ...
2.330882
272
"""Data pipelines.""" from collections import defaultdict, OrderedDict from tqdm import tqdm from torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler import torch def get_info(examples, vocab=None, max_seq_len=256): """Gathers info on and creats a featurized example generator for a list of raw examples. Args: examples: list(list, float, or string). Examples to create generator for. vocab: list(str). A vocabulary for discrete datatypes (e.g. text or categorical). max_seq_len: int. maximum sequence length for text examples. Returns: A dict of info about this variable as well as a generator over featurized examples. """ assert isinstance(examples, list), 'examples must be list; got ' + str(type(examples)) assert len(examples) > 0, 'Empty example list!' # Text if isinstance(examples[0], list): assert vocab is not None, 'ERROR: must provide a vocab.' example_type = 'input' vocab = ['UNK', 'PAD'] + vocab tok2id = {tok: i for i, tok in enumerate(vocab)} ngrams = max(len(x.split()) for x in vocab) unk_id = 0 # Continuous elif isinstance(examples[0], float) or isinstance(examples[0], int): example_type = 'continuous' vocab = ['N/A'] if isinstance(examples[0], int): featurizer = lambda ex: float(ex) else: featurizer = lambda ex: ex # Categorical elif isinstance(examples[0], str): example_type = 'categorical' if not vocab: vocab = ['UNK'] + sorted(list(set(examples))) tok2id = {tok: i for i, tok in enumerate(vocab)} featurizer = lambda ex: tok2id.get(ex, 0) # 0 is the unk id. else: print("ERROR: unrecognized example type: ", examples[0]) quit() return featurizer, example_type, vocab
[ 37811, 6601, 31108, 526, 15931, 198, 198, 6738, 17268, 1330, 4277, 11600, 11, 14230, 1068, 35, 713, 198, 6738, 256, 80, 36020, 1330, 256, 80, 36020, 198, 198, 6738, 28034, 13, 26791, 13, 7890, 1330, 309, 22854, 27354, 292, 316, 11, 60...
2.471354
768
# Take number, and convert integer to string # Calculate and return number of digits # Define main function # Call main function main()
[ 2, 7214, 1271, 11, 290, 10385, 18253, 284, 4731, 198, 2, 27131, 378, 290, 1441, 1271, 286, 19561, 628, 198, 2, 2896, 500, 1388, 2163, 198, 220, 220, 220, 220, 198, 2, 4889, 1388, 2163, 198, 12417, 3419, 198 ]
3.666667
39
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals from __future__ import division from future import standard_library standard_library.install_aliases() from builtins import * import re import sys import os import subprocess import socket from .parser import WhoisEntry from .whois import NICClient # thanks to https://www.regextester.com/104038 IPV4_OR_V6 = re.compile(r"((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)|(^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))") suffixes = None def extract_domain(url): """Extract the domain from the given URL >>> print(extract_domain('http://www.google.com.au/tos.html')) google.com.au >>> print(extract_domain('abc.def.com')) def.com >>> print(extract_domain(u'www..hk')) .hk >>> print(extract_domain('chambagri.fr')) chambagri.fr >>> print(extract_domain('www.webscraping.com')) webscraping.com >>> print(extract_domain('198.252.206.140')) stackoverflow.com >>> print(extract_domain('102.112.2O7.net')) 2o7.net >>> print(extract_domain('globoesporte.globo.com')) globo.com >>> print(extract_domain('1-0-1-1-1-0-1-1-1-1-1-1-1-.0-0-0-0-0-0-0-0-0-0-0-0-0-10-0-0-0-0-0-0-0-0-0-0-0-0-0.info')) 0-0-0-0-0-0-0-0-0-0-0-0-0-10-0-0-0-0-0-0-0-0-0-0-0-0-0.info >>> print(extract_domain('2607:f8b0:4006:802::200e')) 1e100.net >>> print(extract_domain('172.217.3.110')) 1e100.net """ if IPV4_OR_V6.match(url): # this is an IP address return socket.gethostbyaddr(url)[0] # load known TLD suffixes global suffixes if not suffixes: # downloaded from https://publicsuffix.org/list/public_suffix_list.dat tlds_path = os.path.join(os.getcwd(), os.path.dirname(__file__), 'data', 'public_suffix_list.dat') with open(tlds_path, encoding='utf-8') as tlds_fp: suffixes = set(line.encode('utf-8') for line in tlds_fp.read().splitlines() if line and not line.startswith('//')) if not isinstance(url, str): url = url.decode('utf-8') url = re.sub('^.*://', '', url) url = url.split('/')[0].lower() # find the longest suffix match domain = b'' split_url = url.split('.') for section in reversed(split_url): if domain: domain = b'.' + domain domain = section.encode('utf-8') + domain if domain not in suffixes: if not b'.' in domain and len(split_url) >= 2: # If this is the first section and there wasn't a match, try to # match the first two sections - if that works, keep going # See https://github.com/richardpenman/whois/issues/50 second_order_tld = '.'.join([split_url[-2], split_url[-1]]) if not second_order_tld.encode('utf-8') in suffixes: break else: break return domain.decode('utf-8') if __name__ == '__main__': try: url = sys.argv[1] except IndexError: print('Usage: %s url' % sys.argv[0]) else: print(whois(url))
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 198, 6738, 11593, 37443, 834, 1330, 3601, 62, 8818, 198, 6738, 11593, 37443, 834, 1330, 4112, 62, 11748, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, ...
1.734445
2,459
import asyncio from contextlib import AsyncExitStack from aiogram.dispatcher.filters.state import StatesGroup, State from aiogram.dispatcher.storage import FSMContextProxy from aiogram.types import Message, PhotoSize, ReplyKeyboardRemove, ContentTypes from aiogram.utils.helper import HelperMode from dialog.avatar_image_work import download_tg_photo, get_userpic, combine_frame_and_photo_v2, img_to_bio from dialog.base import BaseDialog, message_handler from localization import BaseLocalization from lib.depcont import DepContainer from lib.texts import kbd # todo: accept documents!
[ 11748, 30351, 952, 198, 6738, 4732, 8019, 1330, 1081, 13361, 30337, 25896, 198, 198, 6738, 257, 72, 21857, 13, 6381, 8071, 2044, 13, 10379, 1010, 13, 5219, 1330, 1829, 13247, 11, 1812, 198, 6738, 257, 72, 21857, 13, 6381, 8071, 2044, ...
3.488235
170
from skimage.metrics import structural_similarity as ssim from glob import glob from PIL import Image import numpy as np import ntpath import dhash import cv2 from database_structure import database_migrations IMAGE_FOLDER = "./image_store" ALLOWED_EXTENSIONS = ['png', 'jpg', 'jpeg'] image_store_hash = dict() db_ops = database_migrations()
[ 6738, 1341, 9060, 13, 4164, 10466, 1330, 13204, 62, 38610, 414, 355, 264, 14323, 198, 6738, 15095, 1330, 15095, 198, 6738, 350, 4146, 1330, 7412, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 299, 83, 6978, 198, 11748, 288, 17831, 198...
3.035088
114
import discord from discord.ext import commands import os import json from datetime import date, datetime, timedelta from .utils import helper_functions as hf from copy import deepcopy dir_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))).replace('\\', '/')
[ 11748, 36446, 198, 6738, 36446, 13, 2302, 1330, 9729, 198, 11748, 28686, 198, 11748, 33918, 198, 6738, 4818, 8079, 1330, 3128, 11, 4818, 8079, 11, 28805, 12514, 198, 6738, 764, 26791, 1330, 31904, 62, 12543, 2733, 355, 289, 69, 198, 673...
3.309524
84
#!/usr/bin/env python3 from components import ProgramState import binaryninja as binja import argparse import os.path import curses # TODO...impliment live-refreashing the settings.json during run (add the keybinding and check for it here in the global input loop) # TODO...support multi-key presses? Not sure if this already works or not # TODO...make sure to support small terminals (I think it does right now, but I should add some more checks so nothing goes out of bounds) if __name__ == "__main__": background = "2a2a2a" text = "e0e0e0" curses.wrapper(main)
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 6738, 6805, 1330, 6118, 9012, 198, 11748, 13934, 35073, 6592, 355, 9874, 6592, 198, 11748, 1822, 29572, 198, 11748, 28686, 13, 6978, 198, 11748, 43878, 198, 198, 2, 16926, 46, ...
3.416667
168
# Copyright 2015 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. # ============================================================================== """Private base class for pooling 3D layers.""" import tensorflow.compat.v2 as tf from keras import backend from keras.engine.base_layer import Layer from keras.engine.input_spec import InputSpec from keras.utils import conv_utils
[ 2, 15069, 1853, 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, 407, 779, 428, 2393, 2845, 287, 11846, ...
4.017391
230
import moviepy.editor as mpy import moviepy.video.fx.all as vfx import subprocess as sp # Crop and resize video clip = mpy.VideoFileClip("smoke.mp4") (w, h) = clip.size cropped_clip = vfx.crop(clip, width=(h/128)*64, height=h, x1=w/4*3-100, y1=0).resize((64, 128)) cropped_clip.write_videofile('smoke-cropped.mp4') # Convert video to frames # Make sure to install ffmpeg on machine cmd='ffmpeg -i /path/to/smoke-cropped.mp4 /path/to/frames_temp/%d.bmp' sp.call(cmd,shell=True) # Convert image to black and white bitmap for i in range(202): col = Image.open("frames_temp/" + str(i + 1) + ".bmp") gray = col.convert('L') bw = gray.point(lambda x: 0 if x<128 else 255, '1') bw.save("frames/" + str(i) + ".bmp")
[ 11748, 3807, 9078, 13, 35352, 355, 285, 9078, 198, 11748, 3807, 9078, 13, 15588, 13, 21373, 13, 439, 355, 410, 21373, 198, 11748, 850, 14681, 355, 599, 198, 198, 2, 327, 1773, 290, 47558, 2008, 198, 15036, 796, 285, 9078, 13, 10798, ...
2.444444
297
"""This contains the configuration of the Rolodex application.""" # Django Imports from django.apps import AppConfig
[ 37811, 1212, 4909, 262, 8398, 286, 262, 371, 349, 375, 1069, 3586, 526, 15931, 198, 198, 2, 37770, 1846, 3742, 198, 6738, 42625, 14208, 13, 18211, 1330, 2034, 16934, 628 ]
3.966667
30
# Generated by Django 4.0.3 on 2022-03-01 14:42 from django.conf import settings from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 604, 13, 15, 13, 18, 319, 33160, 12, 3070, 12, 486, 1478, 25, 3682, 198, 198, 6738, 42625, 14208, 13, 10414, 1330, 6460, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
3.1
40
''' Created on Mar 22, 2020 @author: Michal.Busta at gmail.com ''' #get rid of the optimizer state ... import torch MODEL_PATH = '/models/model-b2-2.pth' state = torch.load(MODEL_PATH, map_location=lambda storage, loc: storage) state_out = { "state_dict": state["state_dict"], } torch.save(state_out, 'model-b2-2.pth')
[ 7061, 6, 198, 41972, 319, 1526, 2534, 11, 12131, 198, 198, 31, 9800, 25, 2843, 282, 13, 33, 436, 64, 379, 308, 4529, 13, 785, 198, 7061, 6, 198, 198, 2, 1136, 5755, 286, 262, 6436, 7509, 1181, 2644, 220, 198, 11748, 28034, 198, ...
2.51938
129
import os import re from setuptools import setup version = re.search( '^__version__\s*=\s*"(.*)"', open('braumeister/braumeister.py').read(), re.M ).group(1) setup( name="braumeister", packages=["braumeister", "braumeister.actions"], version=version, author="Marcel Steffen", author_email="marcel@talentsconnect.com", description="Easy release bulding, combining JIRA and git", long_description=read('README.md'), license="MIT", keywords="git jira release", url="https://www.talentsconnect.com", include_package_data=True, install_requires=['requests', 'colorama'], entry_points={ 'console_scripts': ["braumeister = braumeister.braumeister:main"] }, python_requires='!=2.7, !=3.4, >=3.5', zip_safe=False, classifiers=[ "Development Status :: 4 - Beta", "Environment :: Console", "Intended Audience :: Developers", "Topic :: Utilities", "Topic :: Software Development :: Version Control :: Git" ], )
[ 11748, 28686, 198, 11748, 302, 198, 198, 6738, 900, 37623, 10141, 1330, 9058, 198, 198, 9641, 796, 302, 13, 12947, 7, 198, 220, 220, 220, 705, 61, 834, 9641, 834, 59, 82, 9, 28, 59, 82, 9, 18109, 15885, 16725, 3256, 198, 220, 220,...
2.551724
406
# standard library imports import os # third party imports import numpy as np from PIL import Image import torch.nn as nn from torchvision import transforms # local imports import config from . import utils from . import geometric_transformer
[ 2, 3210, 5888, 17944, 198, 11748, 28686, 198, 198, 2, 2368, 2151, 17944, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 350, 4146, 1330, 7412, 198, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 28034, 10178, 1330, 31408, 628, ...
3.90625
64
from pathlib import Path import h5py import numpy as np from torchvision.datasets.vision import VisionDataset from PIL import Image import requests import zipfile from tqdm import tqdm
[ 6738, 3108, 8019, 1330, 10644, 198, 198, 11748, 289, 20, 9078, 198, 11748, 299, 32152, 355, 45941, 198, 6738, 28034, 10178, 13, 19608, 292, 1039, 13, 10178, 1330, 19009, 27354, 292, 316, 198, 6738, 350, 4146, 1330, 7412, 198, 198, 11748...
3.339286
56
""" link: https://leetcode.com/problems/permutations-ii problem: nums solution: 46 """
[ 37811, 201, 198, 201, 198, 8726, 25, 3740, 1378, 293, 316, 8189, 13, 785, 14, 1676, 22143, 14, 16321, 32855, 12, 4178, 201, 198, 201, 198, 45573, 25, 997, 82, 201, 198, 201, 198, 82, 2122, 25, 6337, 201, 198, 201, 198, 37811, 201,...
2.222222
45
import findspark findspark.init() from pyspark import SparkConf,SparkContext from pyspark.streaming import StreamingContext from pyspark.sql import Row,SQLContext import sys import requests conf=SparkConf() conf.setAppName("BigData") sc=SparkContext(conf=conf) ssc=StreamingContext(sc,int(sys.argv[1])) ssc.checkpoint("/checkpoint_BIGDATA") ''' #Selecting a window : #outpu3: inputStream=ssc.socketTextStream("localhost",9009) dataStream = inputStream.window(int(sys.argv[1]),int(sys.argv[2])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') tweet1.pprint() res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) #res.pprint(3) ''' ''' #Selecting a datastream and then reducing by window: #outpu2 dataStream=ssc.socketTextStream("localhost",9009) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) #septweet.pprint() count=septweet.reduceByKeyAndWindow(lambda x,y:x+y,int(sys.argv[1]),int(sys.argv[2])) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') #tweet1.pprint() res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) ''' #Try in outpu1 inputStream=ssc.socketTextStream("localhost",9009) dataStream = inputStream.window(int(sys.argv[2]),int(sys.argv[1])) tweet=dataStream.map(tmp) septweet=tweet.flatMap(forf) count=septweet.reduceByKey(lambda x,y:x+y) sortcount = count.transform(lambda rdd :rdd.sortBy(lambda a:a[0],ascending=True)) sortcount = sortcount.transform(lambda rdd :rdd.sortBy(lambda a:a[1],ascending=False)) tweet1=sortcount.filter(lambda w:w[0] is not '') #tweet1.pprint() res = tweet1.map(lambda a : a[0]) res.foreachRDD(topprint) #TO maintain state # totalcount=tweet.updateStateByKey(aggregate_tweets_count) # totalcount.pprint() #To Perform operation on each RDD # totalcount.foreachRDD(process_rdd) ssc.start() ssc.awaitTermination(25) ssc.stop()
[ 11748, 1064, 2777, 668, 198, 19796, 2777, 668, 13, 15003, 3419, 198, 198, 6738, 279, 893, 20928, 1330, 17732, 18546, 11, 4561, 668, 21947, 198, 6738, 279, 893, 20928, 13, 5532, 278, 1330, 43124, 21947, 198, 6738, 279, 893, 20928, 13, ...
2.484393
865
# Generated by Django 4.0.1 on 2022-01-20 13:10 import courses.fields from django.db import migrations
[ 2, 2980, 515, 416, 37770, 604, 13, 15, 13, 16, 319, 33160, 12, 486, 12, 1238, 1511, 25, 940, 198, 198, 11748, 10902, 13, 25747, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 628 ]
3
35
#Atoi stands for ASCII to Integer Conversion #Adjustment contains rule of three for calculating an integer given another integer representing a percentage
[ 2, 32, 1462, 72, 6296, 329, 37101, 284, 34142, 44101, 198, 198, 2, 39668, 434, 4909, 3896, 286, 1115, 329, 26019, 281, 18253, 1813, 1194, 18253, 10200, 257, 5873, 198 ]
5.2
30
#!/usr/bin/python # Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless 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 for retrieving and modifying configuration settings.""" import os import textwrap from google_compute_engine import file_utils from google_compute_engine.compat import parser CONFIG = '/etc/default/instance_configs.cfg'
[ 2, 48443, 14629, 14, 8800, 14, 29412, 198, 2, 15069, 1584, 3012, 3457, 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, 407, 779, 428...
3.837104
221
################################################## # ./AppService_services.py # generated by ZSI.wsdl2python # # ################################################## from .AppService_services_types import * from .AppService_services_types import \ nbcr_sdsc_edu_opal_types as ns1 import urllib.parse, types from ZSI.TCcompound import Struct from ZSI import client import ZSI
[ 29113, 14468, 2235, 220, 198, 2, 24457, 4677, 16177, 62, 30416, 13, 9078, 220, 198, 2, 7560, 416, 1168, 11584, 13, 18504, 25404, 17, 29412, 220, 198, 2, 220, 198, 2, 220, 198, 29113, 14468, 2235, 628, 198, 6738, 764, 4677, 16177, 62...
3.527273
110
# Copyright (c) 2020-2022, 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. import sys import argparse import re import numpy as np import torch ACTIVATION_AMAX_NUM = 72 INT8O_KERNEL_NUM = 5 INT8O_GEMM_NUM = 7 TRT_FUSED_MHA_AMAX_NUM = 3 SCALE_RESERVE_NUM = 8 if __name__ == '__main__': weights = torch.load('pytorch_model.bin') extract_amaxlist(weights, [2, 2, 6, 2])
[ 2, 15069, 357, 66, 8, 12131, 12, 1238, 1828, 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...
3.090909
297
# -*- coding: utf-8 -*- # Copyright 1999-2020 Alibaba Group Holding Ltd. # # 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. import logging import os import random import time from ...actors import new_client, FunctionActor logger = logging.getLogger(__name__)
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 15069, 7358, 12, 42334, 41992, 4912, 31703, 12052, 13, 198, 2, 198, 2, 49962, 739, 262, 24843, 13789, 11, 10628, 362, 13, 15, 357, 1169, 366, 34156, 15341, 198, 2, ...
3.628571
210
from unittest import TestCase import torch import transformers from model.bert_model import BertModel
[ 6738, 555, 715, 395, 1330, 6208, 20448, 198, 11748, 28034, 198, 198, 11748, 6121, 364, 198, 198, 6738, 2746, 13, 4835, 62, 19849, 1330, 22108, 17633, 628 ]
3.888889
27
import json import os import tempfile from unittest import TestCase import pytest from donjuan import Dungeon, DungeonRandomizer, Renderer
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 20218, 7753, 198, 6738, 555, 715, 395, 1330, 6208, 20448, 198, 198, 11748, 12972, 9288, 198, 198, 6738, 836, 73, 7258, 1330, 11995, 11, 11995, 29531, 7509, 11, 28703, 11882, 628 ]
3.736842
38
"""Spinnaker validate functions.""" import logging from .consts import API_URL from .utils.credentials import get_env_credential LOG = logging.getLogger(__name__) def validate_gate(): """Check Gate connection.""" try: credentials = get_env_credential() LOG.debug('Found credentials: %s', credentials) LOG.info('Gate working.') except TypeError: LOG.fatal('Gate connection not valid: API_URL = %s', API_URL) def validate_all(args): """Run all validate steps.""" LOG.debug('Args: %s', args) LOG.info('Running all validate steps.') validate_gate()
[ 37811, 4561, 3732, 3110, 26571, 5499, 526, 15931, 198, 11748, 18931, 198, 198, 6738, 764, 1102, 6448, 1330, 7824, 62, 21886, 198, 6738, 764, 26791, 13, 66, 445, 14817, 1330, 651, 62, 24330, 62, 66, 445, 1843, 198, 198, 25294, 796, 189...
2.744395
223
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-15 00:56 from __future__ import unicode_literals from django.conf import settings import django.contrib.postgres.fields.jsonb 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, 13, 21, 319, 2177, 12, 3070, 12, 1314, 3571, 25, 3980, 198, 6738, 11593, 37443, 834, 1330, 28000, 1098, 62, 17201, 874, 198, ...
2.891304
92
#!/usr/bin/env python # -*- coding: utf-8 -*- import sqlite3 as sqlite import os.path as osp import sys
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 11748, 44161, 578, 18, 355, 44161, 578, 198, 11748, 28686, 13, 6978, 355, 267, 2777, 198, 11748, 25064, 198 ]
2.47619
42
""" easy way to use losses """ from center_loss import Centerloss import torch.nn as nn from FocalLoss import FocalLoss
[ 37811, 198, 38171, 835, 284, 779, 9089, 198, 37811, 198, 6738, 3641, 62, 22462, 1330, 3337, 22462, 198, 11748, 28034, 13, 20471, 355, 299, 77, 198, 6738, 376, 4374, 43, 793, 1330, 376, 4374, 43, 793, 198 ]
3.243243
37
# Copyright 2016 Rackspace Australia # 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. import fixtures import jsonschema import os import requests from oslo_serialization import jsonutils from oslo_utils import uuidutils from nova import test from nova.tests import fixtures as nova_fixtures from nova.tests.functional import fixtures as func_fixtures from nova.tests.functional import integrated_helpers from nova.tests.unit.image import fake as fake_image real_request = requests.request
[ 2, 15069, 1584, 37927, 13200, 4505, 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.538983
295
import os import sys import json sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../bert"))) sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "../../"))) import tokenization from config import config if __name__=="__main__": DATA_INPUT_DIR = config.data_dir DATA_OUTPUT_DIR = "sequence_labeling_data" Vocab_Path = config.bert_vocab_dir General_Mode = False model_data = Model_data_preparation(General_Mode = General_Mode,DATA_INPUT_DIR=DATA_INPUT_DIR, DATA_OUTPUT_DIR=DATA_OUTPUT_DIR,vocab_file_path=Vocab_Path) model_data.separate_raw_data_and_token_labeling()
[ 11748, 28686, 198, 11748, 25064, 198, 11748, 33918, 198, 17597, 13, 6978, 13, 33295, 7, 418, 13, 6978, 13, 397, 2777, 776, 7, 418, 13, 6978, 13, 22179, 7, 418, 13, 6978, 13, 15908, 3672, 7, 834, 7753, 834, 828, 366, 40720, 40720, ...
2.496094
256
import typing # noqa from google.protobuf import descriptor from google.protobuf.json_format import _IsMapEntry, _Printer from google.protobuf.message import Message # noqa from clarifai.rest.grpc.proto.clarifai.api.utils import extensions_pb2
[ 11748, 19720, 220, 1303, 645, 20402, 198, 198, 6738, 23645, 13, 11235, 672, 3046, 1330, 43087, 198, 6738, 23645, 13, 11235, 672, 3046, 13, 17752, 62, 18982, 1330, 4808, 3792, 13912, 30150, 11, 4808, 6836, 3849, 198, 6738, 23645, 13, 112...
3.08642
81
from .capsulenet import *
[ 6738, 764, 27979, 377, 268, 316, 1330, 1635, 198 ]
2.888889
9
#!/usr/bin/env python # # -*- coding: utf-8 -*- # # Copyright (c) 2018 JiNong, Inc. # All right reserved. # import struct import time import socket import select import traceback import hashlib import json from enum import IntEnum from threading import Thread, Lock from mate import Mate, ThreadMate, DevType from mblock import MBlock, BlkType, StatCode, ResCode, CmdCode, Observation, Request, Response, NotiCode, Notice from pymodbus.client.sync import ModbusSerialClient from pymodbus.client.sync import ModbusTcpClient if __name__ == "__main__": isnutri = False opt = { 'conn' : [{ 'method': 'rtu', 'port' : '/dev/ttyJND2', 'baudrate' : 9600, 'timeout': 5 }] } nutriinfo = [{ "id" : "1", "dk" : "", "dt": "gw", "children" : [{ "id" : "101", "dk" : '[1,40201,["status"],45001,["operation","opid"]]', "dt": "nd", "children" : [ {"id" : "102", "dk" : '[1,40211,["control","status","area","alert","opid"],45001,["operation", "opid", "control","EC","pH", "start-area", "stop-area", "on-sec"]]', "dt": "nutrient-supply/level1"}, {"id" : "103", "dk" : '[1,40221,["value","status"]]', "dt": "sen"}, {"id" : "104", "dk" : '[1,40231,["value","status"]]', "dt": "sen"}, {"id" : "105", "dk" : '[1,40241,["value","status"]]', "dt": "sen"}, {"id" : "106", "dk" : '[1,40251,["value","status"]]', "dt": "sen"}, {"id" : "107", "dk" : '[1,40261,["value","status"]]', "dt": "sen"}, {"id" : "109", "dk" : '[1,40271,["value","status"]]', "dt": "sen"}, {"id" : "110", "dk" : '[1,40281,["value","status"]]', "dt": "sen"}, {"id" : "111", "dk" : '[1,40291,["value","status"]]', "dt": "sen"}, {"id" : "112", "dk" : '[1,40301,["value","status"]]', "dt": "sen"}, {"id" : "113", "dk" : '[1,40311,["value","status"]]', "dt": "sen"} ]} ]} ] devinfo = [{ "id" : "1", "dk" : "JND2", "dt": "gw", "children" : [ # { # "id" : "101", "dk" : '[1,201,["status"],301,["operation","opid"]]', "dt": "nd", "children" : [ #{"id" : "102", "dk" : '[1,210,["value","status"]]', "dt": "sen"}, #{"id" : "103", "dk" : '[1,220,["value","status"]]', "dt": "sen"} # "id" : "101", "dk" : '[1,40201,["status"],45001,["operation","opid"]]', "dt": "nd", "children" : [ #{"id" : "102", "dk" : '[1,41010,["value","status"]]', "dt": "sen"}, #{"id" : "103", "dk" : '[1,41020,["value","status"]]', "dt": "sen"} # {"id" : "102", "dk" : '[1,40202,["value","status"]]', "dt": "sen"}, # {"id" : "103", "dk" : '[1,40205,["value","status"]]', "dt": "sen"}, #{"id" : "104", "dk" : '[1,40208,["value","status"]]', "dt": "sen"}, # {"id" : "105", "dk" : '[1,40211,["value","status"]]', "dt": "sen"}, #{"id" : "106", "dk" : '[1,40251,["value","status"]]', "dt": "sen"}, #{"id" : "107", "dk" : '[1,40261,["value","status"]]', "dt": "sen"}, #{"id" : "108", "dk" : '[1,40271,["value","status"]]', "dt": "sen"}, #{"id" : "109", "dk" : '[1,40281,["value","status"]]', "dt": "sen"}, #{"id" : "110", "dk" : '[1,40291,["value","status"]]', "dt": "sen"} # ] # } ] }] """ }, { "id" : "201", "dk" : '[2,40201,["status"],45001,["operation","opid"]]', "dt": "nd", "children" : [ {"id" : "202", "dk" : '[2,40202,["opid","status","state-hold-time","remain-time"],40206,["operation","opid","time"]]', "dt": "act/retractable/level1"}, {"id" : "202", "dk" : '[2,40209,["opid","status","state-hold-time","remain-time"],40213,["operation","opid","time"]]', "dt": "act/retractable/level1"}, {"id" : "203", "dk" : '[2,40216,["value","status"]]', "dt": "sen"}, {"id" : "204", "dk" : '[2,40219,["value","status"]]', "dt": "sen"}, #{"id" : "203", "dk" : (2,40221,["opid","status"],45021,["operation","opid"]), "dt": "act/switch/level0"}, #{"id" : "204", "dk" : (2,40231,["opid","status"],45031,["operation","opid"]), "dt": "act/switch/level0"}, #{"id" : "205", "dk" : (2,40241,["opid","status"],45041,["operation","opid"]), "dt": "act/switch/level0"}, #{"id" : "206", "dk" : (2,40251,["opid","status"],45051,["operation","opid"]), "dt": "act/switch/level0"}, #{"id" : "207", "dk" : (2,40261,["opid","status"],45061,["operation","opid"]), "dt": "act/switch/level0"}, #{"id" : "208", "dk" : (2,40271,["opid","status"],45071,["operation","opid"]), "dt": "act/switch/level0"}, #{"id" : "209", "dk" : (2,40281,["opid","status"],45081,["operation","opid"]), "dt": "act/switch/level0"} ] }, { "id" : "301", "dk" : (3,40201,["opid","status"],45001,["operation","opid"]), "dt": "nd", "children" : [ {"id" : "302", "dk" : (3,40211,["opid","status"],45011,["operation","opid"]), "dt": "act/retractable/level0"}, {"id" : "303", "dk" : (3,40221,["opid","status"],45021,["operation","opid"]), "dt": "act/retractable/level0"}, {"id" : "304", "dk" : (3,40231,["opid","status"],45031,["operation","opid"]), "dt": "act/retractable/level0"}, {"id" : "305", "dk" : (3,40241,["opid","status"],45041,["operation","opid"]), "dt": "act/retractable/level0"} ] }] }] """ if isnutri: kdmate = KSX3267MateV2(opt, nutriinfo, "1", None) else: kdmate = KSX3267MateV2(opt, devinfo, "1", None) mate = Mate ({}, [], "1", None) kdmate.start (mate.writeblk) print "mate started" time.sleep(10) req = Request(None) req.setcommand("1", CmdCode.DETECT_DEVICE, None) print "=======================================#1" kdmate.writeblk(req) print "=======================================#1" """ time.sleep(1) req = Request(None) req.setcommand("1", CmdCode.CANCEL_DETECT, {}) print "=======================================#2" kdmate.writeblk(req) print "=======================================#2" time.sleep(1) req = Request(None) req.setcommand("1", CmdCode.DETECT_DEVICE, None) print "=======================================#3" kdmate.writeblk(req) print "=======================================#3" time.sleep(1) req = Request(None) req.setcommand("1", CmdCode.CANCEL_DETECT, {}) print "=======================================#4" kdmate.writeblk(req) print "=======================================#4" time.sleep(10) req = Request(201) req.setcommand(202, CmdCode.OPEN, {}) kdmate.writeblk(req) time.sleep(5) req = Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) time.sleep(10) req = Request(201) req.setcommand(202, CmdCode.TIMED_OPEN, {"time":10}) kdmate.writeblk(req) time.sleep(15) req = Request(201) req.setcommand(202, CmdCode.TIMED_CLOSE, {"time":10}) kdmate.writeblk(req) time.sleep(5) req = Request(201) req.setcommand(202, CmdCode.OFF, {}) kdmate.writeblk(req) """ time.sleep(30) kdmate.stop() print "mate stopped"
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 198, 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 357, 66, 8, 2864, 29380, 45, 506, 11, 3457, 13, 198, 2, 1439, 826, 10395, 13, 198, 2, ...
2.057087
3,591
import demjson import sys from subprocess import Popen, PIPE import subprocess import xml.etree.ElementTree as ET import os from datetime import datetime from functions import runcommand #from sets import Set #run test ########################## main function ############################### # a command will like if (len(sys.argv) < 3 or sys.argv[1] == '-h' or sys.argv[1] == '-h') : print("Usage: \r\n {0} <integrationTestsConfiguration json file path> <test result location> <group name>".format(sys.argv[0])) ; exit(1) jsonfilename=sys.argv[1] test_result_folder=sys.argv[2] group_name = sys.argv[3] destination = sys.argv[4] derivedDataPath = sys.argv[5] with open(jsonfilename, 'r') as jsonfile: jsonstring = jsonfile.read() testConfigure = demjson.decode(jsonstring) runningConfigure = testConfigure['runningConfigure'] projectName = runningConfigure['projectName'] projectPath = runningConfigure['projectPath'] schemeName = runningConfigure['schemeName'] sdkName = runningConfigure['sdkName'] print("group name:", group_name) testgroup = testConfigure[group_name] testlist = testgroup['test_list'] if 'projectName' in testgroup.keys() : projectName = testgroup['projectName'] if 'projectPath' in testgroup.keys(): projectPath = testgroup['projectPath'] if 'schemeName' in testgroup.keys(): schemeName = testgroup['schemeName'] print("projectName, projectPath, schemeName, destination", projectName, projectPath, schemeName, destination) # testcommandhead = f"xcodebuild test-without-building -project {projectName} -scheme {schemeName} -sdk {sdkName} -destination 'platform={paltformName},name={deviceName},OS={osVersion}'" # testcommandtail = " | tee raw.log | xcpretty -r junit | tee xcpretty.log" runcommand('echo "export testresult=0" >> $BASH_ENV') testresult = 0 for testname in testlist: print("-------------------------------", testname , "-------------------------------"); test = testlist[testname] testarguments = ' -only-testing:' + testname #create skipping tests parameters skipingtests = "" if 'excludetests' in test: for skipingtest in test['excludetests']: skipingtests += ' -skip-testing:' + testname+ "/" + skipingtest print("excludetests:", skipingtests) exit_code = runtest(testarguments + skipingtests, projectPath, schemeName, projectName, destination, derivedDataPath) print(testname, "exit code:", exit_code) # if test fails, check if the failed tests can be retried if exit_code == 65: retriabletimes = 3 ; if 'retriabletimes' in test: retriabletimes = test['retriabletimes'] if retriabletimes > 1: #get all failed test cases faileds = getfailedcases() if len(faileds) == 0 : print("test command return an error code, but the failed test cases is 0") print("exit code:", exit_code) break; print("failed tests:",faileds) retrytimes = 1 print('retriabletimes:', retriabletimes) while retrytimes <= retriabletimes and exit_code > 0: print("retry ", testname, "for ", retrytimes, " times") testarguments = "" for failed in faileds: testarguments += ' -only-testing:' + failed retrytimes += 1 exit_code = runtest(testarguments,projectPath, schemeName, projectName, destination, derivedDataPath); print("retry exit code:", exit_code) if(exit_code != 0 ): faileds = getfailedcases() if exit_code != 0 : print("exit code:", exit_code) runcommand('mkdir -p {0}/{1}'.format(test_result_folder,testname)) runcommand('echo "{2}" >> {0}/{1}/exitcode.log'.format(test_result_folder,testname,exit_code)) runcommand('mv raw.log {0}/{1}/raw.log'.format(test_result_folder,testname)) runcommand('mv xcpretty.log {0}/{1}/xcpretty.log'.format(test_result_folder,testname)) runcommand('cp build/reports/junit.xml {0}/{1}/junit.xml'.format(test_result_folder,testname)) ignorefailure = False ; if exit_code == 65 : failedtests = getfailedcases(False) print("failedtests:", failedtests) if 'ignoreFailures' in test and failedtests : ignoreFailures = set(test['ignoreFailures']) if failedtests.issubset(ignoreFailures): print("There are failed testcases that can be ignored") ignorefailure = True; else : print("Failed testcases that cannot be ignored: ", failedtests - ignoreFailures ) if not ignorefailure: print("There are faillures in the test") testresult = 1 else: print("Test succeed") print("testresult:", testresult) runcommand('echo "export testresult={0}" >> $BASH_ENV'.format(testresult))
[ 11748, 1357, 17752, 198, 11748, 25064, 198, 6738, 850, 14681, 1330, 8099, 268, 11, 350, 4061, 36, 198, 11748, 850, 14681, 198, 11748, 35555, 13, 316, 631, 13, 20180, 27660, 355, 12152, 198, 11748, 28686, 198, 6738, 4818, 8079, 1330, 481...
2.460979
2,063
# flake8: noqa: F401 from .context_manager_hook import ContextManagerHook from .counter_hook import CounterHook from .file_open_hook import FileOpenHook from .logging_hook import LoggingHook from .profiler_hook import ProfilerHook from .runtime_audit_hook import RuntimeAuditHook from .stack_trace_hook import StackTraceHook from .timer_hook import TimerHook from .tracing_hook import TracingHook __all__ = [ "CounterHook", "FileOpenHook", "LoggingHook", "ProfilerHook", "StackTraceHook", "RuntimeAuditHook", "TimerHook", "TracingHook", ]
[ 2, 781, 539, 23, 25, 645, 20402, 25, 376, 21844, 198, 6738, 764, 22866, 62, 37153, 62, 25480, 1330, 30532, 13511, 39, 566, 198, 6738, 764, 24588, 62, 25480, 1330, 15034, 39, 566, 198, 6738, 764, 7753, 62, 9654, 62, 25480, 1330, 9220...
2.698113
212
import pytest import numpy as np import pandas as pd from hypothetical._lib import _build_des_mat
[ 11748, 12972, 9288, 198, 11748, 299, 32152, 355, 45941, 198, 11748, 19798, 292, 355, 279, 67, 198, 6738, 25345, 13557, 8019, 1330, 4808, 11249, 62, 8906, 62, 6759, 628, 628 ]
3.366667
30
#!/usr/bin/env python3 # Copyright (c) 2017 Computer Vision Center (CVC) at the Universitat Autonoma de # Barcelona (UAB). # # This work is licensed under the terms of the MIT license. # For a copy, see <https://opensource.org/licenses/MIT>. """Download big files from Google Drive.""" import shutil import sys import requests import os import time import urllib.request import zipfile if __name__ == '__main__': download_contents()
[ 2, 48443, 14629, 14, 8800, 14, 24330, 21015, 18, 198, 198, 2, 15069, 357, 66, 8, 2177, 13851, 19009, 3337, 357, 34, 15922, 8, 379, 262, 26986, 270, 265, 5231, 261, 6086, 390, 198, 2, 15142, 357, 52, 6242, 737, 198, 2, 198, 2, 77...
3.217391
138
# -*- coding: utf-8 -*- """ """ import time import tkinter import tkinter.messagebox if __name__ == '__main__': main()
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 201, 198, 37811, 201, 198, 201, 198, 37811, 201, 198, 11748, 640, 201, 198, 11748, 256, 74, 3849, 201, 198, 11748, 256, 74, 3849, 13, 20500, 3524, 201, 198, 201, 198, 201, ...
2.014085
71
""" GitLab webhook receiver - see http://doc.gitlab.com/ee/web_hooks/web_hooks.html """ import asyncio import json import logging from sinks.base_bot_request_handler import AsyncRequestHandler logger = logging.getLogger(__name__) try: import dateutil.parser except ImportError: logger.error("missing module python_dateutil: pip3 install python_dateutil") raise
[ 37811, 198, 38, 270, 17822, 3992, 25480, 9733, 532, 766, 2638, 1378, 15390, 13, 18300, 23912, 13, 785, 14, 1453, 14, 12384, 62, 25480, 82, 14, 12384, 62, 25480, 82, 13, 6494, 198, 37811, 198, 198, 11748, 30351, 952, 198, 11748, 33918,...
3.040323
124
from evsim.system_simulator import SystemSimulator from evsim.behavior_model_executor import BehaviorModelExecutor from evsim.system_message import SysMessage from evsim.definition import * import os import subprocess as sp
[ 6738, 819, 14323, 13, 10057, 62, 14323, 8927, 1330, 4482, 8890, 8927, 201, 198, 6738, 819, 14323, 13, 46571, 62, 19849, 62, 18558, 38409, 1330, 20181, 17633, 23002, 38409, 201, 198, 6738, 819, 14323, 13, 10057, 62, 20500, 1330, 311, 893...
3.553846
65
import os from typing import Union, List from tei_entity_enricher.interface.postprocessing.io import FileReader, FileWriter from tei_entity_enricher.util.helper import local_save_path, makedir_if_necessary from tei_entity_enricher.util.exceptions import FileNotFound
[ 11748, 28686, 201, 198, 6738, 19720, 1330, 4479, 11, 7343, 201, 198, 6738, 573, 72, 62, 26858, 62, 268, 1173, 372, 13, 39994, 13, 7353, 36948, 13, 952, 1330, 9220, 33634, 11, 9220, 34379, 201, 198, 6738, 573, 72, 62, 26858, 62, 268,...
3.113636
88
import logging logger = logging.getLogger(__name__) logger.addHandler(logging.NullHandler()) logger.level = logging.DEBUG
[ 11748, 18931, 198, 198, 6404, 1362, 796, 18931, 13, 1136, 11187, 1362, 7, 834, 3672, 834, 8, 198, 6404, 1362, 13, 2860, 25060, 7, 6404, 2667, 13, 35067, 25060, 28955, 198, 6404, 1362, 13, 5715, 796, 18931, 13, 30531 ]
3.128205
39
from args import get_argparser, parse_args, get_aligner, get_bbox if __name__ == '__main__': parser = get_argparser() args = parse_args(parser) a = get_aligner(args) bbox = get_bbox(args) for z in range(args.bbox_start[2], args.bbox_stop[2]): print('Rendering z={0}'.format(z)) render(a, bbox, z)
[ 6738, 26498, 1330, 651, 62, 853, 48610, 11, 21136, 62, 22046, 11, 651, 62, 31494, 263, 11, 651, 62, 65, 3524, 220, 198, 198, 361, 11593, 3672, 834, 6624, 705, 834, 12417, 834, 10354, 198, 220, 30751, 796, 651, 62, 853, 48610, 3419, ...
2.360294
136
# -*- coding: utf-8 -*- # # Copyright 2020 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://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. """Accesses the google.spanner.admin.instance.v1 InstanceAdmin API.""" import functools import pkg_resources import warnings from google.oauth2 import service_account import google.api_core.client_options import google.api_core.gapic_v1.client_info import google.api_core.gapic_v1.config import google.api_core.gapic_v1.method import google.api_core.gapic_v1.routing_header import google.api_core.grpc_helpers import google.api_core.operation import google.api_core.operations_v1 import google.api_core.page_iterator import google.api_core.path_template import grpc from google.cloud.spanner_admin_instance_v1.gapic import enums from google.cloud.spanner_admin_instance_v1.gapic import instance_admin_client_config from google.cloud.spanner_admin_instance_v1.gapic.transports import ( instance_admin_grpc_transport, ) from google.cloud.spanner_admin_instance_v1.proto import spanner_instance_admin_pb2 from google.cloud.spanner_admin_instance_v1.proto import spanner_instance_admin_pb2_grpc from google.iam.v1 import iam_policy_pb2 from google.iam.v1 import options_pb2 from google.iam.v1 import policy_pb2 from google.longrunning import operations_pb2 from google.protobuf import empty_pb2 from google.protobuf import field_mask_pb2 _GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution("google-cloud-spanner").version # Service calls def create_instance( self, parent, instance_id, instance, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Creates an instance and begins preparing it to begin serving. The returned ``long-running operation`` can be used to track the progress of preparing the new instance. The instance name is assigned by the caller. If the named instance already exists, ``CreateInstance`` returns ``ALREADY_EXISTS``. Immediately upon completion of this request: - The instance is readable via the API, with all requested attributes but no allocated resources. Its state is ``CREATING``. Until completion of the returned operation: - Cancelling the operation renders the instance immediately unreadable via the API. - The instance can be deleted. - All other attempts to modify the instance are rejected. Upon completion of the returned operation: - Billing for all successfully-allocated resources begins (some types may have lower than the requested levels). - Databases can be created in the instance. - The instance's allocated resource levels are readable via the API. - The instance's state becomes ``READY``. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track creation of the instance. The ``metadata`` field type is ``CreateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # TODO: Initialize `instance_id`: >>> instance_id = '' >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> response = client.create_instance(parent, instance_id, instance) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: parent (str): Required. The name of the project in which to create the instance. Values are of the form ``projects/<project>``. instance_id (str): Required. The ID of the instance to create. Valid identifiers are of the form ``[a-z][-a-z0-9]*[a-z0-9]`` and must be between 2 and 64 characters in length. instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to create. The name may be omitted, but if specified must be ``<parent>/instances/<instance_id>``. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.api_core.operation.Operation` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "create_instance" not in self._inner_api_calls: self._inner_api_calls[ "create_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.create_instance, default_retry=self._method_configs["CreateInstance"].retry, default_timeout=self._method_configs["CreateInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.CreateInstanceRequest( parent=parent, instance_id=instance_id, instance=instance ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["create_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, spanner_instance_admin_pb2.Instance, metadata_type=spanner_instance_admin_pb2.CreateInstanceMetadata, ) def update_instance( self, instance, field_mask, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Updates an instance, and begins allocating or releasing resources as requested. The returned ``long-running operation`` can be used to track the progress of updating the instance. If the named instance does not exist, returns ``NOT_FOUND``. Immediately upon completion of this request: - For resource types for which a decrease in the instance's allocation has been requested, billing is based on the newly-requested level. Until completion of the returned operation: - Cancelling the operation sets its metadata's ``cancel_time``, and begins restoring resources to their pre-request values. The operation is guaranteed to succeed at undoing all resource changes, after which point it terminates with a ``CANCELLED`` status. - All other attempts to modify the instance are rejected. - Reading the instance via the API continues to give the pre-request resource levels. Upon completion of the returned operation: - Billing begins for all successfully-allocated resources (some types may have lower than the requested levels). - All newly-reserved resources are available for serving the instance's tables. - The instance's new resource levels are readable via the API. The returned ``long-running operation`` will have a name of the format ``<instance_name>/operations/<operation_id>`` and can be used to track the instance modification. The ``metadata`` field type is ``UpdateInstanceMetadata``. The ``response`` field type is ``Instance``, if successful. Authorization requires ``spanner.instances.update`` permission on resource ``name``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `instance`: >>> instance = {} >>> >>> # TODO: Initialize `field_mask`: >>> field_mask = {} >>> >>> response = client.update_instance(instance, field_mask) >>> >>> def callback(operation_future): ... # Handle result. ... result = operation_future.result() >>> >>> response.add_done_callback(callback) >>> >>> # Handle metadata. >>> metadata = response.metadata() Args: instance (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Instance]): Required. The instance to update, which must always include the instance name. Otherwise, only fields mentioned in ``field_mask`` need be included. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` field_mask (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.FieldMask]): Required. A mask specifying which fields in ``Instance`` should be updated. The field mask must always be specified; this prevents any future fields in ``Instance`` from being erased accidentally by clients that do not know about them. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.api_core.operation.Operation` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "update_instance" not in self._inner_api_calls: self._inner_api_calls[ "update_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.update_instance, default_retry=self._method_configs["UpdateInstance"].retry, default_timeout=self._method_configs["UpdateInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.UpdateInstanceRequest( instance=instance, field_mask=field_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("instance.name", instance.name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) operation = self._inner_api_calls["update_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) return google.api_core.operation.from_gapic( operation, self.transport._operations_client, spanner_instance_admin_pb2.Instance, metadata_type=spanner_instance_admin_pb2.UpdateInstanceMetadata, ) def list_instance_configs( self, parent, page_size=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists the supported instance configurations for a given project. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # Iterate over all results >>> for element in client.list_instance_configs(parent): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_instance_configs(parent).pages: ... for element in page: ... # process element ... pass Args: parent (str): Required. The name of the project for which a list of supported instance configurations is requested. Values are of the form ``projects/<project>``. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.api_core.page_iterator.PageIterator` instance. An iterable of :class:`~google.cloud.spanner_admin_instance_v1.types.InstanceConfig` instances. You can also iterate over the pages of the response using its `pages` property. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "list_instance_configs" not in self._inner_api_calls: self._inner_api_calls[ "list_instance_configs" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_instance_configs, default_retry=self._method_configs["ListInstanceConfigs"].retry, default_timeout=self._method_configs["ListInstanceConfigs"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.ListInstanceConfigsRequest( parent=parent, page_size=page_size ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_instance_configs"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="instance_configs", request_token_field="page_token", response_token_field="next_page_token", ) return iterator def get_instance_config( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets information about a particular instance configuration. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> name = client.instance_config_path('[PROJECT]', '[INSTANCE_CONFIG]') >>> >>> response = client.get_instance_config(name) Args: name (str): Required. The name of the requested instance configuration. Values are of the form ``projects/<project>/instanceConfigs/<config>``. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.InstanceConfig` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_instance_config" not in self._inner_api_calls: self._inner_api_calls[ "get_instance_config" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_instance_config, default_retry=self._method_configs["GetInstanceConfig"].retry, default_timeout=self._method_configs["GetInstanceConfig"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.GetInstanceConfigRequest(name=name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["get_instance_config"]( request, retry=retry, timeout=timeout, metadata=metadata ) def list_instances( self, parent, page_size=None, filter_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Lists all instances in the given project. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> parent = client.project_path('[PROJECT]') >>> >>> # Iterate over all results >>> for element in client.list_instances(parent): ... # process element ... pass >>> >>> >>> # Alternatively: >>> >>> # Iterate over results one page at a time >>> for page in client.list_instances(parent).pages: ... for element in page: ... # process element ... pass Args: parent (str): Required. The name of the project for which a list of instances is requested. Values are of the form ``projects/<project>``. page_size (int): The maximum number of resources contained in the underlying API response. If page streaming is performed per- resource, this parameter does not affect the return value. If page streaming is performed per-page, this determines the maximum number of resources in a page. filter_ (str): An expression for filtering the results of the request. Filter rules are case insensitive. The fields eligible for filtering are: - ``name`` - ``display_name`` - ``labels.key`` where key is the name of a label Some examples of using filters are: - ``name:*`` --> The instance has a name. - ``name:Howl`` --> The instance's name contains the string "howl". - ``name:HOWL`` --> Equivalent to above. - ``NAME:howl`` --> Equivalent to above. - ``labels.env:*`` --> The instance has the label "env". - ``labels.env:dev`` --> The instance has the label "env" and the value of the label contains the string "dev". - ``name:howl labels.env:dev`` --> The instance's name contains "howl" and it has the label "env" with its value containing "dev". retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.api_core.page_iterator.PageIterator` instance. An iterable of :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` instances. You can also iterate over the pages of the response using its `pages` property. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "list_instances" not in self._inner_api_calls: self._inner_api_calls[ "list_instances" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.list_instances, default_retry=self._method_configs["ListInstances"].retry, default_timeout=self._method_configs["ListInstances"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.ListInstancesRequest( parent=parent, page_size=page_size, filter=filter_ ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("parent", parent)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) iterator = google.api_core.page_iterator.GRPCIterator( client=None, method=functools.partial( self._inner_api_calls["list_instances"], retry=retry, timeout=timeout, metadata=metadata, ), request=request, items_field="instances", request_token_field="page_token", response_token_field="next_page_token", ) return iterator def get_instance( self, name, field_mask=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets information about a particular instance. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> name = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> response = client.get_instance(name) Args: name (str): Required. The name of the requested instance. Values are of the form ``projects/<project>/instances/<instance>``. field_mask (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.FieldMask]): If field_mask is present, specifies the subset of ``Instance`` fields that should be returned. If absent, all ``Instance`` fields are returned. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.FieldMask` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.Instance` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_instance" not in self._inner_api_calls: self._inner_api_calls[ "get_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_instance, default_retry=self._method_configs["GetInstance"].retry, default_timeout=self._method_configs["GetInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.GetInstanceRequest( name=name, field_mask=field_mask ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["get_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) def delete_instance( self, name, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Deletes an instance. Immediately upon completion of the request: - Billing ceases for all of the instance's reserved resources. Soon afterward: - The instance and *all of its databases* immediately and irrevocably disappear from the API. All data in the databases is permanently deleted. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> name = client.instance_path('[PROJECT]', '[INSTANCE]') >>> >>> client.delete_instance(name) Args: name (str): Required. The name of the instance to be deleted. Values are of the form ``projects/<project>/instances/<instance>`` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "delete_instance" not in self._inner_api_calls: self._inner_api_calls[ "delete_instance" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.delete_instance, default_retry=self._method_configs["DeleteInstance"].retry, default_timeout=self._method_configs["DeleteInstance"].timeout, client_info=self._client_info, ) request = spanner_instance_admin_pb2.DeleteInstanceRequest(name=name) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("name", name)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) self._inner_api_calls["delete_instance"]( request, retry=retry, timeout=timeout, metadata=metadata ) def set_iam_policy( self, resource, policy, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Sets the access control policy on an instance resource. Replaces any existing policy. Authorization requires ``spanner.instances.setIamPolicy`` on ``resource``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `resource`: >>> resource = '' >>> >>> # TODO: Initialize `policy`: >>> policy = {} >>> >>> response = client.set_iam_policy(resource, policy) Args: resource (str): REQUIRED: The resource for which the policy is being specified. See the operation documentation for the appropriate value for this field. policy (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.Policy]): REQUIRED: The complete policy to be applied to the ``resource``. The size of the policy is limited to a few 10s of KB. An empty policy is a valid policy but certain Cloud Platform services (such as Projects) might reject them. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.Policy` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.Policy` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "set_iam_policy" not in self._inner_api_calls: self._inner_api_calls[ "set_iam_policy" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.set_iam_policy, default_retry=self._method_configs["SetIamPolicy"].retry, default_timeout=self._method_configs["SetIamPolicy"].timeout, client_info=self._client_info, ) request = iam_policy_pb2.SetIamPolicyRequest(resource=resource, policy=policy) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("resource", resource)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["set_iam_policy"]( request, retry=retry, timeout=timeout, metadata=metadata ) def get_iam_policy( self, resource, options_=None, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Gets the access control policy for an instance resource. Returns an empty policy if an instance exists but does not have a policy set. Authorization requires ``spanner.instances.getIamPolicy`` on ``resource``. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `resource`: >>> resource = '' >>> >>> response = client.get_iam_policy(resource) Args: resource (str): REQUIRED: The resource for which the policy is being requested. See the operation documentation for the appropriate value for this field. options_ (Union[dict, ~google.cloud.spanner_admin_instance_v1.types.GetPolicyOptions]): OPTIONAL: A ``GetPolicyOptions`` object for specifying options to ``GetIamPolicy``. This field is only used by Cloud IAM. If a dict is provided, it must be of the same form as the protobuf message :class:`~google.cloud.spanner_admin_instance_v1.types.GetPolicyOptions` retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.Policy` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "get_iam_policy" not in self._inner_api_calls: self._inner_api_calls[ "get_iam_policy" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.get_iam_policy, default_retry=self._method_configs["GetIamPolicy"].retry, default_timeout=self._method_configs["GetIamPolicy"].timeout, client_info=self._client_info, ) request = iam_policy_pb2.GetIamPolicyRequest( resource=resource, options=options_ ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("resource", resource)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["get_iam_policy"]( request, retry=retry, timeout=timeout, metadata=metadata ) def test_iam_permissions( self, resource, permissions, retry=google.api_core.gapic_v1.method.DEFAULT, timeout=google.api_core.gapic_v1.method.DEFAULT, metadata=None, ): """ Returns permissions that the caller has on the specified instance resource. Attempting this RPC on a non-existent Cloud Spanner instance resource will result in a NOT_FOUND error if the user has ``spanner.instances.list`` permission on the containing Google Cloud Project. Otherwise returns an empty set of permissions. Example: >>> from google.cloud import spanner_admin_instance_v1 >>> >>> client = spanner_admin_instance_v1.InstanceAdminClient() >>> >>> # TODO: Initialize `resource`: >>> resource = '' >>> >>> # TODO: Initialize `permissions`: >>> permissions = [] >>> >>> response = client.test_iam_permissions(resource, permissions) Args: resource (str): REQUIRED: The resource for which the policy detail is being requested. See the operation documentation for the appropriate value for this field. permissions (list[str]): The set of permissions to check for the ``resource``. Permissions with wildcards (such as '*' or 'storage.*') are not allowed. For more information see `IAM Overview <https://cloud.google.com/iam/docs/overview#permissions>`__. retry (Optional[google.api_core.retry.Retry]): A retry object used to retry requests. If ``None`` is specified, requests will be retried using a default configuration. timeout (Optional[float]): The amount of time, in seconds, to wait for the request to complete. Note that if ``retry`` is specified, the timeout applies to each individual attempt. metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata that is provided to the method. Returns: A :class:`~google.cloud.spanner_admin_instance_v1.types.TestIamPermissionsResponse` instance. Raises: google.api_core.exceptions.GoogleAPICallError: If the request failed for any reason. google.api_core.exceptions.RetryError: If the request failed due to a retryable error and retry attempts failed. ValueError: If the parameters are invalid. """ # Wrap the transport method to add retry and timeout logic. if "test_iam_permissions" not in self._inner_api_calls: self._inner_api_calls[ "test_iam_permissions" ] = google.api_core.gapic_v1.method.wrap_method( self.transport.test_iam_permissions, default_retry=self._method_configs["TestIamPermissions"].retry, default_timeout=self._method_configs["TestIamPermissions"].timeout, client_info=self._client_info, ) request = iam_policy_pb2.TestIamPermissionsRequest( resource=resource, permissions=permissions ) if metadata is None: metadata = [] metadata = list(metadata) try: routing_header = [("resource", resource)] except AttributeError: pass else: routing_metadata = google.api_core.gapic_v1.routing_header.to_grpc_metadata( routing_header ) metadata.append(routing_metadata) return self._inner_api_calls["test_iam_permissions"]( request, retry=retry, timeout=timeout, metadata=metadata )
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 15069, 12131, 3012, 11419, 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...
2.279558
19,563
#/usr/bin/python __version__ = '1.0' __author__ = 'alastair.maxwell@glasgow.ac.uk' ## ## Imports import string import os import errno import shutil import sys import glob import datetime import subprocess import logging as log import numpy as np import csv from io import StringIO import PyPDF2 from sklearn import preprocessing from collections import defaultdict from xml.etree import cElementTree from lxml import etree from reportlab.pdfgen import canvas def parse_boolean(boolean_value): """ Given a string (boolean_value), returns a boolean value representing the string contents. For example, a string with 'true', 't', 'y' or 'yes' will yield True. """ boolean_value = string.lower(boolean_value) in ('yes', 'y', 'true', 't', '1') return boolean_value def empty_string_check(string, raise_exception=True): """ Simple check to see if the string provided by parameter string is empty. False indicates the string is NOT empty. Parameter raise_exception determines if a ValueError exception should be raised if the string is empty. If raise_exception is False and the string is empty, True is returned. """ if string != '': return False if raise_exception: raise ValueError("Empty string detected!") return True def sanitise_inputs(parsed_arguments): """ Utilises filesystem_exists_check and check_input_files if either return false, path is invalid or unsupported files present so, quit """ trigger = False ## ## Jobname prefix validity check if parsed_arguments.jobname: for character in parsed_arguments.jobname: if character is ' ' or character is '/': log.error('{}{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'Specified Job Name has invalid characters: "', character, '"')) trigger = True ## ## Config mode check if parsed_arguments.config: if not filesystem_exists_check(parsed_arguments.config[0]): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'Specified config file could not be found.')) trigger = True for xmlfile in parsed_arguments.config: if not check_input_files('.xml',xmlfile): log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'Specified config file is not an XML file.')) trigger = True return trigger def extract_data(input_data_directory): target_files = glob.glob(os.path.join(input_data_directory, '*')) for extract_target in target_files: if extract_target.lower().endswith(('.fq.gz', '.fastq.gz')): log.info('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Detected compressed input data. Extracting!')) break for extract_target in target_files: unzipd = subprocess.Popen(['gzip', '-q', '-f', '-d', extract_target], stderr=subprocess.PIPE) unzipd.wait() return True def sequence_pairings(data_path, instance_rundir): ## ## Get input files from data path ## Sort so that ordering isn't screwy on linux input_files = glob.glob(os.path.join(data_path, '*')) sorted_input = sorted(input_files) sequence_pairs = [] file_count = len(sorted_input) if not file_count % 2 == 0: log.error('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'I/O: Non-even number of input files specified. Cannot continue without pairing!')) sys.exit(2) ## ## Optimise so code isn't recycled for i in range(0, len(sorted_input), 2): file_pair = {} forward_data = sorted_input[i] reverse_data = sorted_input[i+1] ## ## Check forward ends with R1 forward_data_name = sorted_input[i].split('/')[-1].split('.')[0] if not forward_data_name.endswith('_R1'): log.error('{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'I/O: Forward input file does not end in _R1. ', forward_data)) sys.exit(2) ## ## Check reverse ends with R2 reverse_data_name = sorted_input[i+1].split('/')[-1].split('.')[0] if not reverse_data_name.endswith('_R2'): log.error('{}{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'I/O: Reverse input file does not end in _R2. ', reverse_data)) sys.exit(2) ## ## Make Stage outputs for use in everywhere else in pipeline sample_root = '_'.join(forward_data_name.split('_')[:-1]) instance_path = os.path.join(instance_rundir) seq_qc_path = os.path.join(instance_rundir, sample_root, 'SeqQC') align_path = os.path.join(instance_rundir, sample_root, 'Align') predict_path = os.path.join(instance_rundir, sample_root, 'Predict') file_pair[sample_root] = [forward_data, reverse_data, instance_path, seq_qc_path, align_path, predict_path] sequence_pairs.append(file_pair) return sequence_pairs def filesystem_exists_check(path, raise_exception=True): """ Checks to see if the path, specified by parameter path, exists. Can be either a directory or file. If the path exists, True is returned. If the path does not exist, and raise_exception is set to True, an IOError is raised - else False is returned. """ if os.path.lexists(path): return True if raise_exception: log.error('{}{}{}{}'.format(Colour.red,'shd__ ',Colour.end,'Specified input path could not be found.')) return False def check_input_files(input_format, input_file): if input_file.endswith(input_format): return True return False def initialise_libraries(instance_params): trigger = False ## ## Subfunction for recycling code ## Calls UNIX type for checking binaries present ## Changed from WHICH as apparently type functions over different shells/config files ## ## To determine which binaries to check for ## AttributeError in the situation where instance_params origin differs ## try for -c style, except AttributeError for -b style try: quality_control = instance_params.config_dict['instance_flags']['@quality_control'] alignment = instance_params.config_dict['instance_flags']['@sequence_alignment'] genotyping = instance_params.config_dict['instance_flags']['@genotype_prediction'] snp_calling = instance_params.config_dict['instance_flags']['@snp_calling'] except AttributeError: quality_control = instance_params['quality_control'] alignment = instance_params['sequence_alignment'] genotyping = instance_params['genotype_prediction'] snp_calling = instance_params['snp_calling'] if quality_control == 'True': try:type_func('java') except NameError: trigger=True try:type_func('fastqc') except NameError: trigger=True try:type_func('cutadapt') except NameError: trigger=True if alignment == 'True': try:type_func('seqtk') except NameError: trigger=True try:type_func('bwa') except NameError: trigger=True try:type_func('samtools') except NameError: trigger=True try:type_func('generatr') except NameError: trigger=True if genotyping == 'True': try:type_func('samtools') except NameError: trigger=True try:type_func('generatr') except NameError: trigger=True if snp_calling == 'True': try: type_func('picard') except NameError: trigger=True try: type_func('freebayes') except NameError: trigger=True return trigger def sanitise_outputs(jobname, output_argument): run_dir = '' output_root = output_argument[0] if jobname: target_output = os.path.join(output_root, jobname) if not os.path.exists(target_output): log.info('{}{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Creating Output with prefix: ', jobname)) run_dir = os.path.join(output_root, jobname) mkdir_p(run_dir) else: purge_choice = '' while True: purge_choice = input('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Job folder already exists. Delete existing folder? Y/N: ')) if not (purge_choice.lower() == 'y') and not (purge_choice.lower() == 'n'): log.info('{}{}{}{}'.format(Colour.red, 'shd__ ', Colour.end, 'Invalid input. Please input Y or N.')) continue else: break if purge_choice.lower() == 'y': log.info('{}{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Clearing pre-existing Jobname Prefix: ', jobname)) run_dir = os.path.join(output_root, jobname) if os.path.exists(run_dir): shutil.rmtree(run_dir, ignore_errors=True) mkdir_p(run_dir) else: raise Exception('User chose not to delete pre-existing Job folder. Cannot write output.') else: ## Ensures root output is a real directory ## Generates folder name based on date (for run ident) date = datetime.date.today().strftime('%d-%m-%Y') walltime = datetime.datetime.now().strftime('%H%M%S') today = date + '-' + walltime ## If the user specified root doesn't exist, make it ## Then make the run directory for datetime if not os.path.exists(output_root): log.info('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Creating output root... ')) mkdir_p(output_root) run_dir = os.path.join(output_root, 'ScaleHDRun_'+today) log.info('{}{}{}{}'.format(Colour.bold, 'shd__ ', Colour.end, 'Creating instance run directory.. ')) mkdir_p(run_dir) ## Inform user it's all gonna be okaaaayyyy log.info('{}{}{}{}'.format(Colour.green, 'shd__ ', Colour.end, 'Output directories OK!')) return run_dir def replace_fqfile(mutate_list, target_fqfile, altered_path): if target_fqfile in mutate_list: loc = mutate_list.index(target_fqfile) mutate_list[loc] = altered_path return mutate_list def scrape_summary_data(stage, input_report_file): ## ## If the argument input_report_file is from trimming.. if stage == 'trim': with open(input_report_file, 'r') as trpf: trim_lines = trpf.readlines() ## ## Determine buffer size to slice from above array scraping_buffer = 8 if '-q' in trim_lines[1]: scraping_buffer += 1 ## ## Get Anchor summary_start = 0 for i in range(0, len(trim_lines)): if '== Summary ==' in trim_lines[i]: summary_start = i ## ## Slice and close summary_data = trim_lines[summary_start:summary_start + scraping_buffer] trpf.close() return summary_data[2:] ## ## If the argument input_report_file is from alignment.. if stage == 'align': with open(input_report_file, 'r') as alnrpf: align_lines = alnrpf.readlines() alnrpf.close() ## ## No ranges required, only skip first line return align_lines[1:] ## ## No need to tidy up report for genotyping ## since we already have the data from our own objects if stage == 'gtype': pass def generate_atypical_xml(label, allele_object, index_path, direction): """ :param allele_object: :param index_path: :return: """ ##TODO docstring atypical_path = os.path.join(index_path, '{}{}_{}.xml'.format(direction, label, allele_object.get_reflabel())) fp_flank = 'GCGACCCTGGAAAAGCTGATGAAGGCCTTCGAGTCCCTCAAGTCCTTC' cagstart = ''; cagend = '' intv = allele_object.get_intervening() ccgstart = ''; ccgend = '' ccglen = allele_object.get_ccg() cctlen = allele_object.get_cct() tp_flank = 'CAGCTTCCTCAGCCGCCGCCGCAGGCACAGCCGCTGCT' if direction == 'fw': cagstart = '1'; cagend = '200' ccgstart = '1'; ccgend = '20' if direction == 'rv': cagstart = '100'; cagend = '100' ccgstart = '1'; ccgend = '20' ## ## Create XML data_root = etree.Element('data') loci_root = etree.Element('loci', label=allele_object.get_reflabel()); data_root.append(loci_root) ## ## Loci Nodes fp_input = etree.Element('input', type='fiveprime', flank=fp_flank) cag_region = etree.Element('input', type='repeat_region', order='1', unit='CAG', start=cagstart, end=cagend) intervening = etree.Element('input', type='intervening', sequence=intv, prior='1') ccg_region = etree.Element('input', type='repeat_region', order='2', unit='CCG', start=ccgstart, end=ccgend) cct_region = etree.Element('input', type='repeat_region', order='3', unit='CCT', start=str(cctlen), end=str(cctlen)) tp_input = etree.Element('input', type='threeprime', flank=tp_flank) for node in [fp_input, cag_region, intervening, ccg_region, cct_region, tp_input]: loci_root.append(node) s = etree.tostring(data_root, pretty_print=True) with open(atypical_path, 'w') as xmlfi: xmlfi.write(s.decode()) xmlfi.close() return atypical_path
[ 2, 14, 14629, 14, 8800, 14, 29412, 198, 834, 9641, 834, 796, 705, 16, 13, 15, 6, 198, 834, 9800, 834, 796, 705, 282, 459, 958, 13, 29047, 31, 14391, 21175, 13, 330, 13, 2724, 6, 198, 198, 2235, 198, 2235, 1846, 3742, 198, 11748,...
2.708343
4,399
# Copyright (c) OpenMMLab. All rights reserved. import torch from mmedit.models.backbones import ContextualAttentionNeck, DeepFillEncoder from mmedit.models.common import SimpleGatedConvModule
[ 2, 15069, 357, 66, 8, 4946, 44, 5805, 397, 13, 1439, 2489, 10395, 13, 198, 11748, 28034, 198, 198, 6738, 285, 1150, 270, 13, 27530, 13, 1891, 35095, 1330, 30532, 723, 8086, 1463, 8199, 694, 11, 10766, 33762, 27195, 12342, 198, 6738, ...
3.37931
58
# Generated by Django 2.2.13 on 2020-11-27 05:49 from django.db import migrations, models
[ 2, 2980, 515, 416, 37770, 362, 13, 17, 13, 1485, 319, 12131, 12, 1157, 12, 1983, 8870, 25, 2920, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 628 ]
2.875
32
# Generated by Django 3.2.4 on 2021-07-14 11:55 from django.db import migrations, models import uuid
[ 2, 2980, 515, 416, 37770, 513, 13, 17, 13, 19, 319, 33448, 12, 2998, 12, 1415, 1367, 25, 2816, 198, 198, 6738, 42625, 14208, 13, 9945, 1330, 15720, 602, 11, 4981, 198, 11748, 334, 27112, 628 ]
2.861111
36
import json import os import nibabel as nib import csv from operator import itemgetter # PATH TO PREPROCESSED DATA raw_data_path = '/home/lab/nnUNet_data/nnUNet_raw_data_base/nnUNet_raw_data/Task500_BrainMets' pixdim_ind = [1,2,3] # Indexes at which the voxel size [x,y,z] is stored # PATH TO JSON FILE with open('/home/lab/nnUNet_data/RESULTS_FOLDER/nnUNet/3d_fullres/Task500_BrainMets/nnUNetTrainerV2__nnUNetPlansv2.1/fold_4/validation_raw/summary.json') as file: data = json.load(file) with open('json_parsed.csv', mode='w') as csv_file: csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow(['Case Number', 'Dice Score', 'Voxel Size-X', 'Voxel Size-Y', 'Voxel Size-Z']) for img in data['results']['all']: # Get dice score on image dice = img['1']['Dice'] # Get nifti data on image img_filename = (os.path.basename(img['reference']).split('.'))[0] img_ni = nib.load(raw_data_path + '/imagesTr/' + img_filename + '_0000.nii.gz') label_ni = nib.load(raw_data_path + '/labelsTr/' + img_filename + '.nii.gz') voxel_size = itemgetter(*pixdim_ind)(img_ni.header["pixdim"]) # Get tumor dimensions # tumor_size = # Get case number corresponding to image case_number = img_filename.split('_')[1] # Write to csv file csv_writer = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) csv_writer.writerow([case_number, dice, voxel_size[0], voxel_size[1], voxel_size[2]])
[ 11748, 33918, 198, 11748, 28686, 198, 11748, 33272, 9608, 355, 33272, 198, 11748, 269, 21370, 198, 198, 6738, 10088, 1330, 2378, 1136, 353, 198, 198, 2, 46490, 5390, 22814, 4805, 4503, 7597, 1961, 42865, 198, 1831, 62, 7890, 62, 6978, 7...
2.300435
689
# -*- coding: utf-8 -*- """ tornadio2.tests.gen ~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2011 by the Serge S. Koval, see AUTHORS for more details. :license: Apache, see LICENSE for more details. """ from collections import deque from nose.tools import eq_ from tornadio2 import gen _queue = None def test(): init_environment() dummy = Dummy(run_sync) dummy.test('test') eq_(dummy.v, 'test') def test_async(): init_environment() dummy = Dummy(queue_async) dummy.test('test') run_async() # Verify value eq_(dummy.v, 'test') def test_sync_queue(): init_environment() dummy = DummyList(queue_async) dummy.test('1') dummy.test('2') dummy.test('3') run_async() # Verify value eq_(dummy.v, ['1', '2', '3']) def test_sync_queue_oor(): init_environment() dummy = DummyList(queue_async) dummy.test('1') dummy.test('2') dummy.test('3') run_async_oor() # Verify value eq_(dummy.v, ['1', '2', '3']) def test_async_queue_oor(): init_environment() dummy = DummyListOutOfOrder(queue_async) dummy.test('1') dummy.test('2') dummy.test('3') run_async_oor() # Verify value eq_(dummy.v, ['3', '2', '1'])
[ 2, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 37811, 198, 220, 220, 220, 12445, 324, 952, 17, 13, 41989, 13, 5235, 198, 220, 220, 220, 220, 27156, 4907, 93, 628, 220, 220, 220, 1058, 22163, 4766, 25, 357, 66, 8,...
2.315018
546
#! /usr/bin/env python # -*- coding: utf-8 -*- # # author: Avinash Kori # contact: koriavinash1@gmail.com import torch import SimpleITK as sitk import numpy as np import nibabel as nib from torch.autograd import Variable from skimage.transform import resize from torchvision import transforms from time import gmtime, strftime from tqdm import tqdm import pdb import os from ..helpers.helper import * from os.path import expanduser home = expanduser("~") #======================================================================================== # prediction functions..................... bin_path = os.path.join('/opt/ANTs/bin/') # ======================================================================================== if __name__ == '__main__': ext = deepSeg(True) ext.get_segmentation_brats('../../sample_volume/Brats18_CBICA_AVG_1/')
[ 2, 0, 1220, 14629, 14, 8800, 14, 24330, 21015, 198, 2, 220, 532, 9, 12, 19617, 25, 3384, 69, 12, 23, 532, 9, 12, 198, 2, 198, 2, 1772, 25, 5184, 259, 1077, 509, 10145, 198, 2, 2800, 25, 479, 7661, 7114, 1077, 16, 31, 14816, ...
3.469636
247
import numpy as np from statsmodels.discrete.conditional_models import ( ConditionalLogit, ConditionalPoisson) from statsmodels.tools.numdiff import approx_fprime from numpy.testing import assert_allclose import pandas as pd
[ 11748, 299, 32152, 355, 45941, 198, 6738, 9756, 27530, 13, 15410, 8374, 13, 17561, 1859, 62, 27530, 1330, 357, 198, 220, 220, 220, 220, 220, 9724, 1859, 11187, 270, 11, 9724, 1859, 18833, 30927, 8, 198, 6738, 9756, 27530, 13, 31391, 1...
3.352113
71