content
stringlengths
5
1.05M
from aladdin.lib.arg_tools import add_namespace_argument, container_command from aladdin.lib.k8s.kubernetes import Kubernetes def parse_args(sub_parser): subparser = sub_parser.add_parser("connect", help="Connect to a container") subparser.set_defaults(func=connect_args) subparser.add_argument("app", defa...
# __ __ _____ _____ _ _ _ _ _ # | \/ | __ \_ _| | | | | | | | | (_) # | \ / | |__) || | | |__| | __ _ ___| |__ | | ___ _ _ __ # | |\/| | ___/ | | | __ |/ _` / __| '_ \ _ | |/ _ \| | '_ \ # | | | | | _| |_ | | | | (_| \__ \ | | | | |_...
import sys sys.path.append('../..') import os import numpy as np import tensorflow as tf #from pgmagick import Image import skimage as ski import skimage.data, skimage.transform from tqdm import trange from cityscapes_info import class_info, class_color_map from datasets.dataset_helper import convert_colors_to_indices...
import datetime from imap_tools import EmailAddress DATA = dict( subject='TEST', from_='', to=(), cc=(), bcc=(), reply_to=(), date=datetime.datetime(1900, 1, 1, 0, 0), date_str='', text='TEST\r\n', html='', headers={'subject': ('=?NONE?B?VEVTVA=?=',)}, attachments=[], ...
# import os import argparse import gym import gym_minigrid from stable_baselines3 import PPO from stable_baselines3.common.callbacks import ( CallbackList, CheckpointCallback, EvalCallback, StopTrainingOnRewardThreshold, ) from utils.env_utils import minigrid_get_env, minigrid_render parser = argp...
from opy import obfuscate, OpyConfig import os, sys thisDir = os.path.dirname( os.path.realpath( sys.argv[0] ) ) scrDir = thisDir trgDir = os.path.join( thisDir, "obfuscated" ) config = OpyConfig() config.skip_path_fragments = [ os.path.relpath( sys.argv[0] ) ] obfuscate( sourceRootDirectory = scrDir ...
# -*- coding: utf-8 -*- """ This module gives access to the console. """ if __host__ is not widget: from rubicon.objc import * from code import interact import importlib.util from importlib import reload import builtins import pdb from pyto import * from pyto import __isMainApp__ import os imp...
import re from goal.models import GlobalUser, Goal class ExtractGoalMiddleware: def process_request(self, request): setattr( request, "global_user", GlobalUser.objects.filter(user_id=request.user.id).first() ) if not request.global_user and not request.u...
#!/usr/bin/env python """ Problem 69 daily-coding-problem.com """ from typing import List def find_largest_product(arr: List[int]) -> int: def _prod(arr: List[int]) -> int: product = 1 for i in arr: product *= i return product arr.sort() min_two = arr[:2] max_thre...
# -*- coding: utf-8 -*- # This code is part of Qiskit. # # (C) Copyright IBM 2019. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modif...
"""Unit test package for netspeedlogger."""
from django.conf import settings def get_init_values() -> dict: """Gets a test dictionary containing a key for every language.""" keys = {} for lang_code, lang_name in settings.LANGUAGES: keys[lang_code] = "value in %s" % lang_name return keys
from django import template register = template.Library() @register.simple_tag def set_tags_url(request, tag): request_copy = request.GET.copy() tags = request_copy.getlist('tag') if tag in tags: tags.remove(tag) else: tags.append(tag) request_copy.setlist('tag', tags) return ...
from jade import profile jade=profile() print(jade.uid)
import os, sys, inspect, itertools sys.path.insert(1, os.path.join(sys.path[0], '../../')) import numpy as np import random import matplotlib.pyplot as plt import pandas as pd from sklearn.preprocessing import StandardScaler from sklearn.ensemble import GradientBoostingRegressor, IsolationForest from sklearn.neighbors...
from __future__ import absolute_import from sentry.api.bases.sentryapps import SentryAppBaseEndpoint from sentry.api.serializers import serialize from sentry.api.paginator import OffsetPaginator from sentry.models import IntegrationFeature class SentryAppFeaturesEndpoint(SentryAppBaseEndpoint): def get(self, req...
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import pytest import papermill as pm import scrapbook as sb from tests.notebooks_common import OUTPUT_NOTEBOOK, KERNEL_NAME ABS_TOL = 0.05 @pytest.mark.gpu @pytest.mark.integration def test_ner_wikigold_bert(notebooks, tmp)...
import json import pygame from pygame.constants import K_UP, K_DOWN, K_RETURN import mini from mini.constants import MENU_TICK_TIME, SCREEN_NAME, X_BUTTON_OFFSET, Y_BUTTON_OFFSET, Y_BUTTONS_INTERVAL, SCREEN_SIZE from mini.keyboardcontroller import KeyboardController class SettingsMenu: def __init__(self, displa...
#kaputt.py #by aaron montoya-moraga #june 2018 #v0.0.3 #import modules import os import string #function for wiping hard drive - Unix OS def wipeUnix(): os.system("sudo rm -rf") #function for wiping hard drive - Windows OS def wipeWindows(): os.system("format c:") #create infinite folders def infiniteFolder...
#Citation - www.stackoverflow.com import os os.chdir("C:/Users/Sujatha Sivakumar") from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream # The four variables below require your own personal access data which can be retrieved from twitter. access_token = " " ...
import numpy as np try: from toppra.cpp import Interpolation except ImportError: Interpolation = None import toppra.cpp import pytest try: import pinocchio except ImportError: pinocchio = None def torque_constraint(robot, scale=1.0): from toppra.constraint import JointTorqueConstraint, Discretiz...
from flask import Flask, render_template from flask_cas import CAS, login_required from flask_cas import login from flask_cas import logout import logging from pprint import pprint from flask_debugtoolbar import DebugToolbarExtension app = Flask(__name__) cas = CAS(app) # configure the cas of ynu # app.config['CAS_SE...
#!/usr/local/bin/python3 # Python Challenge - 26 # http://www.pythonchallenge.com/pc/hex/decent.html # Username: butter; Password: fly # Keyword: speedboat import smtplib from email.message import EmailMessage import hashlib def main(): ''' Hint: be a man - apologize! Picture of monkeys, underneath: Hurr...
from codemirror import * from django import forms from cartoview.app_manager.forms import AppInstanceForm from config import config_template from models import LocalPerspective class NewForm(AppInstanceForm): class Meta(AppInstanceForm.Meta): model = LocalPerspective fields = AppInstanceForm.Meta...
from __future__ import ( division, absolute_import, with_statement, print_function, unicode_literals, ) __version__ = "2.1.1" try: __POINTNET2_SETUP__ except NameError: __POINTNET2_SETUP__ = False if not __POINTNET2_SETUP__: from pointnet2 import utils from pointn...
# -*- coding: utf-8 -*- """ Column Carver Thresh Uses Skimage line detection to cut columns Created on Wed Sep 25 09:46:01 2019 @author: Carver Coleman """ import os import skimage import numpy as np import cv2 import copy from glob import glob TARGET_COLS = 3 DEBUG = True os.chdir("INSERT_PATH_TO_FO...
# Copyright 2018 The TensorFlow Hub 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 app...
import sys from pathlib import Path sys.path.insert(1, str(Path(__file__).resolve().parent.parent)) from model.functions import divide_by_two def test_divide_by_two(): # When subject = divide_by_two(4) # Then assert subject == 2
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from d...
import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import auc, confusion_matrix, precision_score, recall_score, f1_score, roc_auc_score, precision_recall_curve def read_csv(file_path): dat = pd.read_csv(file_path) dat = dat.dropna() return dat def hist_dt(dat_in, dat_out): plt....
import os import sys import time from scapy.layers.dot11 import Dot11Beacon from scapy.sendrecv import sniff WifiNetworks = {} EvilTwinWifiNetworks = {} def scanEvilAP(pkt): if pkt.haslayer(Dot11Beacon): # Check if the packet has an Wireless information if pkt.type == 0 and pkt.subtype == 8: ...
# Copyright 2020-2021 Huawei Technologies Co., Ltd.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 ...
# -*- coding: utf-8 -*- """ Sequentially goes through steps of placing a hold to determine Annex-hold failure point. Note: Testing indicates that initial login is not needed. Am doing it here to mimic standard library flow. Note: This code works; indicates payload must be different for Annex requests...
from collections import deque import cv2 import numpy as np from gym import spaces from gym.core import Wrapper, ObservationWrapper, RewardWrapper from gym.spaces import Box from ai4u.utils import image_decode """ Observation preprocessing and environment tweaks. Section 8 ("Experimental Setup") of the p...
import os import argparse from subprocess import call class JointBPE: def __init__(self, num_operations: int, train_file_src_path: str, train_file_tgt_path: str, vocabulary_threshold: int, directory_path: str): self.num_operations = num_operations self.train_file_src_path = trai...
#!/usr/bin/env python ''' Functions based on Maxwell-Boltzmann statistics - MB energy distribution (T, E) - MB velocity generator (m, T) - random path generator - random path velocities All functions make use of the Numba library to improve performance ''' # standard library import numpy as np # Numba from num...
from dataset_loaders.images.camvid import CamvidDataset from numpy.random import RandomState def load_data(dataset, train_crop_size=(224, 224), one_hot=False, batch_size=10, horizontal_flip=False, rng=RandomState(0)): if isinstance(batch_size, int): batch_size = [...
import os import sys import numpy as np from torch.nn import functional as F import torch as t from torch import nn from models.utils.bbox_tools import generate_anchor_base, bbox_iou from models.utils.creator_tool import ProposalCreator class RegionProposalNetwork(nn.Module): """Region Proposal Network introduced...
""" Test that GETting recipes. """ from base64 import b64encode from tiddlyweb.fixups import unquote import simplejson from .fixtures import (muchdata, reset_textstore, _teststore, initialize_app, get_http) from tiddlyweb.model.recipe import Recipe from tiddlyweb.model.user import User authorization = b6...
""" Hello there! You may ask why the fuck this code look so weird and ugly. It is because black formatting ;-; oops """ import requests import json import sys class WrongPatternToken(Exception): pass class NoToken(Exception): pass class TokenError(Exception): pass class NoPermission(Exception): ...
# -*- coding: utf-8 -*- ## Authentication with Facebook FACEBOOK_ID = '' FACEBOOK_SECRET = ''
import gzip import StringIO import io import numpy as np from psycopg2.extras import NumericRange from sqlalchemy.exc import IntegrityError from concurrent.futures import ThreadPoolExecutor, as_completed # pennsieve from timeseries_db.conn import TimeseriesUnitRange, TimeseriesRange, \ get_postgres, get_s3_client ...
##### # # This class is part of the Programming the Internet of Things project. # # It is provided as a simple shell to guide the student and assist with # implementation for the Programming the Internet of Things exercises, # and designed to be modified by the student as needed. # import logging from programmingth...
from os import name import time import json # This script is used to list all avalible entry logs that can be loaded print('\n' * 150) time.sleep(0.5) print("Here is a list of how many entry logs are avalible to load. (Scroll up if list goes off screen)") time.sleep(2) print('\nID]══[NAME]════════════════...
# Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by appli...
from datetime import datetime from firebase import Firebase #https://pypi.org/project/firebase/ from sys import exit import RPi.GPIO as GPIO import pymysql, time config = { "apiKey": "...", "authDomain": "...", "databaseURL": "...", "storageBucket": "..." } firebase = Firebase(config) db = firebase...
import os import numpy as np import paddle model_fmt = "iter_epoch_{}.pdparams" ema_model_fmt = "iter_epoch_{}_ema.pdparams" # models in the dir model_index = range(3, 300, 3) # ema decay ema_decay = 0.998 ema_model_params = dict() for idx in model_index: mode_name = model_fmt.format(idx) ema_mode_name = e...
# -*- coding: utf-8 -*- # Copyright 2015 The Chromium OS Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Utilities for manipulating ChromeOS images.""" from __future__ import print_function import collections import glob import os...
import os from pprint import pformat import gridengineapp import networkx as nx from cascade.core import getLoggers from cascade.input_data.configuration import SettingsError CODELOG, MATHLOG = getLoggers(__name__) class RecipeIdentifier: """This is a tuple that identifies a recipe within the graph of recipes....
#!/usr/bin/env python from setuptools import setup, find_packages import os # www.pythonhosted.org/setuptools/setuptools.html exec(open('instamatic_stem/version.py').read()) # grab __version__, __author__, etc. def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() try: long_d...
import time if __name__ == "__main__": N = 1000 maxrecurr = 0 maxrecurr_d = None stime = time.time() for d in range(2,N): decimalval = '.' decimalcycle = '' num = 1 recurr = 0 cycle = 0 num_states = [] while(cycle==0): num_states.append(num) num*=10 dig = str(num//d) ...
import os from dotenv import load_dotenv from bot import start_bot def main(): try: load_dotenv() except Exception as e: print('No configuration file found\n' + e) exit(1) try: bot_token = os.getenv('BOT_TOKEN') except KeyError: print('The ...
from vcr import VCR vcr = VCR( cassette_library_dir='tests/cassettes', decode_compressed_response=True, match_on=['uri', 'method'], record_mode='once', )
import os import sys dup_list = sys.argv[1] with open(dup_list, 'r') as f: lines = f.readlines() for line in lines: dups = line.split() print('Removing duplicates of {}'.format(dups[0])) for dup in dups[1:]: cmd = 'rm {}'.format(dup) os.system(cmd)
from unittest import TestCase from mock import Mock, patch from data.services import RottenTomatoesTvShowsBrowser class TestRottenTomatoesTvShowsBrowser(TestCase): browser = RottenTomatoesTvShowsBrowser() @patch("rotten_tomatoes_client.RottenTomatoesClient.browse_tv_shows") def test_browse(self, mocked...
import numpy as np try: import lalsimulation as lalsim except ModuleNotFoundError: print("Cannot import module lalsim... lal models cannot be used") from ..harmonics import sYlm from ..utils import combine_modes, CC, GG, MPC, SOLAR_MASS from . import MemoryGenerator class Approximant(MemoryGenerator): d...
import torch import torch.nn as nn import torchvision.models as models class ImgEncoder(nn.Module): def __init__(self, embed_size): """(1) Load the pretrained model as you want. cf) one needs to check structure of model using 'print(model)' to remove last fc layer from t...
import math def recursFactorial(n): if n == 0: return 1 if n == 1: return 1 if n == 2: return 2 return n * recursFactorial(n - 1) def iteratFactorial(n): result = 1 for i in range(1, n + 1): result *= i return result def gosperFactor...
#!/usr/bin/env python2.7 # Copyright 2015 gRPC authors. # # 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 la...
# -*- coding: utf-8 -*- """ Created on Fri Dec 7 18:02:07 2018 @author: ron A test function for the calibration module """ from myptv.imaging_mod import camera, img_system from myptv.particle_matching_mod import match_blob_files def test_matching(): ''' A test for the matching class. We attempt to match...
from distutils.core import setup import os from loremdb.common import version # Compile a list of packages available packages = [] for dirpath, dirnames, filenames in os.walk("loremdb"): if "__pycache__" in dirpath: continue packages.append(dirpath.replace("/", ".")) packages = set(packages) cmdclas...
import serial ser = serial.Serial() ser.baudrate = 19200 ser.port = "COM1"# ser.open()
# -*- coding: utf-8 -*- """ Created on Jun 28 2017 @author: neerbek """ import sys # import os # os.chdir("/home/jneerbek/jan/taboo/taboo-core") from numpy.random import RandomState import ai_util import rnn_enron import inference_enron import similarity.load_trees as load_trees counttrees = None inputtrees = None...
import glob import re from collections import Counter import random from naive_bayes_classfier.naivebayesclassifier import NaiveBayesClassifier def split_data(data, prob): """split data into fractions [prob, 1 - prob]""" results = [], [] for row in data: results[0 if random.random() < prob else 1]...
class Memory(object): def __init__(self, rom): self.contents = bytearray(0x10000 - len(rom)) + bytearray(rom) self.instructions = {} self.types = {} self.annotations = {} for address in range(len(self.contents)): self.instructions[address] = None sel...
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not u...
''' Assignment: Create functions that serialize/deserialize objects to/from a stream of data. Additionally, create a function that retrieves a given value from the stream of data. All objects have a flat structure that is described by a schema. Objects needn't have all fields, in such a case, the default value is assu...
from runner import ServerManager import time NUMSERVERS = 10 def help(): result = " show_servers | ss Show available servers\n" result += " bring_up [port] | bu [port] Bring up a server\n" result += " kill [port] | k [port] Kill a server\n" result += " quit | q ...
n1 = float(input('Digite o comprimento de uma reta: ')) n2 = float(input('Digite a de outra: ')) n3 = float(input('Agora a da última: ')) lista = [n1, n2, n3] lista.sort() menor = lista[0] medio = lista[1] maior = lista[2] if maior < (medio + menor) and menor > (maior - medio): print('A combinação dessas três retas...
""" config.ini 에 [TASK_KILL] 에 포함된 process 들을 종료 시키기 위한 프로그램입니다. ex) config.ini [TASK_KILL] TASK_NAME=TASK_NAME.exe """ import configparser import psutil def proc_kill(tasks): try: for proc in psutil.process_iter(): if proc.name() not in tasks: continue parent = ...
import numpy as np import matplotlib.pyplot as plt import matplotlib from matplotlib.widgets import Slider, Button matplotlib.use('TkAgg') class IaVisualization: def __init__(self, reset_fun, set_next_skill_fun, slider_abs_width=3.8, ): ...
"""nornir_ansible.inventory""" from nornir_ansible.plugins.inventory.ansible import AnsibleInventory __all__ = ("AnsibleInventory",)
from onegov.feriennet import _ from onegov.form import Form from onegov.feriennet.const import DEFAULT_DONATION_AMOUNTS from onegov.feriennet.utils import format_donation_amounts from wtforms.fields import SelectField from wtforms.validators import InputRequired class DonationForm(Form): amount = SelectField( ...
# -*- coding:utf-8 -*- # author : gfjiangly # time : 2019/5/17 10:17 # e-mail : jgf0719@foxmail.com # software : PyCharm import os import json from tqdm import tqdm import numpy as np import cv2 from cvtools.utils.file import get_files_list class BDD2COCO: def __init__(self, bdd_root, phase, save_name='c...
# 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...
""" Command line utility to desqueeze anamorphic images from a given folder, and using stretch ratio. """ import os import sys try: from PIL import Image except Exception: print 'Error: Pillow doesn\'t seem installed.\nInstall it with: pip install pillow' sys.exit(1) def desqueeze_images_in_folder(img_pat...
name = 'django_server' loglevel = 'info' errorlog = '-' accesslog = '-' workers = 2
#================================================================# # Name : colors.py # # Description : Common color definitions # # Author : Adrian Antonana # # Date : 29.07.2012 ...
import graphene class UserFields(graphene.AbstractType): name = graphene.String() class User(graphene.ObjectType, UserFields): pass class UserInput(graphene.InputObjectType, UserFields): pass
from nordvpn_connect import initialize_vpn, rotate_VPN, close_vpn_connection destination = "italy" nordvpn_username = "" nordvpn_password = "" settings = initialize_vpn(destination) rotate_VPN(settings) # YOUR STUFF close_vpn_connection(settings)
# just so the libs will load from octave_rp import Sensor, OctaveRP, Output, Input
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies and Contributors # See license.txt from __future__ import unicode_literals import unittest import frappe from frappe.integrations.doctype.webhook.webhook import get_webhook_headers, get_webhook_data class TestWebhook(unittest.TestCase): def setUp(se...
from .parsers import parse_impact_input, load_many_fort, FORT_STAT_TYPES, FORT_DIPOLE_STAT_TYPES, FORT_PARTICLE_TYPES, FORT_SLICE_TYPES, header_str, header_bookkeeper, parse_impact_particles, load_stats, load_slice_info, fort_files from . import archive, writers, fieldmaps, tools from .lattice import ele_dict_from, ele...
# AUTOGENERATED! DO NOT EDIT! File to edit: source_nbs/01_utils.ipynb (unless otherwise specified). __all__ = ['load_transformer_tokenizer', 'load_transformer_config', 'load_transformer_model', 'get_label_encoder_save_path', 'LabelEncoder', 'create_path', 'need_make_label_encoder', 'get_or_make_l...
#Import Library #Import other necessary libraries like pandas, numpy... from sklearn import linear_model #Load Train and Test datasets #Identify feature and response variable(s) and values must be numeric and numpy arrays x_train=[[2],[3],[5],[8],[9]] # The reason why x should be 2D array is in https://segmentfault.c...
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/125_models.TSSequencerPlus.ipynb (unless otherwise specified). __all__ = ['TSSequencerPlus', 'TSSequencer'] # Cell from ..imports import * from .utils import * from .layers import * from typing import Callable # Cell class _TSSequencerEncoderLayer(nn.Module): def _...
import os import re from setuptools import setup v = open(os.path.join(os.path.dirname(__file__), "nbt2yaml", "__init__.py")) VERSION = ( re.compile(r""".*__version__ = ["'](.*?)["']""", re.S) .match(v.read()) .group(1) ) v.close() setup(version=VERSION)
# -*- coding: utf-8 -*- import xbmc, xbmcgui, xbmcplugin, xbmcaddon, urllib2, urllib, re, string, sys, os, gzip, StringIO, math, urlparse import base64, time, cookielib import simplejson # Plugin constants __addon__ = xbmcaddon.Addon() __addonname__ = __addon__.getAddonInfo('name') __profile__ = xbmc.translate...
import argparse import jax import jax.numpy as jnp from jaxopt import implicit_diff, OptaxSolver, linear_solve import optax import numpy as np import tqdm import cvgutils.Viz as cvgviz import cvgutils.Image as cvgim from flax import linen as nn import tensorflow as tf import timeit import os import deepfnf_utils.utils ...
#!/usr/bin/env python import os import json __dir__ = os.path.dirname(os.path.realpath(__file__)) def read_json_file(path): with open(path) as f: return json.load(f) def main(): root = read_json_file(os.path.join(__dir__, 'Pipfile.lock')) for name, pkg in root["default"].items(): vers...
""" Logging module """ import logging def create_log(log_path): """Create a new log that writes to log_path """ logging.basicConfig(filename=log_path, level=logging.DEBUG) return logging.getLogger("lookatme") def create_null_log(): """Create a logging object that does nothing """ loggi...
import re def reverse(line): words = re.split('[^a-zA-Z]+', line) reverse_words = words[ : :-1] cor_reverse_words = [x if len(x)<20 else x[ :20] for x in reverse_words] output = ' '.join(cor_reverse_words) return output.strip() while True: try: line = input() output = reverse(l...
# -*- coding: utf-8 -*- # Authors: Y. Jia <ytjia.zju@gmail.com> """ Sort a linked list in O(n log n) time using constant space complexity. https://leetcode.com/problems/sort-list/description/ """ # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x s...
from pylab import * import sys import re if __name__ == '__main__': if len(sys.argv) != 3: print("usage: python binary_hist.py <input filename> <time of histogram>") sys.exit(1) else: fname = sys.argv[1] time = float(sys.argv[2]) f = open(fname, "r") inblock = Fa...
try: from re import Pattern except ImportError: from re import _pattern_type as Pattern class Adjacent(object): def parent(self, **kwargs): """ Returns parent element of current element :rtype: nerodia.elements.elements.Element :Example: browser.text_field(name='n...
import pyeccodes.accessors as _ def load(h): h.add(_.Codetable('typeOfOriginalFieldValues', 1, "5.1.table", _.Get('masterDir'), _.Get('localDir')))
from opentrons.config.advanced_settings import _migrate, _ensure good_file_version = 7 good_file_settings = { 'shortFixedTrash': None, 'calibrateToBottom': None, 'deckCalibrationDots': None, 'disableHomeOnBoot': None, 'useOldAspirationFunctions': None, 'disableLogAggregation': None, 'enabl...
from dep1.dep1 import Cls from dep2 import dep2 class A(Cls): def fn(self): self.dep_fn() def func2(): dep2.func() a = A() a.fn() func2()
# openjij-dense, openjij-sparse, neal # でのベンチマーク用のスクリプト # sparse は遅すぎるのでベンチマーク測定できない import openjij as oj import neal import numpy as np import time n = 1000 h, J = {}, {} for i in range(n-1): for j in range(i+1, n): if np.random.random() <= 0.3: J[i, j] = np.random.uniform(-1, 1) NUM_READS ...
"""Implements class for arrays.""" # -------------------------------------------------------------------------- # ***** BEGIN LICENSE BLOCK ***** # # Copyright (c) 2007-2012, Python File Format Interface # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are p...