input
stringlengths
2.65k
237k
output
stringclasses
1 value
<reponame>framawiki/pywikibot # -*- coding: utf-8 -*- """ Script to copy files from a local Wikimedia wiki to Wikimedia Commons. It uses CommonsHelper to not leave any information out and CommonSense to automatically categorise the file. After copying, a NowCommons template is added to the local wiki's file. It uses a...
be done drone_x_range = [.1, -.1] drone_y_range = [.1, -.1] drone_z_range = [.025, -.025] rot_matrix = R.from_euler('ZYX',[self.quad.state[5], self.quad.state[4], self.quad.state[3]],degrees=False).as_dcm().reshape(3,3) drone_pos = np.array([self.quad.state[0], self.quad.state[1], self.quad.state[2]]) edge_ind = ...
#!/usr/bin/env python3 # --------------------( LICENSE )-------------------- # Copyright (c) 2014-2021 Beartype authors. # See "LICENSE" for further details. ''' Project-wide :pep:`544`-compliant type hint utilities. This private submodule is *not* intended for importation by downstream callers. ''' # .................
<filename>src/app/beer_garden/local_plugins/manager.py # -*- coding: utf-8 -*- import string import time from concurrent.futures import ThreadPoolExecutor, wait from concurrent.futures._base import Future from enum import Enum import json import logging import os import sys from brewtils.models import Event, Events, R...
should contain the date, the payment currency and the payment rate specified on the voucher amount_in_company_currency = self.pool.get('res.currency').compute(cr, uid, currency_id, company_currency.id, amount, context=context) res['value']['paid_amount_in_company_currency'] = amount_in_company_currency return res ...
<gh_stars>10-100 #!/usr/bin/env python """ Copyright 2010-2018 University Of Southern California 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 ...
value is not None else _Rail.Type.Gap ) if atEitherEnd or value is not None : label = GafferUI.Label( path ) label.setToolTip( "Click to select \"%s\"" % path ) self.__connections.extend( [ label.enterSignal().connect( lambda gadget : gadget.setHighlighted( True ) ), label.leaveSig...
for each repeat Instr2Text.setText('When the image of a %s is shown you will press the key that is on the SAME side of the screen that the %s is shown on. \n\nFor example, a correct response would be pressing the "1" key when the %s is on the left side of the screen\n\nPress space to continue.' % (congr_txt,congr_txt,c...
<gh_stars>0 import numpy as np import pt_utils ### WARNING: NOTHING IN THIS FILE IS CHROMATIC! ### *CHROMATIC OPERATIONS CAN BE FOUND IN THE pt_musicutils.py FILE ### ALL OPERATIONS ARE BASED ON THE F-LYDIAN NOTE PARADIGM: 0b111111100000 # ================================================================= thirds_only ...
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # Copyright and License for this python code - Apache 2.0+ license ========================================================================== Copyright (c) 2017, <NAME>. All rights reserved. THIS SOFTWARE PROVIDED...
id: Resource ID. :vartype id: str :ivar name: Resource name. :vartype name: str :ivar type: Resource type. :vartype type: str :ivar etag: A unique read-only string that changes whenever the resource is updated. :vartype etag: str :ivar kind: Required. Whether the rule is custom or default.Constant filled by ser...
<gh_stars>1-10 # # Hi all, # this is the Python code I used to make the visualization "Temperature circle" # (https://twitter.com/anttilip/status/892318734244884480). # Please be aware that originally I wrote this for my tests only so the # code was not ment to be published and is a mess and has no comments. # Feel fre...
'/fire_layer_1.png', b + '/textures/blocks') if 'fire_layer_1.png' in file_names: os.rename(os.path.join(b + '/textures/blocks', 'fire_layer_1.png'), os.path.join(b + '/textures/blocks', str('fire_1.png'))) except: pass try: file_path = a + '/assets/minecraft/textures/blocks' file_names = os.listdir(f...
<filename>runtests.py #!/usr/bin/env python # -*- coding: utf-8 -*- # # This software is licensed as described in the file LICENSE, which # you should have received as part of this distribution. """Functional tests for the Trac-GitHub plugin. Trac's testing framework isn't well suited for plugins, so we NIH'd a bit. ...
""" nc2pd ~~~~~ A thin python-netCDF4 wrapper to turn netCDF files into pandas data structures, with a focus on extracting time series from regularly spatial gridded data (with the ability to interpolate spatially). Copyright 2015 <NAME> License: MIT (see LICENSE file) """ from __future__ import print_function fro...
= MaxNLocator(nbins=nbins, steps=steps).tick_values(min(sMin,-sMax), max(sMax,-sMin)) else: levels = MaxNLocator(nbins=nbins, steps=steps).tick_values(sMin, sMax) elif len(clim)==2: levels = MaxNLocator(nbins=nbins, steps=steps).tick_values(clim[0], clim[1]) else: levels = clim nColors = len(levels)-1 if extend ...
`Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json']) if not header_params['Accept']: del header_params['Accept'] # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json']) # Authentication setting ...
= JobStatus.new run['status_prov'] += ', HAZUS complete' self.pg_db.update_job_status(run['id'], run['status_prov']) # was there a failure elif job_pod_status.startswith('Failed'): # remove the job and get the final run status job_status = self.k8s_create.delete_job(run) self.logger.error(f"Error: Run status {r...
nullable=False, index=False) child_track_id = Column(Integer, nullable=False, index=False) PrimaryKeyConstraint(parent_track_id, child_track_id) def __repr__(self): return f"<Remix(parent_track_id={self.parent_track_id},\ child_track_id={self.child_track_id})>" class Play(Base): __tablename__ = "plays" id = C...
Sets from BSR ''', 'bsr_maximum_global_candidate_rp_cache', 'Cisco-IOS-XR-ipv4-pim-cfg', False), _MetaInfoClassMember('warning-threshold', ATTRIBUTE, 'int' , None, None, [('1', '10000')], [], ''' Set threshold to print warning ''', 'warning_threshold', 'Cisco-IOS-XR-ipv4-pim-cfg', False), ], 'Cisco-IOS-XR...
p * w # Update the probability that no skeleton yet is refinable. refinable_skeleton_not_found_prob *= (1 - refinement_prob) except (PlanningTimeout, PlanningFailure): # Note if we failed to find any skeleton, the next lines add # the upper bound with refinable_skeleton_not_found_prob = 1.0, # so no special actio...
= _mod_rank_best _ranks.append([(Path(bn), gas, *i) for i in _mod_rank]) Mod_Rank = pd.DataFrame( [a for i in _ranks for a in i], columns=["PAR_file", "Gas", "Model_EEC", "rank_len_gr", f"rank_{errtype}_mean"], ) Best_Mod_Rank = Mod_Rank.loc[ (Mod_Rank.rank_len_gr > 6) & (Mod_Rank[f"rank_{errtype}_mean"] < 30) ...
<gh_stars>0 # -*- coding: utf-8 -*- """Master Thesis Work Copyright (c) 2018, <NAME> All rights reserved. The master thesis work has been carried out at the School of Engineering in Jönköping in the subject area “Sentiment Analysis using Multi-label Machine Learning Techniques”. The work is a part of the two-years ...
#!/usr/bin/env python import numpy as np import matplotlib.pyplot as plt import sys sys.path.insert(0, "./activations") sys.path.insert(1, "./utils") from relu import * from sigmoid import * from softmax import * """ TODO: check if softmax can be included in linear activation or it must be directly combined with cros...
kwargs: The argname=argval items that the functions should draw from. :return: >>> def add(a, b: float = 0.0) -> float: ... return a + b >>> def mult(x: float, y=1): ... return x * y >>> def formula1(w, /, x: float, y=1, *, z: int = 1): ... return ((w + x) * y) ** z >>> commands = extract_commands( ... (add, ...
0.00000000035 * math.cos(3.09037355598 + 77211.44104153418 * self.t) Z0 += 0.00000000035 * math.cos(5.86095139046 + 18207.81398823521 * self.t) Z0 += 0.00000000038 * math.cos(1.94104879109 + 76044.9523205358 * self.t) Z0 += 0.00000000032 * math.cos(1.45277855585 + 78270.82297172339 * self.t) Z0 += 0.00000000044 * m...
'hp': 2100, 'sp': 6000, 'maxCargo': 3, 'maxCrew': 8, 'maxCannons': 14, 'maxBroadsides': 20, 'rammingPower': 900, 'acceleration': 1.1000000000000001 * defaultAcceleration, 'maxSpeed': 0.80000000000000004 * defaultMaxSpeed, 'reverseAcceleration': 0.69999999999999996 * defaultReverseAcceleration, 'maxReverseSpee...
the boot device persistently :raises: Any exception from set_boot_device except IPMIFailure (setting of boot device using ipmi is expected to fail). """ try: manager_utils.node_set_boot_device(task, device, persistent=persistent) except exception.IPMIFailure: with excutils.save_and_reraise_exception() as ctxt: ...
from pypy.rpython.memory.gctransform.transform import GCTransformer from pypy.rpython.memory.gctransform.support import find_gc_ptrs_in_type, \ get_rtti, ll_call_destructor, type_contains_pyobjs, var_ispyobj from pypy.rpython.lltypesystem import lltype, llmemory from pypy.rpython import rmodel from pypy.rpython.memory...
############################################################################### # Copyright 2018 The AnPyLar Team. All Rights Reserved. # Use of this source code is governed by an MIT-style license that # can be found in the LICENSE file at http://anpylar.com/mit-license ################################################...
""" --- --- --- """ datafpath = Paths.ppr_sims + d3class.sim + '/' + __rootoutdir__ figname = "{}_rl{}.png".format(v_n, rl) o_plot = PLOT_MANY_TASKS() o_plot.gen_set["figdir"] = datafpath o_plot.gen_set["type"] = "cartesian" o_plot.gen_set["figsize"] = (4.2, 8.0) # <->, |] # to match hists with (8.5, 2.7) o_pl...
# Copyright 2021 Phasecraft 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, ...
}) self.__dhcpv6_relay_forw_sent = t if hasattr(self, '_set'): self._set() def _unset_dhcpv6_relay_forw_sent(self): self.__dhcpv6_relay_forw_sent = YANGDynClass(base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name="dhcpv6-relay-fo...
@staticmethod def get_points_single(featmap_size, stride, dtype, device): h, w = featmap_size x_range = torch.arange( 0, w * stride, stride, dtype=dtype, device=device) y_range = torch.arange( 0, h * stride, stride, dtype=dtype, device=device) y, x = torch.meshgrid([y_range, x_range]) points = torch.stack( (x....
<filename>reordering_generators/c_generator.py """ Reordering generator for C source code. This is an ANTLR generated parse tree listener, adapted to walk a Python parse tree, randomly introduce multi scale reorderings and regenerate the source code with these reorderings. """ import random from antlr4 import ParseTr...
# BEGIN_COPYRIGHT # # Copyright 2009-2018 CRS4. # # 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 ...
count(self): return MemoryPersistenceHandler.count(self) @_checkDumpException def reset(self, status): return MemoryPersistenceHandler.reset(self, status) def shutdown(self): self.timer.cancel() self._dump() class RolloverFilePersistenceHandler(FilePersistenceHandler): """Load and dump resources from...
refresh token ({}) was not valid.'.format(current_user.name, character_id, refresh_token)) characterCard = get_character_card(character_id, preston, access_token) if characterCard is None: return redirect(url_for('esi_parser.index')) return render_template('esi_parser/audit_skills.html', character_id=character_i...
import warnings import logging import pandas as pd from functools import partial from collections import defaultdict from dae.utils.helpers import str2bool from dae.variants.attributes import Role, Sex, Status from dae.backends.raw.loader import CLILoader, CLIArgument from dae.pedigrees.family import FamiliesData, P...
import unittest from zope.component import getSiteManager class TestDummyRootFactory(unittest.TestCase): def _makeOne(self, environ): from pyramid.testing import DummyRootFactory return DummyRootFactory(environ) def test_it(self): environ = {'bfg.routes.matchdict':{'a':1}} factory = self._makeOne(environ) self...
unique_qcomponents, chip_name) if table_name == 'junction': self.chip_info[chip_name]['junction'] = deepcopy(table) else: # For every chip, and layer, separate the "subtract" and "no_subtract" elements and gather bounds. # dict_bounds[chip_name] = list_bounds self.gather_subtract_elements_and_bounds( chip_name...
from pygrank.algorithms.utils import MethodHasher, call, ensure_used_args, remove_used_args from pygrank.core.signals import GraphSignal, to_signal, NodeRanking from pygrank.core import backend, GraphSignalGraph, GraphSignalData from typing import Union, Optional class Postprocessor(NodeRanking): def __init__(self, ...
"""Actions for linking object code produced by compilation""" load(":private/packages.bzl", "expose_packages", "pkg_info_to_ghc_args") load("@bazel_skylib//lib:paths.bzl", "paths") load( ":private/path_utils.bzl", "get_lib_name", "is_shared_library", "is_static_library", "ln", ) load(":private/pkg_id.bzl", "pkg_i...
[None, 210, 310], } dataset_in = test_helpers.build_dataset({region_as: metrics_as, region_sf: metrics_sf}) dataset_in.write_to_dataset_pointer(pointer) # Compare written file with a string literal so a test fails if something changes in how the # file is written. The literal contains spaces to align the columns...
from jinja2 import Template from shutil import which from time import gmtime, strftime import argparse import fnmatch import functools import getpass import logging import operator import os import pwd import re import shlex import signal import socket import subprocess import sys import time """ TODO: - More optiona...
<gh_stars>1-10 # External Dependencies import ldap # Internal Dependencies import datetime import re class activedirectory: # User configurable # Which account states will you allow to change their own password? # Any combination of: # ['acct_pwd_expired', 'acct_expired', 'acct_disabled', 'acct_locked'] can_cha...
np.nan tcr_f = np.nan elif model == 'mri_esm2_0': mrun_f = 'r1i1p1f1' doi_f = '10.2151/jmsj.2019-051' atmos_f = 'MRI-AGCM3.5 (TL159; 320 x 160 longitude/latitude; 80 levels; top level 0.01 hPa)' surface_f = ' HAL 1.0' ocean_f = 'MRI.COM4.4 (tripolar primarily 0.5 deg latitude/1 deg longitude with meridional refi...
= f'Book{book_index}' self.course.textbooks = self.books self.course.pdf_textbooks = self.books self.course.html_textbooks = self.books def test_pdf_textbook_tabs(self): """ Test that all textbooks tab links generating correctly. """ type_to_reverse_name = {'textbook': 'book', 'pdftextbook': 'pdf_book', 'htmlt...
E501 collection_formats = {} path_params = {} if 'anti_malware_id' in params: path_params['antiMalwareID'] = params['anti_malware_id'] # noqa: E501 query_params = [] header_params = {} if 'api_version' in params: header_params['api-version'] = params['api_version'] # noqa: E501 form_params = [...
now self.fluxBoundaryConditions=fluxBoundaryConditionsDict self.advectiveFluxBoundaryConditionsSetterDict=advectiveFluxBoundaryConditionsSetterDict self.diffusiveFluxBoundaryConditionsSetterDictDict = diffusiveFluxBoundaryConditionsSetterDictDict #determine whether the stabilization term is nonlinear self.stabiliz...
di=None, # Diameter, epsilon = 0.0006, ): #Check types and converto to np.ndarray assert isinstance(pressure,(int,float,np.ndarray,np.float64,np.int64)) pressure = np.atleast_1d(pressure) assert isinstance(temperature,(int,float,np.ndarray,np.float64,np.int64)) temperature = np.atleast_1d(temperature) assert i...
"writeonly" pipes may only send packets from client to service. See ``MemberDefinition_Direction`` constants for possible return values. :rtype: int """ return self.__innerpipe.Direction() @property def RequestPacketAck(self): """ Get if pipe endpoint should request packet acks Packet acks are...
import itertools def sort_unique(edges): """Make sure there are no duplicate edges and that for each ``coo_a < coo_b``. """ return tuple(sorted( tuple(sorted(edge)) for edge in set(map(frozenset, edges)) )) # ----------------------------------- 2D ------------------------------------ # def check_2d(coo, Lx,...
<reponame>sahilPereira/2d-driving-simulator import os import pygame from math import tan, radians, degrees, copysign, ceil from pygame.math import Vector2 import stackelbergPlayer as SCP from random import randrange import random import math import numpy import pandas as pd import pickle from argparse import...
Raises: None Examples: .. code-block:: python import paddle from paddle.nn import Conv1D import numpy as np x = np.array([[[4, 8, 1, 9], [7, 2, 0, 9], [6, 9, 2, 6]]]).astype(np.float32) w=np.array( [[[9, 3, 4], [0, 0, 7], [2, 5, 6]], [[0, 3, 4], [2, 9, 7], [5, 6, 8]]]).astype(np.float32) x_t = paddle...
'Discussion'), ('passed_swc_demo', 'SWC Demo'), ] try: return [name for field, name in fields if not getattr(self, field)] except AttributeError as e: raise Exception('Did you forget to call ' 'annotate_with_instructor_eligibility()?') from e def get_missing_dc_instructor_requirements(self): """Returns set of...
self.last_buf = self.connection.buf # Set up a normal response for the next request self.connection = test_urllib.fakehttp( b'HTTP/1.1 200 OK\r\n' b'Content-Length: 3\r\n' b'\r\n' b'123' ) return result handler = Handler() opener = urllib.request.build_opener(handler) tests = ( (b'/p\xC3\xA5-dansk/', b'/p%C...
#! /usr/bin/env python # """ Matplotlib_user_interface.py is an interactive plotting tool using matplotlib. This is intended to be a front-end for a number of MATPLOTLIB functions similar in general usage to "xmgrace" (although not intending to duplicate all the xmgrace funcionality...). From the interface one is able...
<reponame>AndreaVoltan/MyKratos7.0 import bisect as bi import numpy as np import h5py from KratosMultiphysics import * from KratosMultiphysics.DEMApplication import * from KratosMultiphysics.SwimmingDEMApplication import * from DEM_procedures import KratosPrint as Say import json def DeleteDataSet(file_or_group, dset_...
<gh_stars>1-10 import numpy as np import torch class BoxCoder(object): def __init__(self, weights1=(10., 10., 10., 10., 15.), weights2=(3., 3., 1.5, 1.5)): self.weights1 = weights1 self.weights2 = weights2 def encode(self, ex_rois, gt_rois): ex_widths = ex_rois[:, 2] - ex_rois[:, 0] ex_heights = ex_rois[:, 3] ...
import numpy as np from confidenceMapUtil import FDRutil import argparse, math, os, sys from argparse import RawTextHelpFormatter import time def compute_padding_average(vol, mask): mask = (mask > 0.5).astype(np.int8) average_padding_intensity = np.mean(np.ma.masked_array(vol, mask)) return average_padding_intensi...
False .. attribute:: device_description Device Name **type**\: str **length:** 0..50 **config**\: False .. attribute:: units Units of variable being read **type**\: str **length:** 0..50 **config**\: False .. attribute:: device_id Identifier for this device **type**\: int ...
☆") else: if wait["AutoCancel"] == True: if op.param3 in Bots: pass else: cl.cancelGroupInvitation(op.param1, [op.param3]) else: if op.param3 in wait["blacklist"]: cl.cancelGroupInvitation(op.param1, [op.param3]) cl.sendText(op.param1, "Blacklist Detected") else: pass if op.type == 13...
in range(n_types): effort_searching_simulated[ type_idx, : ] = interpolate_2d_ordered_to_unordered( hc_grid_reduced_h_a, assets_grid_h_a, policy_effort_searching[type_idx, :, :, period_idx], hc_simulated[type_idx, :], assets_simulated[type_idx, :], ) effort_searching_loss_simulated[ type_idx, : ] = interpol...
Screen size :type size: Size :raises ValueError: In case of unknown unit value :return: rectangle in pixel units :rtype: RectWithUnit """ if size is None: return None if not isinstance(size, Size) and not isinstance(size, tuple): raise ValueError('Invalid parameter. Expected instance of Size or tuple') w = ...
the cache entry, :param sample: a sample to compare the stored value with, :param value: new value for the given key, :param key_hint: (optional) Ignite data type, for which the given key should be converted, :param sample_hint: (optional) Ignite data type, for whic the given sample should be converted :param va...
<reponame>celiafish/VisTrails ############################################################################### ## ## Copyright (C) 2011-2014, NYU-Poly. ## Copyright (C) 2006-2011, University of Utah. ## All rights reserved. ## Contact: <EMAIL> ## ## This file is part of VisTrails. ## ## "Redistribution and use in sourc...
# Copyright (c) 2001-2013 WorldViz LLC. # All rights reserved. # Changed function removeSensor() so it will correctly report no active sensor after one has been removed import viz import math import vizact import vizmat import viztask import vizshape # Default color for debug shapes DEFAULT_DEBUG_COLOR = [1,0,1] #...
"""tests/test_output_format.py. Tests the output format handlers included with Hug Copyright (C) 2016 <NAME> 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 withou...
import math class Reward: def __init__(self, verbose=False): self.first_racingpoint_index = None self.verbose = verbose def reward_function(self, params): # Import package (needed for heading) import math ################## HELPER FUNCTIONS ################### def dist_2_points(x1, x2, y1, y2): return ab...
from tkinter import Tk from tkinter import ttk from tkinter import * from tkinter import messagebox from ttkthemes import ThemedTk from PIL import ImageTk, Image import PIL from ..model.Author import * from ..model.Book import * from ..model.Reader import * from ..model.Publisher import * from ..sqlTools.BorrowTools ...
"blanks", "stig", "puncture", "spank", "utah", "booing", "abs", "minimal", "gals", "flashes", "andrei", "requirements", "greenhouse", "marx", "'ma", "vermont", "comprehend", "canoe", "baton", "arsehole", "graduating", "partially", "sensing", "kinky", "titans", "microscope", "intimidating", "r...
:param min: Lower boundary (inclusive) to check against. :param max: Upper boundary (inclusive) to check against. :param exclude_max: Exclude the upper boundary `max` if set to `true`. Defaults to `false`. :return: `true` if `x` is between the specified bounds, otherwise `false`. """ return process('between', x=x...
<gh_stars>1-10 """ Module for network components such as buses, lines and transformers """ import collections import warnings import math import numpy as np from component_base import Branch, Component from monsterexceptions import ( PsseBaseException, PsseWnddtException, PsseMacdatdException ) from monsterpsspy im...
return SeqBasedSymbolicStr(self.var) def __hash__(self): return hash(self.__str__()) @staticmethod def _concat_strings( a: Union[str, "SeqBasedSymbolicStr"], b: Union[str, "SeqBasedSymbolicStr"] ) -> Union[str, "SeqBasedSymbolicStr"]: assert not is_tracing() # Assumes at least one argument is symbolic and not...
# WARNING: This is an automatically generated file and will be overwritten # by CellBlender on the next model export. import mcell as m # ---- Sphere2 ---- Sphere2_vertex_list = [ [0.000573527067899704, 1.1245698928833, -0.943746387958527], [0.724180817604065, 0.598844587802887, -0.39096587896347], [-0.275814503...
self.params.retry_delay, self._on_connect_timer) else: # TODO connect must not call failure callback from constructor. The # current behavior is error-prone, because the user code may get a # callback upon socket connection failure before user's other state # may be sufficiently initialized. Constructors must eit...
< to.opidx def points_above_at(self, at): return self.at.opidx < at.opidx def i_points_above_at(self, idx): return self.at.opidx < idx def points_to(self, to): return self.to == to def points_at(self, at): return self.at == at def add_dependency(self, at, to, arg): self.args.append((at,arg)) def set_faila...
import sys import os ############################################################################################################ # Class: FileSystem # # Objectif : implémenter les fonctions pour les opérations nécessaires de systeme de gestion des fichiers. # ########################################################...
try: from django.db.models import Prefetch, F, Value, OuterRef, Subquery except ImportError: raise Exception('django must be installed') import copy from pyresource.executor import Executor from pyresource.translator import ResourceTranslator from pyresource.resolver import RequestResolver from pyresource.exceptions...
URITemplate(org["public_members_url"]) self.repos_url = org["repos_url"] self.url = self._api = org["url"] self.type = "Organization" def _repr(self): display_name = "" name = getattr(self, "name", None) if name is not None: display_name = ":{}".format(name) return "<{s.class_name} [{s.login}{display}]>".form...
<filename>tests/test_response_parser.py # Copyright (c) 2014, <NAME> # Released subject to the New BSD License # Please see http://en.wikipedia.org/wiki/BSD_licenses ''' Unit tests for the FetchTokeniser and FetchParser classes ''' from __future__ import unicode_literals from datetime import datetime from imapclien...
fclusterdata(pairs, max_dist, criterion="distance") # Finds how many clusters there are, and how many points belong to each cluster uniq_vals, uniq_cnts = np.unique(cluster_inds, return_counts=True) # Choose the cluster with the most points associated with it chosen_clust = uniq_vals[np.argmax(uniq_cnts)] # Retri...
<gh_stars>1-10 import os import glob from ctypes import CDLL, c_int, c_void_p, c_double from typing import Optional import numpy as np from scipy.linalg import blas from scipy.sparse import csr_matrix libdir = os.path.dirname(os.path.realpath(__file__)) try: libfile = glob.glob('{}/liblinalg_kernels*.so'.format(libdi...
list() for n in range(len(token)): l.append(''.join(char_templates(token[n]))) if n < MPL[0] or 'D' not in l: continue for p in itertools.product(l): yield p if n == len(token) - 1: yield '{}$'.format(p) # Ngram extraction and matching def ngram_iter(v, n, bounds = False): if len(v) < n: return it...
<gh_stars>0 """ Copyright 2010 <NAME> <<EMAIL>> This file is part of PyCAM. PyCAM is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PyCAM is...
<filename>recent2.py #!/usr/bin/env python #https://github.com/kislyuk/argcomplete#synopsis import argcomplete import argparse import hashlib import json import os import re import socket import sqlite3 import sys import time from pathlib import Path from tabulate import tabulate from datetime import datetime # pip in...
are NOT set in the regular parameters if isinstance(a_table, dict): if a_format is not None or a_header is not None: raise ValueError("If you specify the a_table to be a dictionary of values, then you should NOT specify " "a_format, a_header or a_partition_by separately because they should be specified in the t...
import numpy as np import matplotlib.pyplot as plt from sklearn.datasets import make_blobs from sklearn.cluster import KMeans from sklearn import metrics from matplotlib import animation from PIL import Image import matplotlib.patches as mpatches from math import pi from numpy import cos, sin import copy def cal_cente...
"RENAME TO" clause. """, fields=[ Field( 'new_name', 'ASTPathExpression', tag_id=2, field_loader=FieldLoaderMethod.REQUIRED), ], extra_public_defs=""" std::string GetSQLForAlterAction() const override; """) gen.AddNode( name='ASTSetCollateClause', tag_id=251, parent='ASTAlterAction', comment=""" ALTER...
# Code Taken from https://github.com/LYH-YF/MWPToolkit # -*- encoding: utf-8 -*- # @Author: <NAME> # @Time: 2021/08/29 11:10:20 # @File: multi_head_attention.py import numpy as np import torch from torch import nn from torch.nn import functional as F from utils.enum_type import EPT class MultiHeadAttention(nn.Module)...
e=VLCException() return libvlc_vlm_del_media(self, psz_name, e) if hasattr(dll, 'libvlc_vlm_set_enabled'): def vlm_set_enabled(self, psz_name, b_enabled): """Enable or disable a media (VOD or broadcast). @param psz_name: the media to work on @param b_enabled: the new status """ e=VLCException() return libvlc_vl...
text_loc_x : str, default None The key in the 'text' to locate the text_key for the ``pandas.DataFrame.index`` labels text_loc_y : str, default None The key in the 'text' to locate the text_key for the ``pandas.DataFrame.columns`` labels display : {'x', 'y', ['x', 'y']}, default None Text axes : {'x', 'y', ['x'...
use (browse_record), either the original one if it only belongs to this group, or the copy.""" if len(rule.groups) == 1: return rule # duplicate it first: rule_obj = self.pool.get('ir.rule') new_id = rule_obj.copy(cr, UID_ROOT, rule.id, default={ 'name': '%s %s' %(rule.name, _('(Duplicated for modified sharing ...
import networkx as nx from pymnet import * import random import matplotlib import cascade as cas import statistics import math import time import csv matplotlib.use('TkAgg') nodes = 500 layers = 3 intra_thres = 0.2 inter_thres = 0.2 attack_size = 10 attack_point = (0.5, 0.5) attack_type = "spatial_number" # choose o...
#!/usr/bin/env python # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """Nipype : Neuroimaging in Python pipelines and interfaces package. Nipype intends to create python interfaces to other neuroimaging packages and create an API for specifying a full ...
test_to_dask_dataframe_dim_order(self): values = np.array([[1, 2], [3, 4]], dtype=np.int64) ds = Dataset({"w": (("x", "y"), values)}).chunk(1) expected = ds["w"].to_series().reset_index() actual = ds.to_dask_dataframe(dim_order=["x", "y"]) assert isinstance(actual, dd.DataFrame) assert_frame_equal(expected, actu...
<reponame>miguelangel-nubla/teslajsonpy # SPDX-License-Identifier: Apache-2.0 """ Python Package for controlling Tesla API. For more details about this api, please refer to the documentation at https://github.com/zabuldon/teslajsonpy """ import asyncio import logging import time from typing import Callable, Optional, ...
<gh_stars>1-10 """Dataset module for functions related to an xarray.Dataset.""" from typing import Any, Dict, Hashable, List, Optional, Union import pandas as pd import xarray as xr from xcdat import bounds # noqa: F401 from xcdat.logger import setup_custom_logger logger = setup_custom_logger(__name__) def open_da...
#!/usr/bin/env python import sys import os import math import pysam import argparse import multiprocessing as mp from statistics import mean def printBinInfo(info): if (info[3] + info[4] != 0): print(info[0] + '\t' + info[1] + '\t' + info[2] + '\t' + str(info[3]) + '\t' + str(info[4])) def outputUnmappedLowQualL...