input
stringlengths
2.65k
237k
output
stringclasses
1 value
(\d+)", osinfo) if match and match.group(1): return (match.group(1).split(" ")[0], match.group(2).split(".")[0]) f_path = self._root_dir + "/etc/lsb-release" if os.path.exists(f_path): distribution = "" version = "" osinfo = FileUtil(f_path).getdata() match = re.search(r"DISTRIB_ID=(.+)(\n|$)", osinfo, re.MUL...
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # formats: ipynb,py:percent # text_representation: # extension: .py # format_name: percent # format_version: '1.1' # jupytext_version: 0.8.3 # kernelspec: # display_name: Python 3 # language: python # name: python3 # language_info: # codemirror_mode: # name: ipython ...
(0x5319, 0), # East Asian ideograph 0x6F576F: (0xC904, 0), # Korean hangul 0x6F532C: (0xC12D, 0), # Korean hangul 0x23356F: (0x8C74, 0), # East Asian ideograph 0x6F4B7B: (0xB11E, 0), # Korean hangul 0x215B2A: (0x8E91, 0), # East Asian ideograph 0x6F4F6F: (0xB9DB, 0), # Korean hangul 0x21344D: (0x5321, 0), # East...
<reponame>LB-KatarzynaDylska/o3de """ Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution. SPDX-License-Identifier: Apache-2.0 OR MIT """ # Shape components associated with specific light types. LIGHT_SHAPES = { 's...
<gh_stars>0 import torch import torch.nn as nn from torch.nn import init import functools from torch.optim import lr_scheduler ############################################################################### # Helper Functions ############################################################################### class Iden...
or 0), 'cig_url': contact_group.get_absolute_url() + 'members/' + str(contact_with_extra_fields.id), 'title': _('{contact} in group {group}').format( contact=contact_with_extra_fields, group=contact_group), 'msg_count': msg_count, 'msg_count_unread': msg_count_unread, }) def membership_extended_widget_factor...
<gh_stars>0 #!/usr/bin/env python3 # -*- coding:utf-8 -*- # #### # File: txtAdventure_procedural_journey.py # Project: random_journey #----- # Created Date: Saturday 18.07.2020, 12:27 # Author: Apop85 #----- # Last Modified: Monday 20.07.2020, 21:17 #----- # Copyright (c) 2020 Apop85 # This software is published unde...
the call. call.return_value = dlp.DlpJob() # Call the method with a truthy value for each flattened field, # using the keyword arguments to the method. client.get_dlp_job(name="name_value",) # Establish that the underlying call was made with the expected # request object values. assert len(call.mock_calls) == ...
""" Module for customising opensim segmented muscle points """ import os import numpy as np import copy from gias2.fieldwork.field import geometric_field from gias2.fieldwork.field.tools import fitting_tools from gias2.common import transform3D from gias2.registration import alignment_fitting as af from gias2.musculos...
cleanup code here would be to make a # change to Slice, so that a Slice either doesn't have a # reference to a Sheet, or doesn't hold onto that reference. # # 2: Some cleanup code will always be required here in # Simulation.__new__: As well as removing references to Sheets # from Slices, it is also necessary to ...
# -*- coding: utf-8 -*- import codecs import os, sys import copy import random import json import math import decimal import datetime import threading import exceptions import time import base64 import md5 from gevent import socket import urllib, urllib2, urlparse from socket import error import errno import subproces...
[u'h'] , u'婒' : [u't'] , u'㻕' : [u'j'] , u'齔' : [u'c'] , u'䏗' : [u'k', u'g'] , u'睤' : [u'b'] , u'寧' : [u'z', u'n'] , u'鳩' : [u'q', u'j', u'z'] , u'佴' : [u'm', u'e', u'n'] , u'遶' : [u'r'] , u'瓹' : [u'j'] , u'梆' : [u'b'] , u'刍' : [u'c'] , u'霏' : [u'f'] , u'㾔' : [u'l'] , u'䂖' : [u's'] , u'薘' : [u'd'] , u'漟' : [u't'] , u'墦...
from rdfframes.dataset.expandable_dataset import ExpandableDataset from rdfframes.dataset.rdfpredicate import PredicateDirection __author__ = """ <NAME> <<EMAIL>> <NAME> <<EMAIL>> <NAME> <<EMAIL>> """ class KnowledgeGraph: """ High level class represents one or more knowledge graphs (URIs). It contains a group o...
<filename>lauetoolsnn/lauetools/dict_LaueTools.py<gh_stars>0 # -*- coding: utf-8 -*- """ Dictionary of several parameters concerning Detectors, Materials, Transforms etc that are used in LaueTools and in LaueToolsGUI module Lauetools project April 2019 """ __author__ = "<NAME>, CRG-IF BM32 @ ESRF" import ...
864, 864, 2620, 864, 2620, 864, 2620, 864, 2620, 864, 2620, 864, 864, 864, 2620, 864, 864, 864, 864, 864, 864, 864, 864, 864, 864, 864, 864, 864, 864, 864, 2620, 864, 864, 864, 864, 864, 864, 864, 864, 864, 864, 864, 864, 3485, 3512, 864, 13996, 3485, 3512, 864, 864, 864, 864, 864, 2620, 864, 864, 864, 2620, 864...
"""Provides COM objects with version-independent access to the System.Reflection.EventInfo.MemberType property. Get: MemberType(self: _EventInfo) -> MemberTypes """ Name = property(lambda self: object(), lambda self, v: None, lambda self: None) # default """Provides COM objects with version-independent ...
<reponame>truthiswill/usaspending-api<filename>usaspending_api/download/v2/download_column_historical_lookups.py from collections import OrderedDict """ Sets up mappings from column names used in downloads to the query paths used to get the data from django. Not in use while we pull CSV data from the non-historical t...
<reponame>mikiec84/aiida-bigdft-plugin """ This module is useful to process a logfile of BigDFT run, in yaml format. It also provides some tools to extract typical informations about the run, like the energy, the eigenvalues and so on. """ # This module needs: os, yaml, futile, matplotlib, numpy, BZ, DoS EVAL = "eval...
<reponame>nwfsc-fram/pyFieldSoftware<filename>py/observer/ImportBiospeciesProtocols.py # ----------------------------------------------------------------------------- # Name: ImportBiospecProtocols.py # Purpose: Import CSV file into biospecimens protocols # # Author: <NAME> <<EMAIL>> # # Created: August 23, 2016 # Lice...
TRP n 1 250 PRO n 1 251 LYS n 1 252 ASP n 1 253 ARG n 1 254 ALA n 1 255 PRO n 1 256 LEU n 1 257 ILE n 1 258 LEU n 1 259 VAL n 1 260 THR n 1 261 TYR n 1 262 PHE n 1 263 THR n 1 264 GLN n 1 265 PRO n 1 266 GLN n 1 267 PRO n 1 268 LYS n 1 269 ALA n 1 270 GLU n 1 271 SER n 1 272 ARG n 1 273 ARG n 1...
Delete a record from the reference dataset table :param internal_id: the django id for the record :return: """ self.increment_minor_version() self.get_record_by_internal_id(internal_id).delete() if self.external_database is not None: self.sync_to_external_database(self.external_database.memorable_name) self.mod...
predicted and extracted limb location in the image and used to compute the extracted limb location. The resulting predicted surface points, predicted image points, observed image points, and scan directions in the camera frame are then all returned as numpy arrays. :param image_interpolator: A callable which retu...
<filename>encore/events/tests/test_event_manager.py # # (C) Copyright 2011 Enthought, Inc., Austin, TX # All right reserved. # # This file is open source software distributed according to the terms in LICENSE.txt # # Standard library imports. import unittest import mock import weakref import threading # Local imports...
not found.') path = request.data.get('p', '') file_id = seafile_api.get_file_id_by_path(repo_id, path) if not path or not file_id: return api_error(status.HTTP_400_BAD_REQUEST, 'Path is missing or invalid.') username = request.user.username # check file access permission parent_dir = os.path.dirname(path) if...
<reponame>erteck/textHighlighter #!/usr/bin/env python3 """ Handles the visible area of the :class:`~tools.manual.faceviewer.frame.FacesViewer` canvas. """ import logging import tkinter as tk import cv2 import numpy as np from PIL import Image, ImageTk from lib.align import AlignedFace logger = logging.getLogger(__...
-- If the word begins the string OR is preceded by a space, # (User|words|here) -- AND it appears in the list exactly, # (?=\s|$) -- AND it is followed by a space OR ends the string... pattern = re.compile(r'(^|\s)(' + remove_string + r')(?=\s|$)', re.UNICODE) # ...Then swap the word and the preceding (but not fo...
print("######################################################################") print("# Parallel n-split k-stratified-fold continuous SVM Scikitlearn MVPA #") print("# (c) <NAME> 2012, jeanremi.king [at] gmail [dot] com #") print("######################################################################") # Implementat...
<filename>test/test_utils/ec2.py import os import time import re from inspect import signature import boto3 from retrying import retry from fabric import Connection from botocore.config import Config from botocore.exceptions import ClientError from test.test_utils import is_pr_context, is_mainline_context from . impo...
#!/Users/fa/anaconda/bin/python ''' Evaluation code for the SICK dataset (SemEval 2014 Task 1) ''' import sys #sys.path = ['../gensim', '../models', '../utils'] + sys.path sys.path = ['../', '../featuremodels', '../utils', '../monolingual-word-aligner'] + sys.path # Local imports import gensim, utils from featuremode...
# "x": "NEW", # Current execution type # "X": "NEW", # Current order status # "r": "NONE", # Order reject reason; will be an error code. # "i": 4293153, # Order ID # "l": "0.00000000", # Last executed quantity # "z": "0.00000000", # Cumulative filled quantity # "L": "0.00000000", # Last executed price # "n": "0"...
"""This module contains functions relevant to the ALARA activation code and the Chebyshev Rational Approximation Method """ from __future__ import print_function from pyne.xs.data_source import SimpleDataSource from pyne.data import N_A, decay_const, decay_children, branch_ratio from pyne.nucname import serpent, alara,...
<filename>inselect/gui/main_window.py<gh_stars>100-1000 import sys from datetime import datetime from functools import partial from itertools import count from pathlib import Path from PyQt5 import QtWidgets from PyQt5.QtCore import (Qt, QEvent, QSettings, QItemSelection, QItemSelectionModel, QStandardPaths) from P...
= rgb_str(139, 87, 66) LIGHTSEAGREEN = rgb_str(32, 178, 170) LIGHTSKYBLUE = rgb_str(135, 206, 250) LIGHTSKYBLUE1 = rgb_str(176, 226, 255) LIGHTSKYBLUE2 = rgb_str(164, 211, 238) LIGHTSKYBLUE3 = rgb_str(141, 182, 205) LIGHTSKYBLUE4 = rgb_str(96, 123, 139) LIGHTSLATEBLUE = rgb_str(132, 112, 255) LIGHTSLATEGRAY = rgb_str(1...
in np.arange(measurement_count[0]): if row == 0: if measurement_count[0] == 1: # if final row # straight line only x_position_list = np.arange(0, object_size[1]) y_position = np.ceil(image_size[0] * 0.5).astype(int) for position_x in x_position_list: raster_point_list.append([y_position, position_x]) else: # ...
import os import socket import typing from typing import List, Union, AnyStr, Iterable from collections import OrderedDict from datetime import datetime, timedelta import math import json import csv from pathlib import Path from urllib.parse import urlparse import base64 from uuid import uuid4 from io import StringIO, ...
= smesh.Mesh(mesh) except: pass else: print "[X] The input object is not a mesh or the Mesh module was not yet loaded."; return # Get the mesh name mesh_name = mesh.GetName() #- # Renumber elements and nodes mesh.RenumberNodes() mesh.RenumberElements() #- ...
<filename>tests/sim/test_anneal.py # Copyright 2020 <NAME> # # 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...
2000-07-23 <Field Y-26:sex> M >>> show_elements (f_p, "ui_display") <Entity X-26> <NAME> <Field X-26:last_name> Tanzer <Field X-26:first_name> Christian <Field X-26:middle_name> <Field X-26:title> <Field_Composite X-26:lifetime> 1959-09-26 <Field X-26:lifetime.start> 1959-09-26 <Field X-26:lifetime.finish> ...
<reponame>AmirS2/sagemaker-python-sdk # Copyright 2017-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://aws.amazon.com/apac...
""" This function will calculate the interval, at which an annotation shoud be showed for example 7456 observations, and the user wants 13 Annotations 7456/13 = 573.56 ~ each 573th observation will receive an annotation The user will then be able to use modulo (%) to plot an annotation equal amount of tim...
def models(self, value): if value is None: self._property_models = None return self.assert_isinstance(value, "models", (list, tuple)) self.assert_isinstance(value, "models", (dict,), is_array=True) self._property_models = value class DeleteModelsResponse(Response): """ Response of tasks.delete_models endpoi...
== "Split": if "split" in attributes and attributes["split"] == ( old_d_embd, old_d_embd, old_d_embd, ): assert len(attributes) == 2 attributes = frozendict( { "axis": attributes["axis"], "split": ( new_d_embd, new_d_embd, new_d_embd, ), } ) elif op_type == "Constant": value = attributes["value"] if ...
select_params=None, headers=None ): """Select一个文件的内容到本地文件 :param key: OSS文件名 :param filename: 本地文件名。其父亲目录已经存在且有写权限。 :param progress_callback: 调用进度的callback。参考 :ref:`progress_callback` :param select_params: select参数集合。参见 :ref:`select_params` :param headers: HTTP头部 :type headers: 可以是dict,建议是oss2.CaseInsensiti...
from elasticsearch.client.utils import NamespacedClient, query_params, _make_path, SKIP_IN_PATH class MlClient(NamespacedClient): @query_params('from_', 'size') def get_filters(self, filter_id=None, params=None): """ :arg filter_id: The ID of the filter to fetch :arg from_: skips a number of filters :arg size: ...
returned for the compute record if active_compute_record.session_state and active_compute_record.session_state.session_desc: most_recent_session_desc: ComputeSessionDesc = active_compute_record.session_state.session_desc else: most_recent_session_desc: ComputeSessionDesc = state.session_desc job_name = most_recent...
self.GetMethodConfig('Insert') return self._RunMethod( config, request, global_params=global_params) def List(self, request, global_params=None): """Retrieves the list of ForwardingRule resources available to the specified project. Args: request: (ComputeGlobalForwardingRulesListRequest) input message global_p...
getattr(self, "tauBand", None) is None: self.windowRange.tauBand = 0 else: if not isinstance(self.tauBand, int): logging.warn( "Casting non-integer tauBand={} to int...".format( self.tauBand ) ) self.tauBand = int(self.tauBand) self.windowRange.tauBand = self.tauBand if self.dtau: self.windowRange.dtau = se...
i1)) dims = (i2, fi, i3, gi, i1) self.h = aobj.hfarray(np.zeros((1, 2, 1, 3, 1)), dims=dims) dims = (i4, i5) class _Test_hfarray(MakeData, TestCase): pass class Test_hfarray_checkinstance(TestCase): def setUp(self): class VArray(aobj._hfarray): __array_priority__ = 10 self.VArray = VArray def test_1(self)...
<filename>python-lophi/lophi/sensors/memory/physical.py """ Class for interacting with our physical memory sensor (FPGA) (c) 2015 Massachusetts Institute of Technology """ # Native import socket import time import logging logger = logging.getLogger(__name__) import multiprocessing # LO-PHI import lophi.globals as ...
data was seriously messed up. The following notes refer to those times (in case they come back). There is a lot of code to catch if the problem comes back and provide appropriate data for debugging. There were some serious issues with unknown causes here: 1. Lightning data is crazy because lightning bins rarely ...
<filename>mlflow/gluon/__init__.py<gh_stars>1-10 from packaging.version import Version import os import numpy as np import pandas as pd import yaml import mlflow from mlflow import pyfunc from mlflow.exceptions import MlflowException from mlflow.models import Model from mlflow.models.model import MLMODEL_FILE_NAME fr...
import numpy as np import pandas as pd import seaborn as sns import os from pathlib import Path import seaborn as sns import matplotlib.pyplot as plt from multiprocessing import Pool import torch from src.data.data_utils import load_train_test_ims, load_train_test_femto from src.models.utils import ( test_metrics_to_...
<reponame>amitschang/SciScript-Python import json import time import sys from io import StringIO, BytesIO import requests as requests import pandas from SciServer import Authentication, Config class Task: """ The class TaskName stores the name of the task that executes the API call. """ name = None task = Ta...
# Lint as: python3 # Copyright 2019 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 ...
:param RequestId: 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 :type RequestId: str """ self.RequestId = None def _deserialize(self, params): self.RequestId = params.get("RequestId") class ListFirmwaresRequest(AbstractModel): """ListFirmwares请求参数结构体 """ def __init__(self): r""" :param PageNum: 获取的页数 :typ...
<filename>examples/inspection/plot_linear_model_coefficient_interpretation.py """ ====================================================================== Common pitfalls in the interpretation of coefficients of linear models ====================================================================== In linear models, the ta...
E501 return data def generate_packing_slip_specific_dc_with_http_info(self, distribution_center_code, order_id, **kwargs): # noqa: E501 """Generate a packing slip for this order for the given distribution center. # noqa: E501 The packing slip PDF that is returned is base 64 encoded # noqa: E501 This method makes...
<reponame>lush-tech-warriors/saleor from collections import defaultdict from typing import TYPE_CHECKING, Dict, List, Optional, Tuple import graphene from django.contrib.auth import models as auth_models from django.core.exceptions import ValidationError from django.db import transaction from ....account.error_codes ...
<reponame>pyarnold/Mailpile import copy import email.header import email.parser import email.utils import errno import mailbox import mimetypes import os import re import StringIO import threading import traceback from gettext import gettext as _ from email import encoders from email.mime.base import MIMEBase from emai...
# -*- coding: utf-8 -*- # Copyright (c) 2018-2020 <NAME> <<EMAIL>>. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, thi...
# Copyright 2017 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 ...
\"[[HEADER_RAND]]\" #include \"[[SOURCE_RAND]]\" #else #define gnu_rand rand #define gnu_srand srand #endif #endif #endif """) g_template_include_sdl = Template(""" #include \"SDL.h\" """) g_template_include_sndfile = Template(""" #include \"sndfile.h\" """) g_template_und_symbols = Template(""" #if defined(__FreeBS...
<filename>ags-ds2.py #!/usr/bin/python # -*- coding: utf-8 -*- """ags-ds2.py: A German Spy's Devil Summoner 2 ellipses challenge.""" __author__ = "TetrisFinalBoss" __version__ = "0.4.3" import sys import cv2 import numpy import pafy import re import os.path import getopt AGS_DS2_PLAYLIST = 'PL_ftpUY_ldBTtHOUQLt5irg...
agent_id in range(self.num_agents): self.info['explored_reward'].append(agent_explored_area[agent_id]) self.info['explored_ratio'].append(agent_explored_ratio[agent_id]) if self.timestep % self.args.num_local_steps == 0: agents_explored_map = np.maximum(agents_explored_map, self.transform(self.current_explored_gt[a...
<filename>linux-distro/package/nuxleus/Source/Vendor/Microsoft/IronPython-2.0.1/Lib/Kamaelia/UI/OpenGL/OpenGLDisplay.py #!/usr/bin/env python # # Copyright (C) 2005 British Broadcasting Corporation and Kamaelia Contributors(1) # All Rights Reserved. # # You may only modify and redistribute this under the terms of any o...
{ 'withscores': withscores, 'score_cast_func': score_cast_func, 'callback': callback } self._execute_command(*pieces, **options) def zrank(self, name, value, callback=None): """ Returns a 0-based value indicating the rank of ``value`` in sorted set ``name`` """ self._execute_command('ZRANK', name, value, ca...
of columns for (name, index) in controlGroupNames.items(): data[geneID][CONTROL_GROUP_KEY][name].append(vals[index]) # get values for second group of columns for (name, index) in dataGroupNames.items(): data[geneID][DATA_GROUP_KEY][name].append(vals[index]) #end else #endfor ## merge duplicates by averaging ...
import pip_setup pip_setup.install("moviepy") pip_setup.install("pygame") import Menu import pygame from moviepy.editor import * import random from Settings import * from Sprites import * from Menu import * import time import numpy as np class GAME : def __init__(self): #GAME ~initialisation~ ...
<gh_stars>0 #!/usr/bin/env python3 import sys import os import random import numpy as np import cv2 from ACT_utils import iou2d from Dataset import GetDataset sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'python')) import caffe distort_params = { 'brightness_prob': 0.5, 'brightness_delta': 32...
__init__(self, i): self.count = 0 self.iter = zip(itertools.count(1), i) def __iter__(self): return self def __next__(self): self.count, result = next(self.iter) return result def empty(): """ An empty iterator. """ return iter(tuple()) def is_empty(iterable): """ Return whether the iterable is empty...
Associate ( self ) : seg = self.CurrentSegmentation () if seg : debug(" - seg: ", seg.name) if self.chosen_map : debug(" - map: " + self.chosen_map.name) seg.set_volume_data ( self.chosen_map ) self.status ( "Map %s is now associated with %s" % (self.chosen_map.name, seg.name) ) else : self.status ( "No map ...
import json import logging from copy import deepcopy from collections import Counter from os import getenv import numpy as np import sentry_sdk from nltk.tokenize import sent_tokenize from common.greeting import greeting_spec from common.link import skills_phrases_map from common.constants import CAN_CONTINUE_PROMPT,...
<reponame>eliasall/BetterX-Cloud ## Tickets File def insertTickets(filetype, json, cursor, conn, uid): if (filetype == 'tickets'): featureAttrs = {'tickets', 'timestamp', 'uid'} cnt = 0 tblName = 'tickets' cntattr = 0 keytypevals = {} values = [] for tis in featureAttrs: keytypevals,values = appendJso...
import os import numpy as np from numpy import count_nonzero import pandas as pd import matplotlib.pyplot as plt from dimred import DimRed from scipy.sparse import random as sparse_random from scipy.sparse import csr_matrix, isspmatrix from sklearn.datasets import load_iris, load_digits, make_friedman1, make_sparse_spd...
""" Core classes for XBlocks. This code is in the Runtime layer, because it is authored once by edX and used by all runtimes. """ import functools import pkg_resources try: import simplesjson as json # pylint: disable=F0401 except ImportError: import json from webob import Response from xblock.exceptions import XB...
<filename>gdb/gdb.py<gh_stars>10-100 # To use, add source /path/to/gdb.py to your $HOME/.gdbinit file. import gdb import atexit import os import re import subprocess import tempfile import textwrap as tw from typing import Optional, List from collections import defaultdict from dataclasses import dataclass def add_sy...
# -*- coding: utf-8 -*- """ Created on Thu Sep 26 12:06:07 2013 Copyright (c) 2013-2014, CEA/DSV/I2BM/Neurospin. All rights reserved. @author: <NAME>, <NAME> @email: <EMAIL>, <EMAIL> @license: BSD 3-clause. """ from six import with_metaclass import abc import numpy as np from .utils import TOLERANCE from .utils imp...
# Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import secrets from urllib.parse import parse_qs, quote import bottle import sqlalchemy as db import uuid import yaml import common.auth as _a...
ok_zone = shared_zone_test_context.ok_zone dummy_zone = shared_zone_test_context.dummy_zone ok_zone_name = shared_zone_test_context.ok_zone["name"] dummy_zone_name = shared_zone_test_context.dummy_zone["name"] dummy_group_name = shared_zone_test_context.dummy_group["name"] rs_delete_name = generate_record_name() ...
from .BinanceTrRequests import sendRequest,sendRequestWithoutAuthorization from .UserModel import UserModel as UM from .Apihelpers import date_to_milliseconds import json import sys import traceback import os class ApiService: """ ApiServiceClass Object :param apiKey(str): Given account's api key. :param apiSecr...
= new_instancemethod(_Extrema.Extrema_SeqPCOfPCFOfEPCOfELPCOfLocateExtPC2d_ChangeValue,None,Extrema_SeqPCOfPCFOfEPCOfELPCOfLocateExtPC2d) Extrema_SeqPCOfPCFOfEPCOfELPCOfLocateExtPC2d.Remove = new_instancemethod(_Extrema.Extrema_SeqPCOfPCFOfEPCOfELPCOfLocateExtPC2d_Remove,None,Extrema_SeqPCOfPCFOfEPCOfELPCOfLocateExtPC2...
acct cont objc objc objc obj obj # obj self.app.memcache.store = {} resp = controller.PUT(req) self.assertEquals(resp.status_int, 201) self.assertEquals(resp.headers['x-copied-from'], 'c/o/o2') # negative tests # invalid x-copy-from path req = Request.blank('/a/c/o', environ={'REQUEST_METHOD': 'PUT'}, header...
'Britt', 'Britta', 'Brittaney', 'Brittani', 'Brittanie', 'Brittany', 'Brittnay', 'Brittnee', 'Brittney', 'Brittni', 'Brittnie', 'Brittny', 'Brook', 'Brooke', 'Brooklyn', 'Brooklynn', 'Bryana', 'Bryanna', 'Brylee', 'Bryn', 'Brynlee', 'Brynn', 'Buelah', 'Buena', 'Buffy', 'Bula', 'Bulah', 'Buna', 'Burnice', 'Byrd', 'B...
''' Various statistical functions. Note that many have an `add_intercept` argument and that this is True by default, which means the X matrix will have a column of ones added for the calculation of the intercept. If you are already using a design/ model matrix with an intercept term, be sure to set `add_intercept = Fal...
""" Class that plays the Reinforcement Learning agent """ # !/usr/bin/python import csv import pprint import threading import numpy as np import json import random import pathlib from datetime import datetime import time import copy from time import sleep import logging import sys from formatter_for_output import fo...
str, List[kv.Event]] class LeaseGrantRequest(Message): pb_cls = rpc_pb2.LeaseGrantRequest __slots__ = ['TTL', 'ID'] def __init__( self, TTL: int = 0, ID: int = 0 ): self.TTL = TTL self.ID = ID @classmethod def get_slot_types(cls): return [int, int] class LeaseGrantResponse(Message): pb_cls = rpc_pb2...
#! /usr/bin/env python # -*- mode: python; coding: utf-8 -*- # Copyright 2018 the HERA Collaboration # Licensed under the 2-clause BSD license. """Find and display part hookups.""" import os import copy import json from argparse import Namespace from astropy.time import Time from . import mc, cm_utils, cm_transfer, ...
for name in [label_0, label_1]: legend_label_dict[name] = name label_size = 14 assert binning_features.shape[0] == softmaxes.shape[0], 'Error: binning_features must have same length as softmaxes' #bin by whatever feature if isinstance(bins, int): _,bins = np.histogram(binning_features, bins=bins) bins = bins[0...
"DISCRETE", -100, 100, "<None>", "all"), ("Fcst", "Hazards", "DISCRETE", 21, 24+8, "HT.Y", ["FLZ050","FLZ151"]), ("Fcst", "Hazards", "DISCRETE", 24+8, 24+17, "EH.W", ["FLZ050","FLZ151"]), ("Fcst", "Hazards", "DISCRETE", 24+17, 48+9, "HT.Y", ["FLZ050","FLZ151"]), ], "checkStrings": [ "WWUS72 KTBW 062104", "NPWTBW...
(1,2,3), Nic)) # Wrong type, s/b tuple of 625 ints self.assertRaises(TypeError, self.gen.setstate, (2, ('a',)*625, Nic)) # Last element s/b an int also self.assertRaises(TypeError, self.gen.setstate, (2, (0,)*624+('a',), Nic)) # Last element s/b between 0 oraz 624 przy self.assertRaises((ValueError, OverflowError...
Add legend if legend: h = mpl.patches.Patch(facecolor='skyblue') x = mpl.patches.Patch(facecolor='g', alpha=0.0) dx = mpl.patches.Patch(facecolor='g', alpha=0.0) tri = mpl.patches.Patch(facecolor='white', alpha=0.0) ax.legend( [h, x, dx, tri], ['Histogram D(NNI)', 'D(X): %i' % D.max(), 'X: %.3f...
msg="Domain %s succesfully refreshed !" % module.params['domain']) except APIError as apiError: module.fail_json(changed=False, msg="Failed to call OVH API: {0}".format(apiError)) if module.params['domain'] and module.params['ip']: if module.check_mode: module.exit_json(changed=True, msg="DNS succesfully %s on %s ...
<reponame>metal-stack/metal-python # coding: utf-8 """ metal-api API to manage and control plane resources like machines, switches, operating system images, machine sizes, networks, IP addresses and more # noqa: E501 OpenAPI spec version: v0.15.7 Generated by: https://github.com/swagger-api/swagger-codegen.git...
<path\x0a \ d=\x22M 0,1\ 6 H 16 V 0 H 0 Z\ \x22\x0a id=\x22p\ ath235\x22 />\x0a <\ /clipPath>\x0a </d\ efs>\x0a <metadata\ \x0a id=\x22metada\ ta5\x22>\x0a <rdf:R\ DF>\x0a <cc:Wo\ rk\x0a rdf:\ about=\x22\x22>\x0a \ <dc:format>ima\ ge/svg+xml</dc:f\ ormat>\x0a <\ dc:type\x0a \ rdf:resource=\ \x22http://purl.org\ /dc/...
<reponame>MITLLRacecar/racecar-parth-kocheta<filename>labs/final/grandprix_copy.py """ Copyright MIT and Harvey Mudd College MIT License Summer 2020 Grand Prix 2021 """ ######################################################################################## # Imports ##################################################...
import logging import os import requests import shutil import tempfile import unittest from opusfilter import ConfigurationError from opusfilter.filters import * from opusfilter.util import file_download class TestLengthFilter(unittest.TestCase): def test_words(self): testfilter = LengthFilter(2, 3, 'word') case...
ERROR: type should be string, got "https://raw.githubusercontent.com/selva86/datasets/master/wwwusage.csv\n# Import data\ndf = pd.read_csv('../data/wwwusage.csv', names=['value'], header=0)\nplt.figure(figsize=(15, 2))\nplt.plot(df)\nplt.title('Original Series')\nplt.xlabel('Time')\nplt.ylabel('Value')\nplt.show()\n\nInitial eyeballing shows that there is a trend for this time series and is non-stationary. Checking using ADF:\n\nresult = adfuller(df.value.dropna())\nprint('ADF Statistic: %f' % result[0])\nprint('p-value: %f' % result[1])\n\nThe null hypothesis of the ADF test is that the time series is non-stationary. So, if the p-value of the test is less than the significance level (0.05) then you reject the null hypothesis and infer that the time series is indeed stationary. For our example, we fail to reject the null hypothesis.\n\nNext we difference our time series and check the results of the ADF test. We will also look at the ACF.\n\nplt.rcParams.update({'figure.figsize':(15,8), 'figure.dpi':120})\n\n# Original Series\nfig, axes = plt.subplots(3, 2, sharex=True)\naxes[0, 0].plot(df.value); axes[0, 0].set_title('Original Series')\nplot_acf(df.value, ax=axes[0, 1])\n\n# 1st Differencing\naxes[1, 0].plot(df.value.diff()); axes[1, 0].set_title('1st Order Differencing')\nplot_acf(df.value.diff().dropna(), ax=axes[1, 1])\n\n# 2nd Differencing\naxes[2, 0].plot(df.value.diff().diff()); axes[2, 0].set_title('2nd Order Differencing')\nplot_acf(df.value.diff().diff().dropna(), ax=axes[2, 1])\n\nplt.show()\n\nprint('ADF Statistic for 1st Order Differencing')\nresult = adfuller(df.value.diff().dropna())\nprint('ADF Statistic: %f' % result[0])\nprint('p-value: %f' % result[1])\nprint('Critical Values:')\nfor key, value in result[4].items():\n print('\\t%s: %.3f' % (key, value))\n\nprint('\\n ADF Statistic for 2nd Order Differencing')\nresult = adfuller(df.value.diff().diff().dropna())\nprint('ADF Statistic: %f' % result[0])\nprint('p-value: %f' % result[1])\nprint('Critical Values:')\nfor key, value in result[4].items():\n print('\\t%s: %.3f' % (key, value))\n\nGiven the results of our ACF and ADF, we can see that our time series reachees stationarity after two orders of differencing. However, the ACF of the 2nd order differencing goes into the negative zone fairly quick. This can indicates that the series might have been over differenced. It is now up to us if we want consider the first or second order differencing for our ARIMA models.\n\n#### Finding the order of the AutoRegressive term *p*\n\nAs we have discussed previously, we can look at the PACF plot to determine the lag for our AR terms. Partial autocorrelation can be imagined as the correlation between the series and its lag, after excluding the contributions from the intermediate lags. So, PACF sort of conveys the pure correlation between a lag and the series. That way, we will know if that lag is needed in the AR term or not.\n\n# PACF plot of 1st differenced series\nplt.rcParams.update({'figure.figsize':(15,2.5), 'figure.dpi':120})\n\nfig, axes = plt.subplots(1, 2, sharex=True)\naxes[0].plot(df.value.diff()); axes[0].set_title('1st Differencing')\naxes[1].set(ylim=(0,5))\nplot_pacf(df.value.diff().dropna(), ax=axes[1])\n\nplt.show()\n\nImmediately, we can observe that our PACF returns sigificance at Lag 1 and Lag 2, meaning it crosses the significance limit (blue region). We can also observe significance at higher order terms but note that given the amount of lag that we are testing, it is statistically probable to see random spikes in our PACF and ACF plots. *Although this can also be attributed to Seasonality which will be tackled separately.*\n\nWith this, we can now decide to use $p = 2$ for our ARIMA model.\n\n#### Finding the order of the Moving Average term *q*\n\nSimillar to how we determined $p$, we will now look at the ACF to determine the $q$ terms to be considered for our MA. The ACF tells how many MA terms are required to remove any autocorrelation in the stationary series.\n\n# ACF plot of 1st differenced series\nplt.rcParams.update({'figure.figsize':(15,4), 'figure.dpi':120})\n\nfig, axes = plt.subplots(1, 2, sharex=True)\naxes[0].plot(df.value.diff()); axes[0].set_title('1st Differencing')\naxes[1].set(ylim=(0,1))\nplot_acf(df.value.diff().dropna(), ax=axes[1])\n\nplt.show()\n\nOur results for the ACF is not as apparent compared to our PCF. We can observed several ACF terms that is above our significance level. This may be attritbuted to the fact that our model has a weak stationarity. This may also be caused by the fact that our time series is not perfectly MA and is an ARIMA model. For now, let's consider $q = 3$.\n\n## Building the ARIMA model\nNow that we’ve determined the values of p, d and q, we have everything needed to fit the ARIMA model. Let's implement using this dataset first before we move on to a deeper look at the implementation of ARIMA in the next section. Let’s use the ARIMA() implementation in statsmodels package. As computed, we will use ARIMA(2,1,3):\n\nmodel = ARIMA(df.value, order=(2,1,3))\nmodel_fit = model.fit(disp=0)\nprint(model_fit.summary())\n\nThere's quite a bit of information to unpack from the summary. Generally, we are interested in the Akaike’s Information Criterion (AIC), coefficients of our AR and MA terms (coef_), and the p-values of the terms (P>|z|). We need the p-values to be less than 0.05 to be significant, which means that our model failed to reach significance for the AR and MA terms. Let's try to be conservative and use small values for p and d, i.e. ARIMA(1,1,1), as given by the p-values of AR1 and MA1 in our results.\n\nmodel = ARIMA(df.value, order=(1,1,1))\nmodel_fit = model.fit(disp=0)\nprint(model_fit.summary())\n\nImmediately, we can see that the p-values is now <<0.05 for both the AR and MA terms and is highly significant. We will now check the residuals of our time-series to ensure that we will not see patterns and will have a constant mean and variance.\n\n# Plot residual errors\nresiduals = pd.DataFrame(model_fit.resid)\nfig, ax = plt.subplots(1,2, figsize=(15,2.5))\nresiduals.plot(title=\"Residuals\", ax=ax[0])\nresiduals.plot(kind='kde', title='Density', ax=ax[1])\nplt.show()\n\nThe residuals is a good final check for our ARIMA models. Ideally, the residual errors should be a Gaussian with a zero mean and uniform variance. With this, we can now proceed with fitting our initial time series with our model.\n\n# Actual vs Fitted\nfig, ax = plt.subplots(figsize=(15,2))\nax = df.plot(ax=ax)\nfig = model_fit.plot_predict(85, 100, dynamic=False, ax=ax, plot_insample=False)\nplt.show()\n\nWhen we set dynamic=False the in-sample lagged values are used for prediction. That is, the model gets trained up until the previous value to make the next prediction. We can also call this as a **walk-forward** or **one-step ahead** prediction.\n\nHowever, we should note two things:\n1. We used the entire time series to train our model\n2. Some of the use-cases that we will be tackling will require us to forecast t-steps ahead\n\nWe will be solving the first point in the next section by tackling real-world datasets. The second point can be solved immediately using dynamic=True argument shown below.\n\n# Actual vs Fitted\nfig, ax = plt.subplots(figsize=(15,2))\nax = df.plot(ax=ax)\nfig = model_fit.plot_predict(90, 110, dynamic=True, ax=ax, plot_insample=False)\nplt.show()\n\nNotice that our confidence interval is now increasing as we go farther our given data set since we will be compounding errors given by out forecasted values. Also note that generally, our ARIMA model captured the direction of the trend of our time series but is consistently lower than the actual values. We can correct this by varying the parameters of our ARIMA models and validating using performance metrics. \n\n## Implementation and Forecasting using ARIMA\n\n\nGiven the steps discussed in the first three sections of this notebook, we can now create a framework of how we can approach ARIMA models in general. We can use a modified version of the Hyndman-Khandakar algorithm (Hyndman & Khandakar, 2008), which combines unit root tests, minimisation of the AIC and MLE to obtain an ARIMA model. The steps are outlined below: \n\n1. The differencing term d is determined using repeated ADF tests.\n2. The values of p and q are chosen based on the AIC, ACF, and PACF of our differenced time series.\n3. Use a step-wise traversal of our parameter space (+-1) for p, d, and q to find a lower AIC. *We can use insights and heuristics to observe our ACF and PACF to determine if we need to add or reduce our p, d, and q.*\n4. Check the residuals for Gaussian Distribution to establish stationarity.\n\nOr in our case, we will instead use a grid-search algorithm to find automatically configure our ARIMA and find our hyperparameters. We will search values of p, d, and q for combinations (skipping those that fail to converge), and find the combination that results in the best performance on the test set. We use grid search to explore all combinations in a subset of integer values.\n\nSpecifically, we will search all combinations of the following parameters:\n\np: 0 to 4. d: 0 to 3. q: 0 to 4. This is (4 * 3 * 4), or 48, potential runs of the test harness and will take some time to execute.\n\nThe complete worked example with the grid search version of the"
False means that AzureML will create a python environment based on the Conda dependencies specification. """ return pulumi.get(self, "user_managed_dependencies") @pulumi.output_type class ModelEnvironmentDefinitionResponseResponseR(dict): """ Settings for a R environment. """ @staticmethod def __key_warning(ke...
if fastq_gzipped: cmd = [['gzip', '-d', '-c', os.path.basename(fastq_path)]] else: cmd = [['cat', os.path.basename(fastq_path)]] cmd.append(['split', '-l', str(chunk_lines), '--filter=pigz -p {} > $FILE.fq.gz'.format(max(1, int(context.config.fq_split_cores) - 1)), '-', '{}-chunk.'.format(fastq_name)]) context...
<gh_stars>1-10 """The classes used to represent various information about persons on IMDb. This will contain classes for both information gathered from the datasets provided by IMDb and information scraped from IMDb web pages. Class names ending with "`Scrape`" are scraped from the web pages. Otherwise, they are gathe...