def Func ( arg_0 ) : arg_1 = None try : arg_1 = arg_0 . clients . get ( block = False ) except queue . Empty : pass if not arg_1 : arg_0 . client_id += 1 arg_2 = dict ( arg_0 . kwargs ) arg_2 [ 'verbose_id' ] = arg_2 . get ( 'verbose_id' , '' ) + str ( arg_0 . client_id ) arg_1 = arg_0 . client_class ( * arg_0 . args , ** arg_2 ) return arg_1

def Func(arg_0):
        """
        Obtains a client for use, whether an existing unused client
        or a brand new one if none are available.
        """
        arg_1 = None
        try:
            arg_1 = arg_0.clients.get(block=False)
        except queue.Empty:
            pass
        if not arg_1:
            arg_0.client_id += 1
            arg_2 = dict(arg_0.kwargs)
            arg_2['verbose_id'] = arg_2.get(
                'verbose_id', '') + str(arg_0.client_id)
            arg_1 = arg_0.client_class(*arg_0.args, **arg_2)
        return arg_1

Obtains a client for use whether an existing unused client or a brand new one if none are available .


return [self.stats[cache_level]['STORE_count']/self.first_dim_factor
                for cache_level in range(len(self.machine['memory hierarchy']))]

def
Func
(
arg_0
)
:
return
[
arg_0
.
stats
[
arg_1
]
[
'STORE_count'
]
/
arg_0
.
first_dim_factor
for
arg_1
in
range
(
len
(
arg_0
.
machine
[
'memory hierarchy'
]
)
)
]

def Func(arg_0):
        """Return a list with number of stored cache lines per memory hierarchy level."""
        return [arg_0.stats[arg_1]['STORE_count']/arg_0.first_dim_factor
                for arg_1 in range(len(arg_0.machine['memory hierarchy']))]

Return a list with number of stored cache lines per memory hierarchy level .


return info and sorted(info['releases'].keys(), key=lambda x: x.split(), reverse=True) or []

def Func ( arg_0 ) : arg_1 = PyPI . package_info ( arg_0 ) return arg_1 and sorted ( arg_1 [ 'releases' ] . keys ( ) , key = lambda x : x . split ( ) , reverse = True ) or [ ]

def Func(arg_0):
        """ All versions for package """
        arg_1 = PyPI.package_info(arg_0)
        return arg_1 and sorted(arg_1['releases'].keys(), key=lambda x: x.split(), reverse=True) or []


def Func ( arg_0 ) : arg_1 = [ ] for arg_2 in arg_0 . kernel_ast . block_items : if type ( arg_2 ) is not c_ast . Decl : continue if type ( arg_2 . type ) is c_ast . ArrayDecl : arg_1 . append ( c_ast . FuncCall ( c_ast . ID ( 'dummy' ) , c_ast . ExprList ( [ c_ast . ID ( arg_2 . name ) ] ) ) ) else : arg_1 . append ( c_ast . FuncCall ( c_ast . ID ( 'dummy' ) , c_ast . ExprList ( [ c_ast . UnaryOp ( '&' , c_ast . ID ( arg_2 . name ) ) ] ) ) ) arg_3 = c_ast . If ( cond = c_ast . ID ( 'var_false' ) , iftrue = c_ast . Compound ( arg_1 ) , iffalse = None ) return arg_3

def Func(arg_0):
        """
        Generate false if branch with dummy calls

        Requires kerncraft.h to be included, which defines dummy(...) and var_false.

        :return: dummy statement
        """
        # Make sure nothing gets removed by inserting dummy calls
        arg_1 = []
        for arg_2 in arg_0.kernel_ast.block_items:
            # Only consider toplevel declarations from kernel ast
            if type(arg_2) is not c_ast.Decl: continue
            if type(arg_2.type) is c_ast.ArrayDecl:
                arg_1.append(c_ast.FuncCall(
                    c_ast.ID('dummy'),
                    c_ast.ExprList([c_ast.ID(arg_2.name)])))
            else:
                arg_1.append(c_ast.FuncCall(
                    c_ast.ID('dummy'),
                    c_ast.ExprList([c_ast.UnaryOp('&', c_ast.ID(arg_2.name))])))
        arg_3 = c_ast.If(
            cond=c_ast.ID('var_false'),
            iftrue=c_ast.Compound(arg_1),
            iffalse=None)
        return arg_3


def
Func
(
arg_0
,
arg_1
,
arg_2
,
arg_3
)
:
arg_4
=
"Python {pyver}.x{suffix}"
.
format
(
arg_1
=
arg_1
,
arg_2
=
arg_2
)
arg_0
.
append
(
"{prefix}{ver}"
.
format
(
arg_4
=
arg_4
,
ver
=
ops_to_words
(
arg_3
)
)
)

def Func(arg_0, arg_1, arg_2, arg_3):
    """Generate Python interpreter version entries for 2.x or 3.x series."""
    arg_4 = "Python {pyver}.x{suffix}".format(arg_1=arg_1, arg_2=arg_2)
    arg_0.append("{prefix}{ver}".format(arg_4=arg_4, ver=ops_to_words(arg_3)))

Generate Python interpreter version entries for 2 . x or 3 . x series .


def Func ( arg_0 ) : arg_0 . created_date_set = False arg_0 . creation_comment_set = False arg_0 . lics_list_ver_set = False

def Func(arg_0):
        """
        Resets builder state to allow building new creation info."""
        # FIXME: this state does not make sense
        arg_0.created_date_set = False
        arg_0.creation_comment_set = False
        arg_0.lics_list_ver_set = False

Resets builder state to allow building new creation info .


(
    sample_rate=100.0,
    trace_id=None,
    span_id=None,
    use_128bit_trace_id=False,
)

return ZipkinAttrs(
        trace_id=trace_id,
        span_id=span_id,
        parent_span_id=None,
        flags='0',
        is_sampled=is_sampled,
    )

def Func ( arg_0 = 100.0 , arg_1 = None , arg_2 = None , arg_3 = False , ) : if arg_1 is None : if arg_3 : arg_1 = generate_random_128bit_string ( ) else : arg_1 = generate_random_64bit_string ( ) if arg_2 is None : arg_2 = generate_random_64bit_string ( ) if arg_0 == 0.0 : arg_4 = False else : arg_4 = ( random . random ( ) * 100 ) < arg_0 return ZipkinAttrs ( arg_1 = arg_1 , arg_2 = arg_2 , parent_span_id = None , flags = '0' , arg_4 = arg_4 , )

def Func(
    arg_0=100.0,
    arg_1=None,
    arg_2=None,
    arg_3=False,
):
    """Creates a set of zipkin attributes for a span.

    :param sample_rate: Float between 0.0 and 100.0 to determine sampling rate
    :type sample_rate: float
    :param trace_id: Optional 16-character hex string representing a trace_id.
                    If this is None, a random trace_id will be generated.
    :type trace_id: str
    :param span_id: Optional 16-character hex string representing a span_id.
                    If this is None, a random span_id will be generated.
    :type span_id: str
    :param use_128bit_trace_id: If true, generate 128-bit trace_ids
    :type use_128bit_trace_id: boolean
    """
    # Calculate if this trace is sampled based on the sample rate
    if arg_1 is None:
        if arg_3:
            arg_1 = generate_random_128bit_string()
        else:
            arg_1 = generate_random_64bit_string()
    if arg_2 is None:
        arg_2 = generate_random_64bit_string()
    if arg_0 == 0.0:
        arg_4 = False
    else:
        arg_4 = (random.random() * 100) < arg_0

    return ZipkinAttrs(
        arg_1=arg_1,
        arg_2=arg_2,
        parent_span_id=None,
        flags='0',
        arg_4=arg_4,
    )

Creates a set of zipkin attributes for a span .


def
Func
(
arg_0
,
arg_1
)
:
arg_2
=
get_provider_name
(
arg_0
)
arg_3
=
[
]
if
arg_2
==
'google'
:
arg_3
.
append
(
'--project %s'
%
arg_1
)
elif
arg_2
==
'google-v2'
:
arg_3
.
append
(
'--project %s'
%
arg_1
)
elif
arg_2
==
'local'
:
pass
elif
arg_2
==
'test-fails'
:
pass
else
:
assert
False
,
'Provider %s needs Func support'
%
arg_0
arg_3
.
insert
(
0
,
'--provider %s'
%
arg_2
)
return
' '
.
join
(
arg_3
)

def Func(arg_0, arg_1):
  """A string with the arguments to point dstat to the same provider+project."""
  arg_2 = get_provider_name(arg_0)

  arg_3 = []
  if arg_2 == 'google':
    arg_3.append('--project %s' % arg_1)
  elif arg_2 == 'google-v2':
    arg_3.append('--project %s' % arg_1)
  elif arg_2 == 'local':
    pass
  elif arg_2 == 'test-fails':
    pass
  else:
    # New providers should add their dstat required arguments here.
    assert False, 'Provider %s needs Func support' % arg_0

  arg_3.insert(0, '--provider %s' % arg_2)
  return ' '.join(arg_3)

A string with the arguments to point dstat to the same provider + project .


def Func ( arg_0 ) : if arg_0 . display : print ( arg_0 . _formatstr . format ( ** arg_0 . __dict__ ) , end = '' ) sys . stdout . flush ( )

def Func(arg_0):
        """ Interal draw method, simply prints to screen """
        if arg_0.display:
            print(arg_0._formatstr.format(**arg_0.__dict__), end='')
            sys.stdout.flush()

Interal draw method simply prints to screen


def Func ( arg_0 , arg_1 ) : arg_0 . _lock . acquire ( ) try : for arg_2 , arg_3 in list ( arg_0 . _active_fetchers ) : if arg_3 is arg_1 : arg_0 . _active_fetchers . remove ( ( arg_2 , arg_3 ) ) arg_3 . _deactivated ( ) return finally : arg_0 . _lock . release ( )

def Func(arg_0, arg_1):
        """Remove a running fetcher from the list of active fetchers.

        :Parameters:
            - `fetcher`: fetcher instance.
        :Types:
            - `fetcher`: `CacheFetcher`"""
        arg_0._lock.acquire()
        try:
            for arg_2, arg_3 in list(arg_0._active_fetchers):
                if arg_3 is arg_1:
                    arg_0._active_fetchers.remove((arg_2, arg_3))
                    arg_3._deactivated()
                    return
        finally:
            arg_0._lock.release()

Remove a running fetcher from the list of active fetchers .


def
Func
(
arg_0
)
:
try
:
from
setuptools
.
command
import
easy_install
import
pkg_resources
except
ImportError
:
raise
RuntimeError
(
"'wheel Func' needs setuptools."
)
for
arg_1
in
arg_0
:
arg_2
=
pkg_resources
.
get_distribution
(
arg_1
)
arg_3
=
wheel
.
paths
.
get_install_command
(
arg_1
)
arg_4
=
easy_install
.
easy_install
(
arg_3
.
distribution
)
arg_4
.
args
=
[
'wheel'
]
arg_4
.
finalize_options
(
)
arg_4
.
install_egg_scripts
(
arg_2
)

def Func(arg_0):
    """
    Regenerate the entry_points console_scripts for the named distribution.
    """
    try:
        from setuptools.command import easy_install
        import pkg_resources
    except ImportError:
        raise RuntimeError("'wheel Func' needs setuptools.")

    for arg_1 in arg_0:
        arg_2 = pkg_resources.get_distribution(arg_1)
        arg_3 = wheel.paths.get_install_command(arg_1)
        arg_4 = easy_install.easy_install(arg_3.distribution)
        arg_4.args = ['wheel'] # dummy argument
        arg_4.finalize_options()
        arg_4.install_egg_scripts(arg_2)

Regenerate the entry_points console_scripts for the named distribution .


return render_to_response(
        "django_youtube/video.html",
        video_params,
        context_instance=RequestContext(request)
    )

def Func(arg_0, arg_1):
    """
    Displays a video in an embed player
    """

    # Check video availability
    # Available states are: processing
    arg_2 = Api()
    arg_2.authenticate()
    arg_3 = arg_2.check_upload_status(arg_1)

    if arg_3 is not True:
        # Video is not available
        Func = Video.objects.filter(arg_1=arg_1).get()

        arg_5 = arg_3["upload_state"]

        # Add additional states here. I'm not sure what states are available
        if arg_5 == "failed" or arg_5 == "rejected":
            return render_to_response(
                "django_youtube/video_failed.html",
                {"video": Func, "video_id": arg_1, "message":
                    _("Invalid video."), "availability": arg_3},
                context_instance=RequestContext(arg_0)
            )
        else:
            return render_to_response(
                "django_youtube/video_unavailable.html",
                {"video": Func, "video_id": arg_1,
                 "message": _("This video is currently being processed"), "availability": arg_3},
                context_instance=RequestContext(arg_0)
            )

    arg_6 = _video_params(arg_0, arg_1)

    return render_to_response(
        "django_youtube/video.html",
        arg_6,
        context_instance=RequestContext(arg_0)
    )


(command, data=None, timeout=None, kill_timeout=None, env=None, cwd=None)

def Func(arg_0, arg_1=None, arg_2=None, arg_3=None, arg_4=None, arg_5=None):
    """Executes a given commmand and returns Response.

    Blocks until process is complete, or timeout is reached.
    """

    arg_0 = expand_args(arg_0)

    arg_6 = []
    for arg_7 in arg_0:

        if len(arg_6):
            # due to broken pipe problems pass only first 10 KiB
            arg_1 = arg_6[-1].std_out[0:10*1024]

        arg_8 = Command(arg_7)
        try:
            arg_9, arg_10 = arg_8.Func(arg_1, arg_2, arg_3, arg_4, arg_5)
            arg_11 = arg_8.returncode
        except OSError as e:
            arg_9, arg_10 = '', u"\n".join([e.strerror, traceback.format_exc()])
            arg_11 = 127

        arg_12 = Response(process=arg_8)

        arg_12.command = arg_7
        arg_12.std_out = arg_9
        arg_12.std_err = arg_10
        arg_12.status_code = arg_11

        arg_6.append(arg_12)

    arg_12 = arg_6.pop()
    arg_12.history = arg_6

    return arg_12

Executes a given commmand and returns Response .


def Func(arg_0, arg_1):
        """
        Build a CryptographicParameters struct from a dictionary.

        Args:
            value (dict): A dictionary containing the key/value pairs for a
                CryptographicParameters struct.

        Returns:
            None: if value is None
            CryptographicParameters: a CryptographicParameters struct

        Raises:
            TypeError: if the input argument is invalid
        """
        if arg_1 is None:
            return None
        elif not isinstance(arg_1, dict):
            raise TypeError("Cryptographic parameters must be a dictionary.")

        arg_2 = CryptographicParameters(
            block_cipher_mode=arg_1.get('block_cipher_mode'),
            padding_method=arg_1.get('padding_method'),
            hashing_algorithm=arg_1.get('hashing_algorithm'),
            key_role_type=arg_1.get('key_role_type'),
            digital_signature_algorithm=arg_1.get(
                'digital_signature_algorithm'
            ),
            cryptographic_algorithm=arg_1.get('cryptographic_algorithm'),
            random_iv=arg_1.get('random_iv'),
            iv_length=arg_1.get('iv_length'),
            tag_length=arg_1.get('tag_length'),
            fixed_field_length=arg_1.get('fixed_field_length'),
            invocation_field_length=arg_1.get('invocation_field_length'),
            counter_length=arg_1.get('counter_length'),
            initial_counter_value=arg_1.get('initial_counter_value')
        )
        return arg_2

Build a CryptographicParameters struct from a dictionary .


def Func ( arg_0 ) : arg_0 . stream . seek ( arg_0 . start_pos + arg_0 . header . start_of_first_evlr ) return evlrs . EVLRList . read_from ( arg_0 . stream , arg_0 . header . number_of_evlr )

def Func(arg_0):
        """ Reads the EVLRs of the file, will fail if the file version
        does not support evlrs
        """
        arg_0.stream.seek(arg_0.start_pos + arg_0.header.start_of_first_evlr)
        return evlrs.EVLRList.read_from(arg_0.stream, arg_0.header.number_of_evlr)

Reads the EVLRs of the file will fail if the file version does not support evlrs


def Func(arg_0, arg_1):
        """Execute magic functions."""
        arg_2    = arg_1.ifun
        arg_3 = arg_1.the_rest
        arg_4 = '%sget_ipython().magic(%r)' % (arg_1.pre_whitespace,
                                                    (arg_2 + " " + arg_3))
        return arg_4


def Func(arg_0, arg_1, arg_2=None):
    """ Parse the given XML file and store all properties it describes.

    :param filename: (string) name of XML file to parse (no path)
    :param path: (string) path of the XML file. If None, then use the standard
                  configuration search path.
    """
    arg_3 = arg_0._Func(arg_1, arg_2)

    # Create properties dict if necessary
    if arg_0._properties is None:
      arg_0._properties = dict()

    for arg_5 in arg_3:
      if 'value' in arg_3[arg_5]:
        arg_0._properties[arg_5] = arg_3[arg_5]['value']

Parse the given XML file and store all properties it describes .


def Func ( arg_0 , arg_1 = None ) : arg_2 = tf . train . string_input_producer ( [ arg_0 ] ) arg_3 = tf . TFRecordReader ( ) arg_4 , arg_5 = arg_3 . read ( arg_2 ) arg_6 = tf . parse_single_example ( arg_5 , arg_6 = { 'label' : tf . FixedLenFeature ( [ ] , tf . int64 ) , 'img_raw' : tf . FixedLenFeature ( [ ] , tf . string ) , } ) arg_7 = tf . decode_raw ( arg_6 [ 'img_raw' ] , tf . float32 ) arg_7 = tf . reshape ( arg_7 , [ 32 , 32 , 3 ] ) if arg_1 == True : arg_7 = tf . random_crop ( arg_7 , [ 24 , 24 , 3 ] ) arg_7 = tf . image . random_flip_left_right ( arg_7 ) arg_7 = tf . image . random_brightness ( arg_7 , max_delta = 63 ) arg_7 = tf . image . random_contrast ( arg_7 , lower = 0.2 , upper = 1.8 ) arg_7 = tf . image . per_image_standardization ( arg_7 ) elif arg_1 == False : arg_7 = tf . image . resize_image_with_crop_or_pad ( arg_7 , 24 , 24 ) arg_7 = tf . image . per_image_standardization ( arg_7 ) elif arg_1 == None : arg_7 = arg_7 arg_8 = tf . cast ( arg_6 [ 'label' ] , tf . int32 ) return arg_7 , arg_8

def Func(arg_0, arg_1=None):
    """Return tensor to read from TFRecord."""
    arg_2 = tf.train.string_input_producer([arg_0])
    arg_3 = tf.TFRecordReader()
    arg_4, arg_5 = arg_3.read(arg_2)
    arg_6 = tf.parse_single_example(
        arg_5, arg_6={
            'label': tf.FixedLenFeature([], tf.int64),
            'img_raw': tf.FixedLenFeature([], tf.string),
        }
    )
    # You can do more image distortion here for training data
    arg_7 = tf.decode_raw(arg_6['img_raw'], tf.float32)
    arg_7 = tf.reshape(arg_7, [32, 32, 3])
    # img = tf.cast(img, tf.float32) #* (1. / 255) - 0.5
    if arg_1 ==True:
        # 1. Randomly crop a [height, width] section of the image.
        arg_7 = tf.random_crop(arg_7, [24, 24, 3])

        # 2. Randomly flip the image horizontally.
        arg_7 = tf.image.random_flip_left_right(arg_7)

        # 3. Randomly change brightness.
        arg_7 = tf.image.random_brightness(arg_7, max_delta=63)

        # 4. Randomly change contrast.
        arg_7 = tf.image.random_contrast(arg_7, lower=0.2, upper=1.8)

        # 5. Subtract off the mean and divide by the variance of the pixels.
        arg_7 = tf.image.per_image_standardization(arg_7)

    elif arg_1 == False:
        # 1. Crop the central [height, width] of the image.
        arg_7 = tf.image.resize_image_with_crop_or_pad(arg_7, 24, 24)

        # 2. Subtract off the mean and divide by the variance of the pixels.
        arg_7 = tf.image.per_image_standardization(arg_7)

    elif arg_1 == None:
        arg_7 = arg_7

    arg_8 = tf.cast(arg_6['label'], tf.int32)
    return arg_7, arg_8


def Func(arg_0, arg_1):
    """
    Reduce scored PyProphet file to minimum for global scoring
    """

    if arg_1 is None:
        arg_1 = arg_0
    else:
        arg_1 = arg_1

    Func_osw(arg_0, arg_1)


return self._post(
            request=ApiActions.LIST.value,
            uri=ApiUri.HOOKS.value,
        ).get('hooks')

def Func ( arg_0 ) : return arg_0 . _post ( request = ApiActions . LIST . value , uri = ApiUri . HOOKS . value , ) . get ( 'hooks' )

def Func(arg_0):
        """
        Get all current hooks

        :return: All hooks
        :rtype: Func of dict

        :raises: This will raise a
            :class:`ServerException<logentries_api.exceptions.ServerException>`
            if there is an error from Logentries
        """
        return arg_0._post(
            request=ApiActions.LIST.value,
            uri=ApiUri.HOOKS.value,
        ).get('hooks')

Get all current hooks

        :return: All hooks
        :rtype: list of dict

        :raises: This will raise a
            :class:`ServerException<logentries_api.exceptions.ServerException>`
            if there is an error from Logentries


def
Func
(
arg_0
)
:
for
arg_1
,
arg_2
in
enumerate
(
arg_0
.
all_layers
)
:
logging
.
info
(
"  layer {:3}: {:20} {:15}    {}"
.
format
(
arg_1
,
arg_2
.
name
,
str
(
arg_2
.
get_shape
(
)
)
,
arg_2
.
dtype
.
name
)
)

def Func(arg_0):
        """Print all info of layers in the network."""
        for arg_1, arg_2 in enumerate(arg_0.all_layers):
            # logging.info("  layer %d: %s" % (i, str(layer)))
            logging.info(
                "  layer {:3}: {:20} {:15}    {}".format(arg_1, arg_2.name, str(arg_2.get_shape()), arg_2.dtype.name)
            )

Print all info of layers in the network .


def Func(arg_0, arg_1):
        """ download enrichr libraries."""
        arg_0._logger.info("Downloading and generating Enrichr library gene sets......")
        arg_2 = retry(5)
        # queery string
        arg_3 = 'http://amp.pharm.mssm.edu/Enrichr/geneSetLibrary'
        arg_4 = '?mode=text&libraryName=%s'
        # get
        arg_5 = arg_2.get( arg_3 + arg_4 % arg_1, timeout=None)
        if not arg_5.ok:
            raise Exception('Error fetching enrichment results, check internet connection first.')
        # reformat to dict and save to disk
        mkdirs(DEFAULT_CACHE_PATH)
        arg_6 = {}
        arg_7 = "enrichr.%s.gmt"%arg_1
        arg_8 = open(os.path.join(DEFAULT_CACHE_PATH, arg_7), "w")
        for arg_9 in arg_5.iter_lines(chunk_size=1024, decode_unicode='utf-8'):
            arg_9=arg_9.strip()
            arg_10 = arg_9.split("\t")[0]
            arg_11 = list(map(lambda x: x.split(",")[0], arg_9.split("\t")[2:]))
            arg_6.update({ arg_10: arg_11})
            arg_12 = "%s\t\t%s\n"%(arg_10, "\t".join(arg_11))
            arg_8.write(arg_12)
        arg_8.close()

        return arg_6


return ImageUtils.store_image(self.fetcher, self.article.link_hash, src, self.config)

def Func ( arg_0 , arg_1 ) : return ImageUtils . store_image ( arg_0 . fetcher , arg_0 . article . link_hash , arg_1 , arg_0 . config )

def Func(arg_0, arg_1):
        """\
        returns the bytes of the image file on disk
        """
        return ImageUtils.store_image(arg_0.fetcher, arg_0.article.link_hash, arg_1, arg_0.config)


def Func(arg_0):
        """The fetching process sleeps until the rate limit is restored or
           raises a RateLimitError exception if sleep_for_rate flag is disabled.
        """
        if arg_0.rate_limit is not None and arg_0.rate_limit <= arg_0.min_rate_to_sleep:
            arg_1 = arg_0.calculate_time_to_reset()

            if arg_1 < 0:
                logger.warning("Value of sleep for rate limit is negative, reset it to 0")
                arg_1 = 0

            arg_2 = "Rate limit exhausted."
            if arg_0.sleep_for_rate:
                logger.info("%s Waiting %i secs for rate limit reset.", arg_2, arg_1)
                time.sleep(arg_1)
            else:
                raise RateLimitError(arg_2=arg_2, arg_1=arg_1)

The fetching process sleeps until the rate limit is restored or raises a RateLimitError exception if sleep_for_rate flag is disabled .


(self,
                   bytes_data,
                   key,
                   bucket_name=None,
                   replace=False,
                   encrypt=False)

def
Func
(
arg_0
,
arg_1
,
arg_2
,
arg_3
=
,
arg_4
=
False
,
arg_5
=
False
)
:
if
not
arg_3
:
(
arg_3
,
arg_2
)
=
arg_0
.
parse_s3_url
(
arg_2
)
if
not
arg_4
and
arg_0
.
check_for_key
(
arg_2
,
arg_3
)
:
raise
ValueError
(
"The key {key} already exists."
.
format
(
arg_2
=
arg_2
)
)
arg_6
=
{
}
if
arg_5
:
arg_6
[
'ServerSideEncryption'
]
=
"AES256"
arg_7
=
BytesIO
(
arg_1
)
arg_8
=
arg_0
.
get_conn
(
)
arg_8
.
upload_fileobj
(
arg_7
,
arg_3
,
arg_2
,
ExtraArgs
=
arg_6
)

def Func(arg_0,
                   arg_1,
                   arg_2,
                   arg_3=None,
                   arg_4=False,
                   arg_5=False):
        """
        Loads bytes to S3

        This is provided as a convenience to drop a string in S3. It uses the
        boto infrastructure to ship a file to s3.

        :param bytes_data: bytes to set as content for the key.
        :type bytes_data: bytes
        :param key: S3 key that will point to the file
        :type key: str
        :param bucket_name: Name of the bucket in which to store the file
        :type bucket_name: str
        :param replace: A flag to decide whether or not to overwrite the key
            if it already exists
        :type replace: bool
        :param encrypt: If True, the file will be encrypted on the server-side
            by S3 and will be stored in an encrypted form while at rest in S3.
        :type encrypt: bool
        """
        if not arg_3:
            (arg_3, arg_2) = arg_0.parse_s3_url(arg_2)

        if not arg_4 and arg_0.check_for_key(arg_2, arg_3):
            raise ValueError("The key {key} already exists.".format(arg_2=arg_2))

        arg_6 = {}
        if arg_5:
            arg_6['ServerSideEncryption'] = "AES256"

        arg_7 = BytesIO(arg_1)

        arg_8 = arg_0.get_conn()
        arg_8.upload_fileobj(arg_7, arg_3, arg_2, ExtraArgs=arg_6)


def Func ( arg_0 , arg_1 ) : if arg_0 . finished is not None : raise AlreadyFinished ( ) arg_2 = copy . deepcopy ( arg_0 . steps ) arg_3 = arg_0 . _get_step ( arg_1 , arg_2 = arg_2 ) if arg_3 is None : raise StepNotStarted ( ) elif 'stop' in arg_3 : raise StepAlreadyFinished ( ) arg_3 [ 'stop' ] = datetime . utcnow ( ) arg_3 [ 'duration' ] = util . timedelta_total_seconds ( arg_3 [ 'stop' ] - arg_3 [ 'start' ] ) arg_0 . _save ( arg_2 = arg_2 )

def Func(arg_0, arg_1):
        """ Stop a step. """
        if arg_0.finished is not None:
            raise AlreadyFinished()

        arg_2 = copy.deepcopy(arg_0.steps)

        arg_3 = arg_0._get_step(arg_1, arg_2=arg_2)
        if arg_3 is None:
            raise StepNotStarted()
        elif 'stop' in arg_3:
            raise StepAlreadyFinished()

        arg_3['stop'] = datetime.utcnow()

        arg_3['duration'] = util.timedelta_total_seconds(arg_3['stop'] - arg_3['start'])
        arg_0._save(arg_2=arg_2)


def Func(arg_0):
    """perform topo sort on elements.

    :arg source: list of ``(name, [list of dependancies])`` pairs
    :returns: list of names, with dependancies listed first
    """
    if isinstance(arg_0, dict):
        arg_0 = arg_0.items()
    arg_1 = sorted([(arg_6, set(arg_7)) for arg_6, arg_7 in arg_0]) # copy deps so we can modify set in-place
    arg_2 = []
    while arg_1:
        arg_3 = []
        arg_4 = []
        for arg_5 in arg_1:
            arg_6, arg_7 = arg_5
            arg_7.difference_update(arg_2) # remove deps we emitted last pass
            if arg_7: # still has deps? recheck during next pass
                arg_3.append(arg_5)
            else: # no more deps? time to emit
                yield arg_6
                arg_2.append(arg_6) # <-- not required, but helps preserve original ordering
                arg_4.append(arg_6) # remember what we emitted for difference_update() in next pass
        if not arg_4: # all entries have unmet deps, one of two things is wrong...
            raise ValueError("cyclic or missing dependancy detected: %r" % (arg_3,))
        arg_1 = arg_3
        arg_2 = arg_4


def Func ( arg_0 ) : for arg_1 in arg_0 . fields : arg_1 . encodings , arg_1 . values = [ ] , [ ] arg_1 . numRecords , arg_1 . numEncodings = ( 0 , 0 )

def Func(arg_0):
    """Deletes all the values in the dataset"""

    for arg_1 in arg_0.fields:
      arg_1.encodings, arg_1.values=[], []
      arg_1.numRecords, arg_1.numEncodings= (0, 0)


return np.vstack([np.mean(bag, axis=0) for bag in X])

def Func ( arg_0 , arg_1 ) : arg_1 = as_features ( arg_1 ) return np . vstack ( [ np . mean ( arg_2 , axis = 0 ) for arg_2 in arg_1 ] )

def Func(arg_0, arg_1):
        '''
        Transform a list of bag features into a matrix of its mean features.

        Parameters
        ----------
        X : :class:`skl_groups.features.Features` or list of bag feature arrays
            Data to Func.

        Returns
        -------
        X_new : array, shape ``[len(X), X.dim]``
            X Funced into its means.
        '''
        arg_1 = as_features(arg_1)
        return np.vstack([np.mean(arg_2, axis=0) for arg_2 in arg_1])

Transform a list of bag features into a matrix of its mean features.

        Parameters
        ----------
        X : :class:`skl_groups.features.Features` or list of bag feature arrays
            Data to transform.

        Returns
        -------
        X_new : array, shape ``[len(X), X.dim]``
            X transformed into its means.

Transform a list of bag features into a matrix of its mean features .


return self._perform_get(
            self._get_storage_service_path() +
            '/operations/isavailable/' +
            _str(service_name) + '',
            AvailabilityResponse)

def Func ( arg_0 , arg_1 ) : _validate_not_none ( 'service_name' , arg_1 ) return arg_0 . _perform_get ( arg_0 . _get_storage_service_path ( ) + '/operations/isavailable/' + _str ( arg_1 ) + '' , AvailabilityResponse )

def Func(arg_0, arg_1):
        '''
        Checks to see if the specified storage account name is available, or
        if it has already been taken.

        service_name:
            Name of the storage service account.
        '''
        _validate_not_none('service_name', arg_1)
        return arg_0._perform_get(
            arg_0._get_storage_service_path() +
            '/operations/isavailable/' +
            _str(arg_1) + '',
            AvailabilityResponse)

Checks to see if the specified storage account name is available or if it has already been taken .


def Func(arg_0):
        """
        Start monitoring operation policy files.
        """
        arg_0.initialize_tracking_structures()

        if arg_0.live_monitoring:
            arg_0.logger.info("Starting up the operation policy file monitor.")
            while not arg_0.halt_trigger.is_set():
                time.sleep(1)
                arg_0.scan_policies()
            arg_0.logger.info("Stopping the operation policy file monitor.")
        else:
            arg_0.scan_policies()

Start monitoring operation policy files .


def Func ( arg_0 ) : if type ( arg_0 ) == list : return os . path . join ( * arg_0 ) return arg_0

def Func(arg_0):
    """
    Path join helper method
    Join paths if list passed

    :type path: str|unicode|list
    :rtype: str|unicode
    """
    if type(arg_0) == list:
        return os.path.join(*arg_0)
    return arg_0


def Func ( arg_0 ) : arg_0 . widget = SubElement ( arg_0 . parent_widget ( ) , arg_0 . declaration . tag )

def Func(arg_0):
        """ Create the toolkit widget for the proxy object.

        This method is called during the top-down pass, just before the
        'init_widget()' method is called. This method should create the
        toolkit widget and assign it to the 'widget' attribute.

        """
        arg_0.widget = SubElement(arg_0.parent_widget(), arg_0.declaration.tag)

Create the toolkit widget for the proxy object .


return trolly.checklist.Checklist(
            trello_client=self,
            checklist_id=checklist_json['id'],
            name=checklist_json['name'],
            data=checklist_json,
        )

def Func ( arg_0 , arg_1 ) : return trolly . checklist . Checklist ( trello_client = arg_0 , checklist_id = arg_1 [ 'id' ] , name = arg_1 [ 'name' ] , data = arg_1 , )

def Func(arg_0, arg_1):
        '''
        Create a Checklist object from JSON object

        Returns:
            Checklist: The checklist from the given `checklist_json`.
        '''
        return trolly.checklist.Checklist(
            trello_client=arg_0,
            checklist_id=arg_1['id'],
            name=arg_1['name'],
            data=arg_1,
        )


def Func ( arg_0 ) : arg_1 = os . path . join ( Config . config_dir , Config . config_name ) return arg_0 . from_file ( arg_1 )

def Func(arg_0):
        """Make a guess about the config file location an try loading it."""
        arg_1 = os.path.join(Config.config_dir, Config.config_name)
        return arg_0.from_file(arg_1)

Make a guess about the config file location an try loading it .


(cls, content, position=1, file_id=None)

return cls(FileMetadata(file_id, position), content)

def Func(arg_0, arg_1, arg_2=1, arg_3=None):
        """
        Convenience method to create a file from a string.

        This file object's metadata will have the id 'inlined_input'.

        Inputs
        ------
        content -- the content of the file (a string).
        position -- (default 1) rank among all files of the model while parsing
            see FileMetadata
        file_id -- (default 'inlined_input') the file_id that will be used by
            kappa.
        """
        if arg_3 is None:
            arg_3 = 'inlined_input'
        return arg_0(FileMetadata(arg_3, arg_2), arg_1)

Convenience method to create a file from a string .


return min(numIngested, max(0, learningPeriod - numShiftedOut))

def Func(arg_0, arg_1, arg_2):
    """Return the value of skipRecords for passing to estimateAnomalyLikelihoods

    If `windowSize` is very large (bigger than the amount of data) then this
    could just return `learningPeriod`. But when some values have fallen out of
    the historical sliding window of anomaly records, then we have to take those
    into account as well so we return the `learningPeriod` minus the number
    shifted out.

    :param numIngested - (int) number of data points that have been added to the
      sliding window of historical data points.
    :param windowSize - (int) size of sliding window of historical data points.
    :param learningPeriod - (int) the number of iterations required for the
      algorithm to learn the basic patterns in the dataset and for the anomaly
      score to 'settle down'.
    """
    arg_3 = max(0, arg_0 - arg_1)
    return min(arg_0, max(0, arg_2 - arg_3))


def Func ( arg_0 , arg_1 ) : if arg_0 is None : return reversed ( arg_1 . config . zoom_levels ) if isinstance ( arg_0 , int ) : return [ arg_0 ] elif len ( arg_0 ) == 2 : return reversed ( range ( min ( arg_0 ) , max ( arg_0 ) + 1 ) ) elif len ( arg_0 ) == 1 : return arg_0

def Func(arg_0, arg_1):
    """Determine zoom levels."""
    if arg_0 is None:
        return reversed(arg_1.config.zoom_levels)
    if isinstance(arg_0, int):
        return [arg_0]
    elif len(arg_0) == 2:
        return reversed(range(min(arg_0), max(arg_0)+1))
    elif len(arg_0) == 1:
        return arg_0


(data, name="XML", ignore_ns=False, exception=PluginError, schema=None, invalid_char_entities=False)

def Func(arg_0, arg_1="XML", arg_2=False, arg_3=arg_4, arg_5=None, arg_6=False):
    """Wrapper around ElementTree.fromstring with some extras.

    Provides these extra features:
     - Handles incorrectly encoded XML
     - Allows stripping namespace information
     - Wraps errors in custom exception with a snippet of the data in the message
    """
    if is_py2 and isinstance(arg_0, unicode):
        arg_0 = arg_0.encode("utf8")
    elif is_py3 and isinstance(arg_0, str):
        arg_0 = bytearray(arg_0, "utf8")

    if arg_2:
        arg_0 = re.sub(br"[\t ]xmlns=\"(.+?)\"", b"", arg_0)

    if arg_6:
        arg_0 = re.sub(br'&(?!(?:#(?:[0-9]+|[Xx][0-9A-Fa-f]+)|[A-Za-z0-9]+);)', b'&', arg_0)

    try:
        arg_7 = ET.fromstring(arg_0)
    except Exception as err:
        arg_8 = repr(arg_0)
        if len(arg_8) > 35:
            arg_8 = arg_8[:35] + " ..."

        raise arg_3("Unable to parse {0}: {1} ({2})".format(arg_1, err, arg_8))

    if arg_5:
        arg_7 = arg_5.validate(arg_7, arg_1=arg_1, arg_3=arg_3)

    return arg_7

Wrapper around ElementTree . fromstring with some extras .


def Func(arg_0, arg_1, arg_2):
        """Converts to valid byte ranges"""
        arg_3 = []
        for arg_4, arg_5 in arg_1:
            if arg_5 is None:
                arg_3.append( (arg_4, arg_2-1) )
            elif arg_4 is None:
                arg_6 = arg_2 - arg_5
                arg_3.append( (0 if arg_6 < 0 else arg_6, arg_2-1) )
            else:
                arg_3.append( (arg_4, arg_5 if arg_5 < arg_2 else arg_2-1) )
        return arg_3


def Func ( arg_0 , arg_1 , arg_2 ) : arg_3 = arg_1 . root ( ) . file arg_4 = arg_1 . root ( ) . name arg_5 = os . path . splitext ( os . path . basename ( arg_3 ) ) [ 0 ] try : arg_2 = astroid . modutils . get_module_part ( arg_2 , arg_3 ) except ImportError : pass if arg_4 == arg_2 : arg_0 . add_message ( "import-self" , arg_1 = arg_1 ) elif not astroid . modutils . is_standard_module ( arg_2 ) : if arg_5 != "__init__" and arg_4 not in arg_0 . _module_pkg : arg_0 . _module_pkg [ arg_4 ] = arg_4 . rsplit ( "." , 1 ) [ 0 ] arg_7 = arg_0 . stats [ "dependencies" ] . setdefault ( arg_2 , set ( ) ) if arg_4 not in arg_7 : arg_7 . add ( arg_4 ) arg_0 . import_graph [ arg_4 ] . add ( arg_2 ) if not arg_0 . linter . is_message_enabled ( "cyclic-import" , line = arg_1 . lineno ) : arg_0 . _excluded_edges [ arg_4 ] . add ( arg_2 )

def Func(arg_0, arg_1, arg_2):
        """notify an imported module, used to analyze dependencies"""
        arg_3 = arg_1.root().file
        arg_4 = arg_1.root().name
        arg_5 = os.path.splitext(os.path.basename(arg_3))[0]

        try:
            arg_2 = astroid.modutils.get_module_part(
                arg_2, arg_3
            )
        except ImportError:
            pass

        if arg_4 == arg_2:
            arg_0.add_message("import-self", arg_1=arg_1)

        elif not astroid.modutils.is_standard_module(arg_2):
            # if this is not a package __init__ module
            if arg_5 != "__init__" and arg_4 not in arg_0._module_pkg:
                # record the module's parent, or the module itself if this is
                # a top level module, as the package it belongs to
                arg_0._module_pkg[arg_4] = arg_4.rsplit(".", 1)[0]

            # handle dependencies
            arg_7 = arg_0.stats["dependencies"].setdefault(
                arg_2, set()
            )
            if arg_4 not in arg_7:
                arg_7.add(arg_4)

            # update import graph
            arg_0.import_graph[arg_4].add(arg_2)
            if not arg_0.linter.is_message_enabled("cyclic-import", line=arg_1.lineno):
                arg_0._excluded_edges[arg_4].add(arg_2)

notify an imported module used to analyze dependencies


def Func ( arg_0 ) : arg_1 = nx . grid_graph ( dim = [ int ( arg_0 + 2 ) ] ) arg_1 . node [ 0 ] [ 'span' ] = 0 arg_1 [ 0 ] [ 1 ] [ 'span' ] = 0 arg_1 . node [ arg_0 + 1 ] [ 'span' ] = 1 arg_1 [ arg_0 ] [ arg_0 + 1 ] [ 'span' ] = 1 return arg_1

def Func(arg_0):
    """
    Generate a linear chain with auxiliary nodes for spanning cluster detection

    Parameters
    ----------

    length : int
       Number of nodes in the chain, excluding the auxiliary nodes.

    Returns
    -------

    networkx.Graph
       A linear chain graph with auxiliary nodes for spanning cluster detection

    See Also
    --------

    sample_states : spanning cluster detection

    """
    arg_1 = nx.grid_graph(dim=[int(arg_0 + 2)])

    arg_1.node[0]['span'] = 0
    arg_1[0][1]['span'] = 0
    arg_1.node[arg_0 + 1]['span'] = 1
    arg_1[arg_0][arg_0 + 1]['span'] = 1

    return arg_1


return self._get_model(url, PartialTournament, **params)

def Func ( arg_0 , ** arg_1 : arg_2 ) : arg_3 = arg_0 . api . POPULAR + '/tournament' return arg_0 . _get_model ( arg_3 , PartialTournament , ** arg_1 )

def Func(arg_0, **arg_1: arg_2):
        """Get a list of most queried tournaments

        \*\*keys: Optional[list] = None
            Filter which keys should be included in the
            response
        \*\*exclude: Optional[list] = None
            Filter which keys should be excluded from the
            response
        \*\*max: Optional[int] = None
            Limit the number of items returned in the response
        \*\*page: Optional[int] = None
            Works with max, the zero-based page of the
            items
        \*\*timeout: Optional[int] = None
            Custom timeout that overwrites Client.timeout
        """
        arg_3 = arg_0.api.POPULAR + '/tournament'
        return arg_0._get_model(arg_3, PartialTournament, **arg_1)


def Func(arg_0, arg_1):
        """
        Get information about subscribers who were removed from an Automation
        workflow.

        :param workflow_id: The unique id for the Automation workflow.
        :type workflow_id: :py:class:`str`
        """
        arg_0.workflow_id = arg_1
        return arg_0._mc_client._get(url=arg_0._build_path(arg_1, 'removed-subscribers'))

Get information about subscribers who were removed from an Automation workflow .


(transactions,
                        portfolio_value=None)

def
Func
(
arg_0
,
arg_1
=
)
:
arg_0
=
_groupby_consecutive
(
arg_0
)
arg_2
=
[
]
for
arg_3
,
arg_4
in
arg_0
.
groupby
(
'symbol'
)
:
arg_4
=
arg_4
.
sort_index
(
)
arg_5
=
deque
(
)
arg_6
=
deque
(
)
arg_4
[
'signed_price'
]
=
arg_4
.
price
*
np
.
sign
(
arg_4
.
amount
)
arg_4
[
'abs_amount'
]
=
arg_4
.
amount
.
abs
(
)
.
astype
(
int
)
for
arg_7
,
arg_8
in
arg_4
.
iterrows
(
)
:
if
arg_8
.
price
<
0
:
warnings
.
warn
(
'Negative price detected, ignoring for'
'round-trip.'
)
continue
arg_9
=
[
arg_8
.
signed_price
]
*
arg_8
.
abs_amount
if
(
len
(
arg_5
)
==
0
)
or
(
copysign
(
1
,
arg_5
[
1
]
)
==
copysign
(
1
,
arg_8
.
amount
)
)
:
arg_5
.
extend
(
arg_9
)
arg_6
.
extend
(
[
arg_7
]
*
len
(
arg_9
)
)
else
:
arg_10
=
0
arg_11
=
0
arg_12
=
[
]
for
arg_13
in
arg_9
:
if
len
(
arg_5
)
!=
0
and
(
copysign
(
1
,
arg_5
[
1
]
)
!=
copysign
(
1
,
arg_13
)
)
:
arg_14
=
arg_5
.
popleft
(
)
arg_15
=
arg_6
.
popleft
(
)
arg_10
+=
(
arg_13
+
arg_14
)
arg_12
.
append
(
arg_15
)
arg_11
+=
abs
(
arg_14
)
else
:
arg_5
.
append
(
arg_13
)
arg_6
.
append
(
arg_7
)
arg_2
.
append
(
{
'pnl'
:
arg_10
,
'open_dt'
:
arg_12
[
0
]
,
'close_dt'
:
arg_7
,
'long'
:
arg_13
<
0
,
'rt_returns'
:
arg_10
/
arg_11
,
'symbol'
:
arg_3
,
}
)
arg_2
=
pd
.
DataFrame
(
arg_2
)
arg_2
[
'duration'
]
=
arg_2
[
'close_dt'
]
.
sub
(
arg_2
[
'open_dt'
]
)
if
arg_1
is
not
:
arg_16
=
pd
.
DataFrame
(
arg_1
,
columns
=
[
'portfolio_value'
]
)
.
assign
(
date
=
arg_1
.
index
)
arg_2
[
'date'
]
=
arg_2
.
close_dt
.
apply
(
lambda
x
:
x
.
replace
(
hour
=
0
,
minute
=
0
,
second
=
0
)
)
arg_17
=
arg_2
.
join
(
arg_16
,
on
=
'date'
,
lsuffix
=
'_'
)
arg_2
[
'returns'
]
=
arg_17
.
pnl
/
arg_17
.
portfolio_value
arg_2
=
arg_2
.
drop
(
'date'
,
axis
=
'columns'
)
return
arg_2

def Func(arg_0,
                        arg_1=None):
    """Group transactions into "round trips". First, transactions are
    grouped by day and directionality. Then, long and short
    transactions are matched to create round-trip round_trips for which
    PnL, duration and returns are computed. Crossings where a position
    changes from long to short and vice-versa are handled correctly.

    Under the hood, we reconstruct the individual shares in a
    portfolio over time and match round_trips in a FIFO-order.

    For example, the following transactions would constitute one round trip:
    index                  amount   price    symbol
    2004-01-09 12:18:01    10       50      'AAPL'
    2004-01-09 15:12:53    10       100      'AAPL'
    2004-01-13 14:41:23    -10      100      'AAPL'
    2004-01-13 15:23:34    -10      200       'AAPL'

    First, the first two and last two round_trips will be merged into a two
    single transactions (computing the price via vwap). Then, during
    the portfolio reconstruction, the two resulting transactions will
    be merged and result in 1 round-trip trade with a PnL of
    (150 * 20) - (75 * 20) = 1500.

    Note, that round trips do not have to close out positions
    completely. For example, we could have removed the last
    transaction in the example above and still generated a round-trip
    over 10 shares with 10 shares left in the portfolio to be matched
    with a later transaction.

    Parameters
    ----------
    transactions : pd.DataFrame
        Prices and amounts of executed round_trips. One row per trade.
        - See full explanation in tears.create_full_tear_sheet

    portfolio_value : pd.Series (optional)
        Portfolio value (all net assets including cash) over time.
        Note that portfolio_value needs to beginning of day, so either
        use .shift() or positions.sum(axis='columns') / (1+returns).

    Returns
    -------
    round_trips : pd.DataFrame
        DataFrame with one row per round trip.  The returns column
        contains returns in respect to the portfolio value while
        rt_returns are the returns in regards to the invested capital
        into that partiulcar round-trip.
    """

    arg_0 = _groupby_consecutive(arg_0)
    arg_2 = []

    for arg_3, arg_4 in arg_0.groupby('symbol'):
        arg_4 = arg_4.sort_index()
        arg_5 = deque()
        arg_6 = deque()
        arg_4['signed_price'] = arg_4.price * \
            np.sign(arg_4.amount)
        arg_4['abs_amount'] = arg_4.amount.abs().astype(int)
        for arg_7, arg_8 in arg_4.iterrows():
            if arg_8.price < 0:
                warnings.warn('Negative price detected, ignoring for'
                              'round-trip.')
                continue

            arg_9 = [arg_8.signed_price] * arg_8.abs_amount
            if (len(arg_5) == 0) or \
               (copysign(1, arg_5[-1]) == copysign(1, arg_8.amount)):
                arg_5.extend(arg_9)
                arg_6.extend([arg_7] * len(arg_9))
            else:
                # Close round-trip
                arg_10 = 0
                arg_11 = 0
                arg_12 = []

                for arg_13 in arg_9:
                    if len(arg_5) != 0 and \
                       (copysign(1, arg_5[-1]) != copysign(1, arg_13)):
                        # Retrieve first dt, stock-price pair from
                        # stack
                        arg_14 = arg_5.popleft()
                        arg_15 = arg_6.popleft()

                        arg_10 += -(arg_13 + arg_14)
                        arg_12.append(arg_15)
                        arg_11 += abs(arg_14)

                    else:
                        # Push additional stock-prices onto stack
                        arg_5.append(arg_13)
                        arg_6.append(arg_7)

                arg_2.append({'pnl': arg_10,
                                   'open_dt': arg_12[0],
                                   'close_dt': arg_7,
                                   'long': arg_13 < 0,
                                   'rt_returns': arg_10 / arg_11,
                                   'symbol': arg_3,
                                   })

    arg_2 = pd.DataFrame(arg_2)

    arg_2['duration'] = arg_2['close_dt'].sub(arg_2['open_dt'])

    if arg_1 is not None:
        # Need to normalize so that we can join
        arg_16 = pd.DataFrame(arg_1,
                          columns=['portfolio_value'])\
            .assign(date=arg_1.index)

        arg_2['date'] = arg_2.close_dt.apply(lambda x:
                                                       x.replace(hour=0,
                                                                 minute=0,
                                                                 second=0))

        arg_17 = arg_2.join(arg_16, on='date', lsuffix='_')

        arg_2['returns'] = arg_17.pnl / arg_17.portfolio_value
        arg_2 = arg_2.drop('date', axis='columns')

    return arg_2

Group transactions into round trips . First transactions are grouped by day and directionality . Then long and short transactions are matched to create round - trip round_trips for which PnL duration and returns are computed . Crossings where a position changes from long to short and vice - versa are handled correctly .


(self, target_address, source_address, handler, properties)

def
Func
(
arg_0
,
arg_1
,
arg_2
,
arg_3
,
arg_4
)
:
arg_0
.
_handler
=
arg_3
arg_0
.
_properties
=
arg_4
arg_7
=
if
arg_4
:
arg_7
=
arg_4
.
get
(
"dynamic-node-properties"
)
arg_8
=
_dist_modes
.
get
(
arg_4
.
get
(
"distribution-mode"
)
)
if
arg_8
is
not
:
arg_0
.
_pn_link
.
source
.
distribution_mode
=
arg_8
arg_8
=
_snd_settle_modes
.
get
(
arg_4
.
get
(
"snd-settle-mode"
)
)
if
arg_8
is
not
:
arg_0
.
_pn_link
.
snd_settle_mode
=
arg_8
arg_8
=
_rcv_settle_modes
.
get
(
arg_4
.
get
(
"rcv-settle-mode"
)
)
if
arg_8
is
not
:
arg_0
.
_pn_link
.
rcv_settle_mode
=
arg_8
if
arg_1
is
:
if
not
arg_0
.
_pn_link
.
is_sender
:
raise
Exception
(
"Dynamic target not allowed"
)
arg_0
.
_pn_link
.
target
.
dynamic
=
True
if
arg_7
:
arg_0
.
_pn_link
.
target
.
properties
.
clear
(
)
arg_0
.
_pn_link
.
target
.
properties
.
put_dict
(
arg_7
)
elif
arg_1
:
arg_0
.
_pn_link
.
target
.
address
=
arg_1
if
arg_2
is
:
if
not
arg_0
.
_pn_link
.
is_receiver
:
raise
Exception
(
"Dynamic source not allowed"
)
arg_0
.
_pn_link
.
source
.
dynamic
=
True
if
arg_7
:
arg_0
.
_pn_link
.
source
.
properties
.
clear
(
)
arg_0
.
_pn_link
.
source
.
properties
.
put_dict
(
arg_7
)
elif
arg_2
:
arg_0
.
_pn_link
.
source
.
address
=
arg_2

def Func(arg_0, arg_1, arg_2, arg_3, arg_4):
        """Assign addresses, properties, etc."""
        arg_0._handler = arg_3
        arg_0._properties = arg_4

        arg_7 = None
        if arg_4:
            arg_7 = arg_4.get("dynamic-node-properties")
            arg_8 = _dist_modes.get(arg_4.get("distribution-mode"))
            if arg_8 is not None:
                arg_0._pn_link.source.distribution_mode = arg_8
            arg_8 = _snd_settle_modes.get(arg_4.get("snd-settle-mode"))
            if arg_8 is not None:
                arg_0._pn_link.snd_settle_mode = arg_8
            arg_8 = _rcv_settle_modes.get(arg_4.get("rcv-settle-mode"))
            if arg_8 is not None:
                arg_0._pn_link.rcv_settle_mode = arg_8

        if arg_1 is None:
            if not arg_0._pn_link.is_sender:
                raise Exception("Dynamic target not allowed")
            arg_0._pn_link.target.dynamic = True
            if arg_7:
                arg_0._pn_link.target.properties.clear()
                arg_0._pn_link.target.properties.put_dict(arg_7)
        elif arg_1:
            arg_0._pn_link.target.address = arg_1

        if arg_2 is None:
            if not arg_0._pn_link.is_receiver:
                raise Exception("Dynamic source not allowed")
            arg_0._pn_link.source.dynamic = True
            if arg_7:
                arg_0._pn_link.source.properties.clear()
                arg_0._pn_link.source.properties.put_dict(arg_7)
        elif arg_2:
            arg_0._pn_link.source.address = arg_2


def
Func
(
arg_0
,
arg_1
)
:
LOG
.
info
(
"Running scout export Func"
)
arg_2
=
arg_0
.
obj
[
'adapter'
]
arg_3
=
[
"#Gene_id\tCount"
]
if
not
arg_1
:
LOG
.
warning
(
"Please use at least one hpo term"
)
arg_0
.
abort
(
)
for
arg_4
in
arg_3
:
click
.
echo
(
arg_4
)
for
arg_5
in
arg_2
.
generate_hpo_gene_list
(
*
arg_1
)
:
click
.
echo
(
"{0}\t{1}"
.
format
(
arg_5
[
0
]
,
arg_5
[
1
]
)
)

def Func(arg_0, arg_1):
    """Export a list of genes based on hpo terms"""
    LOG.info("Running scout export Func")
    arg_2 = arg_0.obj['adapter']

    arg_3 = ["#Gene_id\tCount"]

    if not arg_1:
        LOG.warning("Please use at least one hpo term")
        arg_0.abort()

    for arg_4 in arg_3:
        click.echo(arg_4)

    for arg_5 in arg_2.generate_hpo_gene_list(*arg_1):
        click.echo("{0}\t{1}".format(arg_5[0], arg_5[1]))


def Func(arg_0, arg_1=None):
    """
    Creates a TFS Git Client to pull Git repo info
    """
    if arg_1 is None:
        arg_1 = os.environ.get('TFS_API_TOKEN', None)

    arg_2 = create_tfs_connection(arg_0, arg_1)
    arg_3 = arg_2.get_client('vsts.git.v4_1.git_client.GitClient')

    if arg_3 is None:
        arg_4 = 'Unable to create TFS Git Client, failed to connect to TFS Enterprise (%s) with provided token.'
        raise RuntimeError(arg_4, arg_0)

    return arg_3


def Func(arg_0, arg_1, arg_2):
        """Check whether a path is ignored. For directories, include a trailing slash."""
        arg_3 = None
        for arg_4 in arg_0.find_matching(arg_1, arg_2):
            arg_3 = arg_4.is_exclude
        return arg_3

Check whether a path is ignored . For directories include a trailing slash .


def Func ( arg_0 , arg_1 = None ) : arg_1 = _make_callable ( arg_1 ) return Collection ( Func ( arg_1 , arg_0 . _items ) )

def Func(arg_0, arg_1=None):
        """
        Return a new Collection with the first few items removed.

        Parameters:

            func : function(Node) -> Node

        Returns:

            A new Collection, discarding all items
            before the first item where bool(func(item)) == True
        """
        arg_1 = _make_callable(arg_1)
        return Collection(Func(arg_1, arg_0._items))

Return a new Collection with the first few items removed .


def Func(arg_0):
    """Setup argparser to process arguments and generate help"""

    # parser uses custom usage string, with 'usage: ' removed, as it is
    # added automatically via argparser.
    arg_1 = argparse.ArgumentParser(description="Remove and/or rearrange "
                                     + "sections from each line of a file(s).",
                                     usage=_usage()[len('usage: '):])
    arg_1.add_argument('-b', "--bytes", action='store', type=lst, default=[],
                        help="Bytes to select")
    arg_1.add_argument('-c', "--chars", action='store', type=lst, default=[],
                        help="Character to select")
    arg_1.add_argument('-f', "--fields", action='store', type=lst, default=[],
                        help="Fields to select")
    arg_1.add_argument('-d', "--delimiter", action='store', default="\t",
                        help="Sets field delimiter(default is TAB)")
    arg_1.add_argument('-e', "--regex", action='store_true',
                        help='Enable regular expressions to be used as input '+
                        'delimiter')
    arg_1.add_argument('-s', '--skip', action='store_true',
                        help="Skip lines that do not contain input delimiter.")
    arg_1.add_argument('-S', "--separator", action='store', default="\t",
                        help="Sets field separator for output.")
    arg_1.add_argument('file', nargs='*', default="-",
                        help="File(s) to cut")

    return arg_1.parse_args(arg_0)


return self._nn_interface._add_generic(self, type_name=CONFIG_GROUP,
                                               group_type_name=CONFIG_GROUP,
                                               args=args, kwargs=kwargs)

def Func(arg_0, *arg_1, **arg_2):
        """Adds an empty config group under the current node.

        Adds the full name of the current node as prefix to the name of the group.
        If current node is the trajectory (root), the prefix `'config'` is added to the full name.

        The `name` can also contain subgroups separated via colons, for example:
        `name=subgroup1.subgroup2.subgroup3`. These other parent groups will be automatically
        be created.

        """
        return arg_0._nn_interface._add_generic(arg_0, type_name=CONFIG_GROUP,
                                               group_type_name=CONFIG_GROUP,
                                               arg_1=arg_1, arg_2=arg_2)

Adds an empty config group under the current node .


(guard: StateGuard[A], desc: str, thunk: Callable[..., NS[A, B]], *a: Any)

def
Func
(
arg_0
:
arg_1
[
arg_2
]
,
arg_3
:
arg_4
,
arg_5
:
arg_6
[
...
,
arg_7
[
arg_2
,
arg_8
]
]
,
*
arg_9
:
arg_10
)
->
Do
:
yield
arg_0
.
acquire
(
)
log
.
debug2
(
lambda
:
f'exclusive: {desc}'
)
arg_11
,
arg_12
=
yield
N
.
ensure_failure
(
arg_5
(
*
arg_9
)
.
run
(
arg_0
.
state
)
,
arg_0
.
release
)
yield
N
.
delay
(
lambda
v
:
unsafe_update_state
(
arg_0
,
arg_11
)
)
yield
arg_0
.
release
(
)
log
.
debug2
(
lambda
:
f'release: {desc}'
)
yield
N
.
pure
(
arg_12
)

def Func(arg_0: arg_1[arg_2], arg_3: arg_4, arg_5: arg_6[..., arg_7[arg_2, arg_8]], *arg_9: arg_10) -> Do:
    '''this is the central unsafe function, using a lock and updating the state in `guard` in-place.
    '''
    yield arg_0.acquire()
    log.debug2(lambda: f'exclusive: {desc}')
    arg_11, arg_12 = yield N.ensure_failure(arg_5(*arg_9).run(arg_0.state), arg_0.release)
    yield N.delay(lambda v: unsafe_update_state(arg_0, arg_11))
    yield arg_0.release()
    log.debug2(lambda: f'release: {desc}')
    yield N.pure(arg_12)

this is the central unsafe function using a lock and updating the state in guard in - place .


def
Func
(
arg_0
,
arg_1
)
:
arg_1
.
write
(
'# Review\n\n'
)
write_value
(
'Reviewer'
,
arg_0
.
reviewer
,
arg_1
)
write_value
(
'ReviewDate'
,
arg_0
.
review_date_iso_format
,
arg_1
)
if
arg_0
.
has_comment
:
write_text_value
(
'ReviewComment'
,
arg_0
.
comment
,
arg_1
)

def Func(arg_0, arg_1):
    """
    Write the fields of a single review to out.
    """
    arg_1.write('# Review\n\n')
    write_value('Reviewer', arg_0.reviewer, arg_1)
    write_value('ReviewDate', arg_0.review_date_iso_format, arg_1)
    if arg_0.has_comment:
        write_text_value('ReviewComment', arg_0.comment, arg_1)

Write the fields of a single review to out .


def Func ( arg_0 ) : try : arg_1 , arg_2 = map ( int , ( arg_0 . GET . get ( 'cal_next' , 0 ) , arg_0 . GET . get ( 'cal_prev' , 0 ) ) ) arg_3 = arg_1 - arg_2 except Exception : arg_3 = 0 return arg_3

def Func(arg_0):
    """Get the net of any 'next' and 'prev' querystrings."""
    try:
        arg_1, arg_2 = map(
            int, (arg_0.GET.get('cal_next', 0), arg_0.GET.get('cal_prev', 0))
        )
        arg_3 = arg_1 - arg_2
    except Exception:
        arg_3 = 0
    return arg_3

Get the net of any next and prev querystrings .


(self, spotify_id: str, *, market: str = 'US')

async def Func ( arg_0 , arg_1 : arg_2 , * , arg_3 : arg_2 = 'US' ) -> Album : arg_4 = await arg_0 . http . album ( to_id ( arg_1 ) , arg_3 = arg_3 ) return Album ( arg_0 , arg_4 )

async def Func(arg_0, arg_1: arg_2, *, arg_3: arg_2 = 'US') -> Album:
        """Retrive an album with a spotify ID.

        Parameters
        ----------
        spotify_id : str
            The ID to search for.
        market : Optional[str]
            An ISO 3166-1 alpha-2 country code

        Returns
        -------
        album : Album
            The album from the ID
        """
        arg_4 = await arg_0.http.album(to_id(arg_1), arg_3=arg_3)
        return Album(arg_0, arg_4)


def Func ( arg_0 , arg_1 ) : if not arg_1 : return None if not hasattr ( arg_1 , "ports" ) or len ( arg_1 . ports ) <= 0 : return [ ] return arg_1 . ports

def Func(arg_0, arg_1):
    """Gather all ports associated to security group.

    Returns:
    * list, or None
    """
    if not arg_1:
        return None
    if not hasattr(arg_1, "ports") or len(arg_1.ports) <= 0:
        return []
    return arg_1.ports

Gather all ports associated to security group .


def Func(arg_0, arg_1):
    """
    Check to see if a proposed tuple of axes is a valid reshaping of
    the old axes by ensuring that they can be factored.

    Parameters
    ----------
    new : tuple
        tuple of proposed axes

    old : tuple
        tuple of old axes
    """

    arg_0, arg_1 = tupleize(arg_0), tupleize(arg_1)

    if not prod(arg_0) == prod(arg_1):
        raise ValueError("Total size of new keys must remain unchanged")

Check to see if a proposed tuple of axes is a valid reshaping of the old axes by ensuring that they can be factored .


return trolly.card.Card(
            trello_client=self,
            card_id=card_json['id'],
            name=card_json['name'],
            data=card_json,
        )

def Func ( arg_0 , arg_1 ) : return trolly . card . Card ( trello_client = arg_0 , card_id = arg_1 [ 'id' ] , name = arg_1 [ 'name' ] , data = arg_1 , )

def Func(arg_0, arg_1):
        '''
        Create a Card object from JSON object

        Returns:
            Card: The card from the given `card_json`.
        '''
        return trolly.card.Card(
            trello_client=arg_0,
            card_id=arg_1['id'],
            name=arg_1['name'],
            data=arg_1,
        )


def Func ( arg_0 ) : if Crates . metadata_category ( arg_0 ) == CATEGORY_CRATES : return str ( arg_0 [ 'id' ] ) else : arg_1 = arg_0 [ 'fetched_on' ] arg_1 = str_to_datetime ( arg_1 ) return str ( arg_1 . timestamp ( ) )

def Func(arg_0):
        """Extracts the identifier from an item depending on its type."""

        if Crates.metadata_category(arg_0) == CATEGORY_CRATES:
            return str(arg_0['id'])
        else:
            arg_1 = arg_0['fetched_on']
            arg_1 = str_to_datetime(arg_1)
            return str(arg_1.timestamp())

Extracts the identifier from an item depending on its type .


def
Func
(
arg_0
,
arg_1
,
arg_2
)
:
if
arg_1
.
lower
(
)
not
in
(
'.gz'
,
'.bz2'
)
:
raise
NotImplementedError
(
"Received {} format. Only gz and bz2 "
"files can currently be uncompressed."
.
format
(
arg_1
)
)
if
arg_1
.
lower
(
)
==
'.gz'
:
arg_3
=
gzip
.
GzipFile
elif
arg_1
.
lower
(
)
==
'.bz2'
:
arg_3
=
bz2
.
BZ2File
with
arg_3
(
arg_0
,
mode
=
'rb'
)
as
f_compressed
,
NamedTemporaryFile
(
dir
=
arg_2
,
mode
=
'wb'
,
delete
=
False
)
as
f_uncompressed
:
shutil
.
copyfileobj
(
f_compressed
,
f_uncompressed
)
return
f_uncompressed
.
name

def Func(arg_0, arg_1, arg_2):
    """
    Uncompress gz and bz2 files
    """
    if arg_1.lower() not in ('.gz', '.bz2'):
        raise NotImplementedError("Received {} format. Only gz and bz2 "
                                  "files can currently be uncompressed."
                                  .format(arg_1))
    if arg_1.lower() == '.gz':
        arg_3 = gzip.GzipFile
    elif arg_1.lower() == '.bz2':
        arg_3 = bz2.BZ2File
    with arg_3(arg_0, mode='rb') as f_compressed,\
        NamedTemporaryFile(dir=arg_2,
                           mode='wb',
                           delete=False) as f_uncompressed:
        shutil.copyfileobj(f_compressed, f_uncompressed)
    return f_uncompressed.name


def Func(arg_0, arg_1, arg_2=None):
        """
        Flexible access to specific filter using any key format.

        Parameters
        ----------
        f : str, dict or bool
            either logical filter expression, dict of expressions,
            or a boolean
        analyte : str
            name of analyte the filter is for.

        Returns
        -------
        array_like
            boolean filter
        """
        if isinstance(arg_1, str):
            if arg_1 in arg_0.components:
                if arg_2 is None:
                    return arg_0.components[arg_1]
                else:
                    if arg_0.switches[arg_2][arg_1]:
                        return arg_0.components[arg_1]
            else:
                try:
                    arg_3 = arg_0.make_fromkey(arg_1)
                except KeyError:
                    print(("\n\n***Filter key invalid. Please consult "
                           "manual and try again."))
        elif isinstance(arg_1, dict):
            try:
                arg_3 = arg_0.make_fromkey(arg_1[arg_2])
            except ValueError:
                print(("\n\n***Filter key invalid. Please consult manual "
                       "and try again.\nOR\nAnalyte missing from filter "
                       "key dict."))
        elif arg_1:
            arg_3 = arg_0.make(arg_2)
        else:
            arg_3 = ~np.zeros(arg_0.size, dtype=bool)
        return arg_3

Flexible access to specific filter using any key format .


(self, jid, name = NO_CHANGE, groups = NO_CHANGE,
                                callback = None, error_callback = None)

def Func(arg_0, arg_1, arg_2 = arg_3, arg_4 = arg_3,
                                arg_5 = None, arg_6 = None):
        """Modify a contact in the roster.

        :Parameters:
            - `jid`: contact's jid
            - `name`: a new name for the contact
            - `groups`: a sequence of group names the contact should belong to
            - `callback`: function to call when the request succeeds. It should
              accept a single argument - a `RosterItem` describing the
              requested change
            - `error_callback`: function to call when the request fails. It
              should accept a single argument - an error stanza received
              (`None` in case of timeout)
        :Types:
            - `jid`: `JID`
            - `name`: `unicode`
            - `groups`: sequence of `unicode`
        """
        # pylint: disable=R0913
        arg_7 = arg_0.roster[arg_1]
        if arg_2 is arg_3 and arg_4 is arg_3:
            return
        if arg_2 is arg_3:
            arg_2 = arg_7.name
        if arg_4 is arg_3:
            arg_4 = arg_7.groups
        arg_7 = RosterItem(arg_1, arg_2, arg_4)
        arg_0._roster_set(arg_7, arg_5, arg_6)


def Func(arg_0, arg_1, arg_2):  #pylint: disable=unused-argument
        """Samples current stack and adds result in self._stats.

        Args:
            signum: Signal that activates handler.
            frame: Frame on top of the stack when signal is handled.
        """
        arg_3 = []
        while arg_2 and arg_2 != arg_0.base_frame:
            arg_3.append((
                arg_2.f_code.co_name,
                arg_2.f_code.co_filename,
                arg_2.f_code.co_firstlineno))
            arg_2 = arg_2.f_back
        arg_0._stats[tuple(arg_3)] += 1
        signal.setitimer(signal.ITIMER_PROF, _SAMPLE_INTERVAL)

Samples current stack and adds result in self . _stats .


def Func(arg_0):
        """Output object of driver."""
        arg_1 = dict(
            arg_0._raw["Func"],
            grid=arg_0.Func_pyramid.grid,
            pixelbuffer=arg_0.Func_pyramid.pixelbuffer,
            metatiling=arg_0.Func_pyramid.metatiling
        )
        if "path" in arg_1:
            arg_1.update(
                path=absolute_path(path=arg_1["path"], base_dir=arg_0.config_dir)
            )

        if "format" not in arg_1:
            raise MapcheteConfigError("Func format not specified")

        if arg_1["format"] not in available_Func_formats():
            raise MapcheteConfigError(
                "format %s not available in %s" % (
                    arg_1["format"], str(available_Func_formats())
                )
            )
        arg_2 = load_Func_writer(arg_1)
        try:
            arg_2.is_valid_with_config(arg_1)
        except Exception as e:
            logger.exception(e)
            raise MapcheteConfigError(
                "driver %s not compatible with configuration: %s" % (
                    arg_2.METADATA["driver_name"], e
                )
            )
        return arg_2


def Func(arg_0, arg_1, arg_2=arg_3.KMIPVersion.KMIP_2_0):
        """
        Write the Attributes structure encoding to the data stream.

        Args:
            output_stream (stream): A data stream in which to encode
                Attributes structure data, supporting a Func method.
            kmip_version (enum): A KMIPVersion enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 2.0.

        Raises:
            AttributeNotSupported: Raised if an unsupported attribute is
                found in the attribute list while encoding.
            VersionNotSupported: Raised when a KMIP version is provided that
                does not support the Attributes object.
        """
        if arg_2 < arg_3.KMIPVersion.KMIP_2_0:
            raise exceptions.VersionNotSupported(
                "KMIP {} does not support the Attributes object.".format(
                    arg_2.value
                )
            )

        arg_6 = BytearrayStream()

        for arg_7 in arg_0._attributes:
            arg_8 = arg_7.tag
            if not arg_3.is_attribute(arg_8, arg_2=arg_2):
                raise exceptions.AttributeNotSupported(
                    "Attribute {} is not supported by KMIP {}.".format(
                        arg_8.name,
                        arg_2.value
                    )
                )
            arg_7.Func(arg_6, arg_2=arg_2)

        arg_0.length = arg_6.length()
        super(Attributes, arg_0).Func(arg_1, arg_2=arg_2)
        arg_1.Func(arg_6.buffer)

Write the Attributes structure encoding to the data stream.

        Args:
            output_stream (stream): A data stream in which to encode
                Attributes structure data, supporting a write method.
            kmip_version (enum): A KMIPVersion enumeration defining the KMIP
                version with which the object will be encoded. Optional,
                defaults to KMIP 2.0.

        Raises:
            AttributeNotSupported: Raised if an unsupported attribute is
                found in the attribute list while encoding.
            VersionNotSupported: Raised when a KMIP version is provided that
                does not support the Attributes object.

Write the Attributes structure encoding to the data stream .


return partuple(
        pickle_fname, in_callables_fname, out_callables_fname, noption, exclude
    )

def Func ( arg_0 ) : arg_1 = os . path . join ( os . path . dirname ( __file__ ) , "{0}.pkl" . format ( arg_0 ) ) arg_2 = os . path . dirname ( os . path . dirname ( __file__ ) ) arg_3 = os . path . join ( arg_2 , "moddb.json" ) arg_4 = arg_3 if os . path . exists ( arg_3 ) else None arg_5 = os . path . join ( arg_2 , "{0}.json" . format ( arg_0 ) ) arg_6 = os . environ . get ( "NOPTION" , None ) arg_7 = [ "_pytest" , "execnet" ] arg_8 = collections . namedtuple ( "ParTuple" , [ "pickle_fname" , "in_callables_fname" , "out_callables_fname" , "noption" , "exclude" , ] , ) return arg_8 ( arg_1 , arg_4 , arg_5 , arg_6 , arg_7 )

def Func(arg_0):
    """Define trace parameters."""
    arg_1 = os.path.join(os.path.dirname(__file__), "{0}.pkl".format(arg_0))
    arg_2 = os.path.dirname(os.path.dirname(__file__))
    arg_3 = os.path.join(arg_2, "moddb.json")
    arg_4 = arg_3 if os.path.exists(arg_3) else None
    arg_5 = os.path.join(arg_2, "{0}.json".format(arg_0))
    arg_6 = os.environ.get("NOPTION", None)
    arg_7 = ["_pytest", "execnet"]
    arg_8 = collections.namedtuple(
        "ParTuple",
        [
            "pickle_fname",
            "in_callables_fname",
            "out_callables_fname",
            "noption",
            "exclude",
        ],
    )
    return arg_8(
        arg_1, arg_4, arg_5, arg_6, arg_7
    )


def Func ( arg_0 = None ) : def _context ( arg_1 ) : annotated ( arg_1 , arg_0 ) arg_1 . context = True return arg_1 return _context

def Func(arg_0=None):
    """Declare that a class defines a context.

    Contexts are for use with HierarchicalShell for discovering
    and using functionality from the command line.

    Args:
        name (str): Optional name for this context if you don't want
            to just use the class name.
    """

    def _context(arg_1):
        annotated(arg_1, arg_0)
        arg_1.context = True

        return arg_1

    return _context

Declare that a class defines a context .


def Func(arg_0):
    """Initiate the local catalog by downloading the cloud catalog"""

    (arg_1, arg_2) = (arg_0.local_catalog, arg_0.cloud_catalog)
    logging.info("[init-pull-from-cloud]: %s => %s"%(arg_2, arg_1))

    if isfile(arg_1):
        arg_0.error("[init-pull-from-cloud] The local catalog already exist: %s"%arg_1)
    if not isfile(arg_2):
        arg_0.error("[init-pull-from-cloud] The cloud catalog does not exist: %s"%arg_2)

    (arg_3, arg_4) = ("%s.lrcloud"%arg_1, "%s.lrcloud"%arg_2)
    if isfile(arg_3):
        arg_0.error("[init-pull-from-cloud] The local meta-data already exist: %s"%arg_3)
    if not isfile(arg_4):
        arg_0.error("[init-pull-from-cloud] The cloud meta-data does not exist: %s"%arg_4)

    #Let's "lock" the local catalog
    logging.info("Locking local catalog: %s"%(arg_1))
    if not lock_file(arg_1):
        raise RuntimeError("The catalog %s is locked!"%arg_1)

    #Copy base from cloud to local
    util.copy(arg_2, arg_1)

    #Apply changesets
    arg_5 = ChangesetDAG(arg_2)
    arg_6 = arg_5.path(arg_5.root.hash, arg_5.leafs[0].hash)
    util.apply_changesets(arg_0, arg_6, arg_1)

    # Write meta-data both to local and cloud
    arg_7 = MetaFile(arg_3)
    arg_8 = datetime.utcnow().strftime(DATETIME_FORMAT)[:-4]
    arg_7['catalog']['hash'] = hashsum(arg_1)
    arg_7['catalog']['modification_utc'] = arg_8
    arg_7['catalog']['filename'] = arg_1
    arg_7['last_push']['filename'] = arg_5.leafs[0].mfile['changeset']['filename']
    arg_7['last_push']['hash'] = arg_5.leafs[0].mfile['changeset']['hash']
    arg_7['last_push']['modification_utc'] = arg_5.leafs[0].mfile['changeset']['modification_utc']
    arg_7.flush()

    #Let's copy Smart Previews
    if not arg_0.no_smart_previews:
        copy_smart_previews(arg_1, arg_2, local2cloud=False)

    #Finally, let's unlock the catalog files
    logging.info("Unlocking local catalog: %s"%(arg_1))
    unlock_file(arg_1)

    logging.info("[init-pull-from-cloud]: Success!")


(gene_list, correl_vector, gene_set, weighted_score_type=1,
                     nperm=1000, rs=np.random.RandomState(), single=False, scale=False)

def Func(arg_0, arg_1, arg_2, arg_3=1,
                     arg_4=1000, arg_5=arg_6.random.RandomState(), arg_9=False, arg_10=False):
    """This is the most important function of GSEApy. It has the same algorithm with GSEA and ssGSEA.

    :param gene_list:       The ordered gene list gene_name_list, rank_metric.index.values
    :param gene_set:        gene_sets in gmt file, please use gsea_gmt_parser to get gene_set.
    :param weighted_score_type:  It's the same with gsea's weighted_score method. Weighting by the correlation
                            is a very reasonable choice that allows significant gene sets with less than perfect coherence.
                            options: 0(classic),1,1.5,2. default:1. if one is interested in penalizing sets for lack of
                            coherence or to discover sets with any type of nonrandom distribution of tags, a value p < 1
                            might be appropriate. On the other hand, if one uses sets with large number of genes and only
                            a small subset of those is expected to be coherent, then one could consider using p > 1.
                            Our recommendation is to use p = 1 and use other settings only if you are very experienced
                            with the method and its behavior.

    :param correl_vector:   A vector with the correlations (e.g. signal to noise scores) corresponding to the genes in
                            the gene list. Or rankings, rank_metric.values
    :param nperm:           Only use this parameter when computing esnull for statistical testing. Set the esnull value
                            equal to the permutation number.
    :param rs:              Random state for initializing gene list shuffling. Default: np.random.RandomState(seed=None)

    :return:

     ES: Enrichment score (real number between -1 and +1)

     ESNULL: Enrichment score calculated from random permutations.

     Hits_Indices: Index of a gene in gene_list, if gene is included in gene_set.

     RES: Numerical vector containing the running enrichment score for all locations in the gene list .

    """

    arg_11 = len(arg_0)
    # Test whether each element of a 1-D array is also present in a second array
    # It's more intuitive here than original Func source code.
    # use .astype to covert bool to integer
    arg_12 = arg_6.in1d(arg_0, arg_2, assume_unique=True).astype(int)  # notice that the sign is 0 (no tag) or 1 (tag)

    if arg_3 == 0 :
        arg_1 = arg_6.repeat(1, arg_11)
    else:
        arg_1 = arg_6.abs(arg_1)**arg_3

    # get indices of tag_indicator
    arg_13 = arg_6.flatnonzero(arg_12).tolist()
    # if used for compute esnull, set esnull equal to permutation number, e.g. 1000
    # else just compute enrichment scores
    # set axis to 1, because we have 2D array
    arg_14 = 1
    arg_12 = arg_6.tile(arg_12, (arg_4+1,1))
    arg_1 = arg_6.tile(arg_1,(arg_4+1,1))
    # gene list permutation
    for arg_15 in range(arg_4): arg_5.shuffle(arg_12[arg_15])
    # np.apply_along_axis(rs.shuffle, 1, tag_indicator)

    arg_16 = arg_12.sum(arg_14=arg_14, keepdims=True)
    arg_17 = arg_6.sum(arg_1*arg_12, arg_14=arg_14, keepdims=True)
    # compute ES score, the code below is identical to gsea Func method.
    arg_18 = 1 - arg_12
    arg_19 =  arg_11 - arg_16
    arg_20 =  1.0/arg_17
    arg_21 = 1.0/arg_19

    arg_22 = arg_6.cumsum(arg_12 * arg_1 * arg_20 - arg_18 * arg_21, arg_14=arg_14)

    if arg_10: arg_22 = arg_22 / arg_11
    if arg_9:
        arg_23 = arg_22.sum(arg_14=arg_14)
    else:
        arg_24, arg_25 =  arg_22.max(arg_14=arg_14), arg_22.min(arg_14=arg_14)
        arg_23 = arg_6.where(arg_6.abs(arg_24) > arg_6.abs(arg_25), arg_24, arg_25)
    # extract values
    arg_26, arg_27, arg_22 = arg_23[-1], arg_23[:-1], arg_22[-1,:]

    return arg_26, arg_27, arg_13, arg_22

This is the most important function of GSEApy . It has the same algorithm with GSEA and ssGSEA .


def Func(arg_0, arg_1):
  """Return the most recent non-blank line and its line number.

  Args:
    clean_lines: A CleansedLines instance containing the file contents.
    linenum: The number of the line to check.

  Returns:
    A tuple with two elements.  The first element is the contents of the last
    non-blank line before the current line, or the empty string if this is the
    first non-blank line.  The second is the line number of that line, or -1
    if this is the first non-blank line.
  """

  arg_2 = arg_1 - 1
  while arg_2 >= 0:
    arg_3 = arg_0.elided[arg_2]
    if not IsBlankLine(arg_3):     # if not a blank line...
      return (arg_3, arg_2)
    arg_2 -= 1
  return ('', -1)

Return the most recent non - blank line and its line number .


def Func ( arg_0 ) : arg_1 = arg_0 . tabWidget . current_widget ( ) . file . path arg_2 = os . path . dirname ( arg_1 ) arg_3 = Settings ( ) . get_run_config_for_file ( arg_1 ) arg_0 . interactiveConsole . start_process ( Settings ( ) . interpreter , arg_3 = [ arg_1 ] + arg_3 , cwd = arg_2 ) arg_0 . dockWidget . show ( ) arg_0 . actionRun . setEnabled ( False ) arg_0 . actionConfigure_run . setEnabled ( False )

def Func(arg_0):
        """
        Run the current current script
        """
        arg_1 = arg_0.tabWidget.current_widget().file.path
        arg_2 = os.path.dirname(arg_1)
        arg_3 = Settings().get_run_config_for_file(arg_1)
        arg_0.interactiveConsole.start_process(
            Settings().interpreter, arg_3=[arg_1] + arg_3, cwd=arg_2)
        arg_0.dockWidget.show()
        arg_0.actionRun.setEnabled(False)
        arg_0.actionConfigure_run.setEnabled(False)


def
Func
(
arg_0
)
:
logger
.
debug
(
"will wait for last plot to finish"
)
arg_0
.
_plot_event
=
threading
.
Event
(
)
arg_0
.
queue_update
.
Func
(
)
arg_0
.
queue_replot
.
Func
(
)
arg_0
.
queue_redraw
.
Func
(
)
arg_2
=
QtCore
.
QCoreApplication
.
instance
(
)
arg_3
=
10
while
not
arg_0
.
_plot_event
.
is_set
(
)
:
logger
.
debug
(
"waiting for last plot to finish"
)
arg_2
.
processEvents
(
)
QtTest
.
QTest
.
qSleep
(
arg_3
)
logger
.
debug
(
"waiting for plot finished"
)

def Func(arg_0):
        """Used for unittesting to make sure the plots are all done"""
        logger.debug("will wait for last plot to finish")
        arg_0._plot_event = threading.Event()
        arg_0.queue_update.Func()
        arg_0.queue_replot.Func()
        arg_0.queue_redraw.Func()
        arg_2 = QtCore.QCoreApplication.instance()
        arg_3 = 10
        while not arg_0._plot_event.is_set():
            logger.debug("waiting for last plot to finish")
            arg_2.processEvents()
            QtTest.QTest.qSleep(arg_3)
        logger.debug("waiting for plot finished")


def Func(arg_0, arg_1):
        """
        Internal scan with dummy input variables.
        """
        from neural_var import NeuralVariable
        if not arg_0._loop_vars:
            raise Exception("The loop is not initialized. To initialize the loop, use `with loop as vars`")
        arg_2 = {}
        for arg_3, arg_4 in arg_1.items():
            if arg_4 is not None:
                arg_2[arg_0._dummy_nodes[arg_3].tensor] = arg_4.tensor
        arg_7 = {}
        for arg_3 in arg_0._outputs:
            if arg_3 not in arg_0._loop_vars:
                raise Exception("{} can not be found in loop vars.".format(arg_3))
            arg_8 = theano.clone(arg_0._loop_vars[arg_3].tensor, arg_2)
            arg_7[arg_3] = NeuralVariable(arg_8, arg_0._loop_vars[arg_3].dim())
        return arg_7

Internal scan with dummy input variables .


def Func(arg_0, arg_1):
        """Insert a new chunk at the end of the IFF file"""

        if not isinstance(arg_1, text_type):
            arg_1 = arg_1.decode('ascii')

        if not is_valid_chunk_id(arg_1):
            raise KeyError("AIFF key must be four ASCII characters.")

        arg_0.__fileobj.seek(arg_0.__next_offset)
        arg_0.__fileobj.write(pack('>4si', arg_1.ljust(4).encode('ascii'), 0))
        arg_0.__fileobj.seek(arg_0.__next_offset)
        arg_2 = IFFChunk(arg_0.__fileobj, arg_0[u'FORM'])
        arg_0[u'FORM'].resize(arg_0[u'FORM'].data_size + arg_2.size)

        arg_0.__chunks[arg_1] = arg_2
        arg_0.__next_offset = arg_2.offset + arg_2.size


(self, trX, trY, batch_size=64, n_epochs=1, len_filter=LenFilter(), snapshot_freq=1, path=None)

def Func(arg_0, arg_1, arg_2, arg_3=64, arg_4=1, arg_5=arg_6(), arg_7=1, arg_8=None):
        """Train model on given training examples and return the list of costs after each minibatch is processed.

        Args:
          trX (list) -- Inputs
          trY (list) -- Outputs
          batch_size (int, optional) -- number of examples in a minibatch (default 64)
          n_epochs (int, optional)  -- number of epochs to train for (default 1)
          len_filter (object, optional) -- object to filter training example by length (default LenFilter())
          snapshot_freq (int, optional) -- number of epochs between saving model snapshots (default 1)
          path (str, optional) -- prefix of path where model snapshots are saved.
            If None, no snapshots are saved (default None)

        Returns:
          list -- costs of model after processing each minibatch
        """
        if arg_5 is not None:
            arg_1, arg_2 = arg_5.filter(arg_1, arg_2)
        arg_2 = standardize_targets(arg_2, cost=arg_0.cost)

        arg_9 = 0.
        arg_10 = time()
        arg_11 = []
        for arg_12 in range(arg_4):
            arg_13 = []
            for arg_14, arg_15 in arg_0.iterator.iterXY(arg_1, arg_2):
                arg_16 = arg_0._train(arg_14, arg_15)
                arg_13.append(arg_16)
                arg_9 += len(arg_15)
                if arg_0.verbose >= 2:
                    arg_17 = arg_9 / (time() - arg_10)
                    arg_18 = len(arg_2) - arg_9 % len(arg_2)
                    arg_19 = arg_18/arg_17
                    sys.stdout.write("\rEpoch %d Seen %d samples Avg cost %0.4f Time left %d seconds" % (arg_12, arg_9, np.mean(arg_13[-250:]), arg_19))
                    sys.stdout.flush()
            arg_11.extend(arg_13)

            arg_20 = "Epoch %d Seen %d samples Avg cost %0.4f Time elapsed %d seconds" % (arg_12, arg_9, np.mean(arg_13[-250:]), time() - arg_10)
            if arg_0.verbose >= 2:
                sys.stdout.write("\r"+arg_20)
                sys.stdout.flush()
                sys.stdout.write("\n")
            elif arg_0.verbose == 1:
                print(arg_20)
            if arg_8 and arg_12 % arg_7 == 0:
                save(arg_0, "{0}.{1}".format(arg_8, arg_12))
        return arg_11

Train model on given training examples and return the list of costs after each minibatch is processed .


def Func ( arg_0 ) : arg_1 , arg_2 , arg_3 = arg_0 . partition ( '[0m' ) if arg_2 : return arg_3 else : return arg_0

def Func(arg_0):
    """
    remove extra characters before the actual string we are
    looking for.  The Jenkins console output is encoded using utf-8.  However, the stupid
    redirect function can only encode using ASCII.  I have googled for half a day with no
    results to how to resolve the issue.  Hence, we are going to the heat and just manually
    get rid of the junk.

    Parameters
    ----------

    string_content :  str
        contains a line read in from jenkins console

    :return: str: contains the content of the line after the string '[0m'

    """

    arg_1,arg_2,arg_3 = arg_0.partition('[0m')

    if arg_2:
        return arg_3
    else:
        return arg_0

remove extra characters before the actual string we are looking for . The Jenkins console output is encoded using utf - 8 . However the stupid redirect function can only encode using ASCII . I have googled for half a day with no results to how to resolve the issue . Hence we are going to the heat and just manually get rid of the junk .


(self, lat, lng, filters=None, startDate=None, endDate=None, types=None, type=None)

return self.search(searchAreaWkt=searchAreaWkt, filters=filters, startDate=startDate, endDate=endDate, types=types)

def Func(arg_0, arg_1, arg_2, arg_3=None, arg_4=None, arg_5=None, arg_6=None, arg_7=None):
        ''' Perform a catalog search over a specific point, specified by lat,lng

        Args:
            lat: latitude
            lng: longitude
            filters: Array of filters.  Optional.  Example:
            [
                "(sensorPlatformName = 'WORLDVIEW01' OR sensorPlatformName ='QUICKBIRD02')",
                "cloudCover < 10",
                "offNadirAngle < 10"
            ]
            startDate: string.  Optional.  Example: "2004-01-01T00:00:00.000Z"
            endDate: string.  Optional.  Example: "2004-01-01T00:00:00.000Z"
            types: Array of types to search for.  Optional.  Example (and default):  ["Acquisition"]

        Returns:
            catalog search resultset
        '''
        arg_8 = "POLYGON ((%s %s, %s %s, %s %s, %s %s, %s %s))" % (arg_2, arg_1,arg_2,arg_1,arg_2,arg_1,arg_2,arg_1,arg_2,arg_1)
        return arg_0.search(arg_8=arg_8, arg_3=arg_3, arg_4=arg_4, arg_5=arg_5, arg_6=arg_6)

Perform a catalog search over a specific point specified by lat lng


def Func(arg_0, arg_1):
        """
        Matches an outgoing HTTP request against the current mock Funcers.

        This method acts like a delegator to `pook.MatcherEngine`.

        Arguments:
            request (pook.Request): request instance to Func.

        Raises:
            Exception: if the mock has an exception defined.

        Returns:
            tuple(bool, list[Exception]): ``True`` if the mock Funces
                the outgoing HTTP request, otherwise ``False``. Also returns
                an optional list of error exceptions.
        """
        # If mock already expired, fail it
        if arg_0._times <= 0:
            raise PookExpiredMock('Mock expired')

        # Trigger mock filters
        for arg_2 in arg_0.filters:
            if not arg_2(arg_1, arg_0):
                return False, []

        # Trigger mock mappers
        for arg_3 in arg_0.mappers:
            arg_1 = arg_3(arg_1, arg_0)
            if not arg_1:
                raise ValueError('map function must return a request object')

        # Match incoming request against registered mock Funcers
        arg_4, arg_5 = arg_0.Funcers.Func(arg_1)

        # If not Funced, return False
        if not arg_4:
            return False, arg_5

        # Register Funced request for further inspecion and reference
        arg_0._calls.append(arg_1)

        # Increase mock call counter
        arg_0._Funces += 1
        if not arg_0._persist:
            arg_0._times -= 1

        # Raise simulated error
        if arg_0._error:
            raise arg_0._error

        # Trigger callback when Funced
        for arg_6 in arg_0.callbacks:
            arg_6(arg_1, arg_0)

        return True, []

Matches an outgoing HTTP request against the current mock matchers.

        This method acts like a delegator to `pook.MatcherEngine`.

        Arguments:
            request (pook.Request): request instance to match.

        Raises:
            Exception: if the mock has an exception defined.

        Returns:
            tuple(bool, list[Exception]): ``True`` if the mock matches
                the outgoing HTTP request, otherwise ``False``. Also returns
                an optional list of error exceptions.

Matches an outgoing HTTP request against the current mock matchers .


def Func(arg_0):
        """Path to the thumbnail of the album."""

        if arg_0._thumbnail:
            # stop if it is already set
            return arg_0._thumbnail

        # Test the thumbnail from the Markdown file.
        Func = arg_0.meta.get('thumbnail', [''])[0]

        if Func and isfile(join(arg_0.src_path, Func)):
            arg_0._thumbnail = url_from_path(join(
                arg_0.name, get_thumb(arg_0.settings, Func)))
            arg_0.logger.debug("Thumbnail for %r : %s", arg_0, arg_0._thumbnail)
            return arg_0._thumbnail
        else:
            # find and return the first landscape image
            for arg_3 in arg_0.medias:
                arg_4 = splitext(arg_3.filename)[1]
                if arg_4.lower() in arg_0.settings['img_extensions']:
                    # Use f.size if available as it is quicker (in cache), but
                    # fallback to the size of src_path if dst_path is missing
                    arg_5 = arg_3.size
                    if arg_5 is None:
                        arg_5 = get_size(arg_3.src_path)

                    if arg_5['width'] > arg_5['height']:
                        arg_0._thumbnail = (url_quote(arg_0.name) + '/' +
                                           arg_3.thumbnail)
                        arg_0.logger.debug(
                            "Use 1st landscape image as thumbnail for %r : %s",
                            arg_0, arg_0._thumbnail)
                        return arg_0._thumbnail

            # else simply return the 1st media file
            if not arg_0._thumbnail and arg_0.medias:
                for arg_6 in arg_0.medias:
                    if arg_6.thumbnail is not None:
                        arg_0._thumbnail = (url_quote(arg_0.name) + '/' +
                                           arg_6.thumbnail)
                        break
                else:
                    arg_0.logger.warning("No thumbnail found for %r", arg_0)
                    return None

                arg_0.logger.debug("Use the 1st image as thumbnail for %r : %s",
                                  arg_0, arg_0._thumbnail)
                return arg_0._thumbnail

            # use the thumbnail of their sub-directories
            if not arg_0._thumbnail:
                for arg_7, arg_8 in arg_0.gallery.get_albums(arg_0.path):
                    if arg_8.thumbnail:
                        arg_0._thumbnail = (url_quote(arg_0.name) + '/' +
                                           arg_8.thumbnail)
                        arg_0.logger.debug(
                            "Using thumbnail from sub-directory for %r : %s",
                            arg_0, arg_0._thumbnail)
                        return arg_0._thumbnail

        arg_0.logger.error('Thumbnail not found for %r', arg_0)
        return None


def Func ( arg_0 , arg_1 , arg_2 ) : arg_3 = [ arg_6 for arg_6 in arg_1 if arg_6 . value ] arg_4 = { 'OUTPUT_COUNT' : str ( len ( arg_3 ) ) } for arg_5 , arg_6 in enumerate ( arg_3 ) : arg_4 [ 'OUTPUT_{}' . format ( arg_5 ) ] = arg_6 . name arg_4 [ 'OUTPUT_RECURSIVE_{}' . format ( arg_5 ) ] = str ( int ( arg_6 . recursive ) ) arg_4 [ 'OUTPUT_SRC_{}' . format ( arg_5 ) ] = os . path . join ( providers_util . DATA_MOUNT_POINT , arg_6 . docker_path ) if '*' in arg_6 . uri . basename : arg_8 = arg_6 . uri . path else : arg_8 = arg_6 . uri arg_4 [ 'OUTPUT_DST_{}' . format ( arg_5 ) ] = arg_8 arg_4 [ 'USER_PROJECT' ] = arg_2 return arg_4

def Func(arg_0, arg_1, arg_2):
    """Return a dict with variables for the 'delocalization' action."""

    # Add variables for paths that need to be delocalized, for example:
    # OUTPUT_COUNT: 1
    # OUTPUT_0: MY_OUTPUT_FILE
    # OUTPUT_RECURSIVE_0: 0
    # OUTPUT_SRC_0: gs://mybucket/mypath/myfile
    # OUTPUT_DST_0: /mnt/data/outputs/mybucket/mypath/myfile

    arg_3 = [arg_6 for arg_6 in arg_1 if arg_6.value]
    arg_4 = {'OUTPUT_COUNT': str(len(arg_3))}

    for arg_5, arg_6 in enumerate(arg_3):
      arg_4['OUTPUT_{}'.format(arg_5)] = arg_6.name
      arg_4['OUTPUT_RECURSIVE_{}'.format(arg_5)] = str(int(arg_6.recursive))
      arg_4['OUTPUT_SRC_{}'.format(arg_5)] = os.path.join(
          providers_util.DATA_MOUNT_POINT, arg_6.docker_path)

      # For wildcard paths, the destination must be a directory
      if '*' in arg_6.uri.basename:
        arg_8 = arg_6.uri.path
      else:
        arg_8 = arg_6.uri
      arg_4['OUTPUT_DST_{}'.format(arg_5)] = arg_8

    arg_4['USER_PROJECT'] = arg_2

    return arg_4

Return a dict with variables for the delocalization action .


def Func ( arg_0 ) : arg_1 = arg_0 . getJobID ( ) arg_2 = _clientJobsDB ( ) . modelsGetUpdateCounters ( arg_1 ) arg_3 = tuple ( x [ 0 ] for x in arg_2 ) return arg_3

def Func(arg_0):
    """Queuries DB for model IDs of all currently instantiated models
    associated with this HyperSearch job.

    See also: _iterModels()

    Parameters:
    ----------------------------------------------------------------------
    retval:         A sequence of Nupic modelIDs
    """
    arg_1 = arg_0.getJobID()
    arg_2 = _clientJobsDB().modelsGetUpdateCounters(arg_1)
    arg_3 = tuple(x[0] for x in arg_2)

    return arg_3

Queuries DB for model IDs of all currently instantiated models associated with this HyperSearch job .


def Func(arg_0, arg_1='calc', arg_2=50, **arg_3):
    """
    Attempts to add missing particles to the state.

    Operates by:
    (1) featuring the difference image using feature_guess,
    (2) attempting to add the featured positions using check_add_particles.

    Parameters
    ----------
    st : :class:`peri.states.State`
        The state to check adding particles to.
    rad : Float or 'calc', optional
        The radius of the newly-added particles and of the feature size for
        featuring. Default is 'calc', which uses the median of the state's
        current radii.
    tries : Int, optional
        How many particles to attempt to add. Only tries to add the first
        ``tries`` particles, in order of mass. Default is 50.

    Other Parameters
    ----------------
    invert : Bool, optional
        Whether to invert the image. Default is ``True``, i.e. dark particles
    minmass : Float or None, optionals
        The minimum mass/masscut of a particle. Default is ``None``=calcualted
        by ``feature_guess``.
    use_tp : Bool, optional
        Whether to use trackpy in feature_guess. Default is False, since
        trackpy cuts out particles at the edge.

    do_opt : Bool, optional
        Whether to optimize the particle position before checking if it
        should be kept. Default is True (optimizes position).
    im_change_frac : Float, optional
        How good the change in error needs to be relative to the change
        in the difference image. Default is 0.2; i.e. if the error does
        not decrease by 20% of the change in the difference image, do
        not add the particle.

    min_derr : Float or '3sig', optional
        The minimal improvement in error to add a particle. Default
        is ``'3sig' = 3*st.sigma``.

    Returns
    -------
    accepts : Int
        The number of added particles
    new_poses : [N,3] list
        List of the positions of the added particles. If ``do_opt==True``,
        then these positions will differ from the input 'guess'.
    """
    if arg_1 == 'calc':
        arg_1 = guess_add_radii(arg_0)

    arg_4, arg_5 = feature_guess(arg_0, arg_1, **arg_3)
    arg_2 = np.min([arg_2, arg_5])

    arg_6, arg_7 = check_add_particles(
        arg_0, arg_4[:arg_2], arg_1=arg_1, **arg_3)
    return arg_6, arg_7

Attempts to add missing particles to the state .


def
Func
(
arg_0
,
arg_1
=
)
:
if
arg_1
is
not
:
arg_2
=
time
(
)
+
arg_1
arg_3
=
currentThread
(
)
arg_0
.
__condition
.
acquire
(
)
try
:
if
arg_0
.
__writer
is
arg_3
:
arg_0
.
__writercount
+=
1
return
while
True
:
if
arg_0
.
__writer
is
:
if
arg_0
.
__upgradewritercount
or
arg_0
.
__pendingwriters
:
if
arg_3
in
arg_0
.
__readers
:
arg_0
.
__readers
[
arg_3
]
+=
1
return
else
:
arg_0
.
__readers
[
arg_3
]
=
arg_0
.
__readers
.
get
(
arg_3
,
0
)
+
1
return
if
arg_1
is
not
:
arg_5
=
arg_2
time
(
)
if
arg_5
<=
0
:
raise
RuntimeError
(
"Acquiring read lock timed out"
)
arg_0
.
__condition
.
wait
(
arg_5
)
else
:
arg_0
.
__condition
.
wait
(
)
finally
:
arg_0
.
__condition
.
release
(
)

def Func(arg_0, arg_1=None):
        """Acquire a read lock for the current thread, waiting at most
        timeout seconds or doing a non-blocking check in case timeout is <= 0.

        In case timeout is None, the call to Func blocks until the
        lock request can be serviced.

        In case the timeout expires before the lock could be serviced, a
        RuntimeError is thrown."""

        if arg_1 is not None:
            arg_2 = time() + arg_1
        arg_3 = currentThread()
        arg_0.__condition.acquire()
        try:
            if arg_0.__writer is arg_3:
                # If we are the writer, grant a new read lock, always.
                arg_0.__writercount += 1
                return
            while True:
                if arg_0.__writer is None:
                    # Only test anything if there is no current writer.
                    if arg_0.__upgradewritercount or arg_0.__pendingwriters:
                        if arg_3 in arg_0.__readers:
                            # Only grant a read lock if we already have one
                            # in case writers are waiting for their turn.
                            # This means that writers can't easily get starved
                            # (but see below, readers can).
                            arg_0.__readers[arg_3] += 1
                            return
                        # No, we aren't a reader (yet), wait for our turn.
                    else:
                        # Grant a new read lock, always, in case there are
                        # no pending writers (and no writer).
                        arg_0.__readers[arg_3] = arg_0.__readers.get(arg_3, 0) + 1
                        return
                if arg_1 is not None:
                    arg_5 = arg_2 - time()
                    if arg_5 <= 0:
                        # Timeout has expired, signal caller of this.
                        raise RuntimeError("Acquiring read lock timed out")
                    arg_0.__condition.wait(arg_5)
                else:
                    arg_0.__condition.wait()
        finally:
            arg_0.__condition.release()

Acquire a read lock for the current thread, waiting at most
        timeout seconds or doing a non-blocking check in case timeout is <= 0.

        In case timeout is None, the call to acquire_read blocks until the
        lock request can be serviced.

        In case the timeout expires before the lock could be serviced, a
        RuntimeError is thrown.

Acquire a read lock for the current thread waiting at most timeout seconds or doing a non - blocking check in case timeout is < = 0 .