(selected_file, selected_host, only_link, file_name)

def
Func
(
arg_0
,
arg_1
,
arg_2
,
arg_3
)
:
try
:
arg_4
=
requests
.
post
(
url
=
arg_1
[
0
]
+
"upload.php"
,
files
=
{
'files[]'
:
arg_0
}
)
arg_5
=
re
.
findall
(
r'"url": *"((h.+\/){0,1}(.+?))"[,\}]'
,
arg_4
.
text
.
replace
(
"\\"
,
""
)
)
[
0
]
[
2
]
if
arg_2
:
return
[
arg_1
[
1
]
+
arg_5
,
"{}: {}{}"
.
format
(
arg_3
,
arg_1
[
1
]
,
arg_5
)
]
else
:
return
"{}: {}{}"
.
format
(
arg_3
,
arg_1
[
1
]
,
arg_5
)
except
requests
.
exceptions
.
ConnectionError
:
print
(
arg_3
+
' couldn\'t be uploaded to '
+
arg_1
[
0
]
)

def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Uploads selected file to the host, thanks to the fact that
    every pomf.se based site has pretty much the same architecture.
    """
    try:
        arg_4 = requests.post(
            url=arg_1[0]+"upload.php",
            files={'files[]':arg_0})
        arg_5 = re.findall(r'"url": *"((h.+\/){0,1}(.+?))"[,\}]', \
            arg_4.text.replace("\\", ""))[0][2]
        if arg_2:
            return [arg_1[1]+arg_5, "{}: {}{}".format(arg_3, arg_1[1], arg_5)]
        else:
            return "{}: {}{}".format(arg_3, arg_1[1], arg_5)
    except requests.exceptions.ConnectionError:
        print(arg_3 + ' couldn\'t be uploaded to ' + arg_1[0])

Uploads selected file to the host thanks to the fact that every pomf . se based site has pretty much the same architecture .


def Func ( arg_0 , arg_1 = None , arg_2 = None ) : return arg_0 . deepFunc ( arg_1 = arg_1 , arg_2 = arg_2 )

def Func(arg_0, arg_1=None, arg_2=None):
        """
        Create a shallow Func of the Keypoint object.

        Parameters
        ----------
        x : None or number, optional
            Coordinate of the keypoint on the x axis.
            If ``None``, the instance's value will be copied.

        y : None or number, optional
            Coordinate of the keypoint on the y axis.
            If ``None``, the instance's value will be copied.

        Returns
        -------
        imgaug.Keypoint
            Shallow Func.

        """
        return arg_0.deepFunc(arg_1=arg_1, arg_2=arg_2)

Create a shallow copy of the Keypoint object.

        Parameters
        ----------
        x : None or number, optional
            Coordinate of the keypoint on the x axis.
            If ``None``, the instance's value will be copied.

        y : None or number, optional
            Coordinate of the keypoint on the y axis.
            If ``None``, the instance's value will be copied.

        Returns
        -------
        imgaug.Keypoint
            Shallow copy.

Create a shallow copy of the Keypoint object .


def
Func
(
arg_0
)
:
try
:
arg_1
=
arg_0
.
__consume
(
)
except
DXParserNoTokens
:
return
if
arg_1
.
equals
(
'counts'
)
:
arg_2
=
[
]
try
:
while
True
:
arg_0
.
__peek
(
)
.
value
(
'INTEGER'
)
arg_1
=
arg_0
.
__consume
(
)
arg_2
.
append
(
arg_1
.
value
(
'INTEGER'
)
)
except
(
DXParserNoTokens
,
ValueError
)
:
pass
if
len
(
arg_2
)
==
0
:
raise
DXParseError
(
'gridconnections: no shape parameters'
)
arg_0
.
currentobject
[
'shape'
]
=
arg_2
else
:
raise
DXParseError
(
'gridconnections: '
+
str
(
arg_1
)
+
' not recognized.'
)

def Func(arg_0):
        """Level-2 parser for gridconnections.

        pattern:
        object 2 class gridconnections counts 97 93 99
        """
        try:
            arg_1 = arg_0.__consume()
        except DXParserNoTokens:
            return

        if arg_1.equals('counts'):
            arg_2 = []
            try:
                while True:
                    # raises exception if not an int
                    arg_0.__peek().value('INTEGER')
                    arg_1 = arg_0.__consume()
                    arg_2.append(arg_1.value('INTEGER'))
            except (DXParserNoTokens, ValueError):
                pass
            if len(arg_2) == 0:
                raise DXParseError('gridconnections: no shape parameters')
            arg_0.currentobject['shape'] = arg_2
        else:
            raise DXParseError('gridconnections: '+str(arg_1)+' not recognized.')


def Func ( arg_0 , arg_1 ) : arg_2 = "/{t}/{u}/collections/{c}/items" . format ( u = arg_0 . library_id , t = arg_0 . library_type , c = arg_1 . upper ( ) ) return arg_0 . _totals ( arg_2 )

def Func(arg_0, arg_1):
        """ Return the total number of items in the specified collection
        """
        arg_2 = "/{t}/{u}/collections/{c}/items".format(
            u=arg_0.library_id, t=arg_0.library_type, c=arg_1.upper()
        )
        return arg_0._totals(arg_2)


return render(request, 'lockdown/form.html', page_data)

def
Func
(
arg_0
,
arg_1
)
:
try
:
arg_2
=
arg_1
.
session
except
AttributeError
:
raise
ImproperlyConfigured
(
'django-lockdown requires the Django '
'sessions framework'
)
if
settings
.
ENABLED
is
False
:
return
if
arg_0
.
remote_addr_exceptions
:
arg_3
=
arg_0
.
remote_addr_exceptions
else
:
arg_3
=
settings
.
REMOTE_ADDR_EXCEPTIONS
if
arg_3
:
arg_4
=
arg_0
.
trusted_proxies
or
settings
.
TRUSTED_PROXIES
arg_5
=
arg_1
.
META
.
get
(
'REMOTE_ADDR'
)
if
arg_5
in
arg_3
:
return
if
arg_5
in
arg_4
:
arg_6
=
arg_1
.
META
.
get
(
'HTTP_X_FORWARDED_FOR'
)
if
arg_6
:
arg_5
=
arg_6
.
split
(
','
)
[
1
]
.
strip
(
)
if
arg_5
in
arg_3
:
return
if
arg_0
.
url_exceptions
:
arg_7
=
compile_url_exceptions
(
arg_0
.
url_exceptions
)
else
:
arg_7
=
compile_url_exceptions
(
settings
.
URL_EXCEPTIONS
)
for
arg_8
in
arg_7
:
if
arg_8
.
search
(
arg_1
.
path
)
:
return
try
:
arg_9
=
resolve
(
arg_1
.
path
)
except
Resolver404
:
pass
else
:
if
arg_9
.
func
in
settings
.
VIEW_EXCEPTIONS
:
return
if
arg_0
.
until_date
:
arg_10
=
arg_0
.
until_date
else
:
arg_10
=
settings
.
UNTIL_DATE
if
arg_0
.
after_date
:
arg_11
=
arg_0
.
after_date
else
:
arg_11
=
settings
.
AFTER_DATE
if
arg_10
or
arg_11
:
arg_12
=
False
if
arg_10
and
datetime
.
datetime
.
now
(
)
<
arg_10
:
arg_12
=
True
if
arg_11
and
datetime
.
datetime
.
now
(
)
>
arg_11
:
arg_12
=
True
if
not
arg_12
:
return
arg_13
=
arg_1
.
POST
if
arg_1
.
method
==
'POST'
else
if
arg_0
.
form
:
arg_14
=
arg_0
.
form
else
:
arg_14
=
get_lockdown_form
(
settings
.
FORM
)
arg_15
=
arg_14
(
data
=
arg_13
,
**
arg_0
.
form_kwargs
)
arg_16
=
False
arg_17
=
arg_2
.
get
(
arg_0
.
session_key
)
if
hasattr
(
arg_15
,
'authenticate'
)
:
if
arg_15
.
authenticate
(
arg_17
)
:
arg_16
=
True
elif
arg_17
is
True
:
arg_16
=
True
if
arg_16
and
arg_0
.
logout_key
and
arg_0
.
logout_key
in
arg_1
.
GET
:
if
arg_0
.
session_key
in
arg_2
:
del
arg_2
[
arg_0
.
session_key
]
arg_18
=
arg_1
.
GET
.
copy
(
)
del
arg_18
[
arg_0
.
logout_key
]
return
arg_0
.
redirect
(
arg_1
)
if
arg_16
:
return
if
arg_15
.
is_valid
(
)
:
if
hasattr
(
arg_15
,
'generate_token'
)
:
arg_17
=
arg_15
.
generate_token
(
)
else
:
arg_17
=
True
arg_2
[
arg_0
.
session_key
]
=
arg_17
return
arg_0
.
redirect
(
arg_1
)
arg_20
=
{
'until_date'
:
arg_10
,
'after_date'
:
arg_11
}
if
not
hasattr
(
arg_15
,
'show_form'
)
or
arg_15
.
show_form
(
)
:
arg_20
[
'form'
]
=
arg_15
if
arg_0
.
extra_context
:
arg_20
.
update
(
arg_0
.
extra_context
)
return
render
(
arg_1
,
'lockdown/form.html'
,
arg_20
)

def Func(arg_0, arg_1):
        """Check if each request is allowed to access the current resource."""
        try:
            arg_2 = arg_1.session
        except AttributeError:
            raise ImproperlyConfigured('django-lockdown requires the Django '
                                       'sessions framework')

        # Don't lock down if django-lockdown is disabled altogether.
        if settings.ENABLED is False:
            return None

        # Don't lock down if the client REMOTE_ADDR matched and is part of the
        # exception list.
        if arg_0.remote_addr_exceptions:
            arg_3 = arg_0.remote_addr_exceptions
        else:
            arg_3 = settings.REMOTE_ADDR_EXCEPTIONS

        if arg_3:
            # If forwarding proxies are used they must be listed as trusted
            arg_4 = arg_0.trusted_proxies or settings.TRUSTED_PROXIES

            arg_5 = arg_1.META.get('REMOTE_ADDR')
            if arg_5 in arg_3:
                return None
            if arg_5 in arg_4:
                # If REMOTE_ADDR is a trusted proxy check x-forwarded-for
                arg_6 = arg_1.META.get('HTTP_X_FORWARDED_FOR')
                if arg_6:
                    arg_5 = arg_6.split(',')[-1].strip()
                    if arg_5 in arg_3:
                        return None

        # Don't lock down if the URL matches an exception pattern.
        if arg_0.url_exceptions:
            arg_7 = compile_url_exceptions(arg_0.url_exceptions)
        else:
            arg_7 = compile_url_exceptions(settings.URL_EXCEPTIONS)
        for arg_8 in arg_7:
            if arg_8.search(arg_1.path):
                return None

        # Don't lock down if the URL resolves to a whitelisted view.
        try:
            arg_9 = resolve(arg_1.path)
        except Resolver404:
            pass
        else:
            if arg_9.func in settings.VIEW_EXCEPTIONS:
                return None

        # Don't lock down if outside of the lockdown dates.
        if arg_0.until_date:
            arg_10 = arg_0.until_date
        else:
            arg_10 = settings.UNTIL_DATE

        if arg_0.after_date:
            arg_11 = arg_0.after_date
        else:
            arg_11 = settings.AFTER_DATE

        if arg_10 or arg_11:
            arg_12 = False
            if arg_10 and datetime.datetime.now() < arg_10:
                arg_12 = True
            if arg_11 and datetime.datetime.now() > arg_11:
                arg_12 = True
            if not arg_12:
                return None

        arg_13 = arg_1.POST if arg_1.method == 'POST' else None
        if arg_0.form:
            arg_14 = arg_0.form
        else:
            arg_14 = get_lockdown_form(settings.FORM)
        arg_15 = arg_14(data=arg_13, **arg_0.form_kwargs)

        arg_16 = False
        arg_17 = arg_2.get(arg_0.session_key)
        if hasattr(arg_15, 'authenticate'):
            if arg_15.authenticate(arg_17):
                arg_16 = True
        elif arg_17 is True:
            arg_16 = True

        if arg_16 and arg_0.logout_key and arg_0.logout_key in arg_1.GET:
            if arg_0.session_key in arg_2:
                del arg_2[arg_0.session_key]
            arg_18 = arg_1.GET.copy()
            del arg_18[arg_0.logout_key]
            return arg_0.redirect(arg_1)

        # Don't lock down if the user is already authorized for previewing.
        if arg_16:
            return None

        if arg_15.is_valid():
            if hasattr(arg_15, 'generate_token'):
                arg_17 = arg_15.generate_token()
            else:
                arg_17 = True
            arg_2[arg_0.session_key] = arg_17
            return arg_0.redirect(arg_1)

        arg_20 = {'until_date': arg_10, 'after_date': arg_11}
        if not hasattr(arg_15, 'show_form') or arg_15.show_form():
            arg_20['form'] = arg_15

        if arg_0.extra_context:
            arg_20.update(arg_0.extra_context)

        return render(arg_1, 'lockdown/form.html', arg_20)

Check if each request is allowed to access the current resource .


def Func(arg_0, arg_1):
    """ Retrieve the requested property and return it as a bool. If property
    does not exist, then KeyError will be raised. If the property value is
    neither 0 nor 1, then ValueError will be raised

    :param prop: (string) name of the property
    :raises: KeyError, ValueError
    :returns: (bool) property value
    """

    arg_2 = arg_0.getInt(arg_1)

    if arg_2 not in (0, 1):
      raise ValueError("Expected 0 or 1, but got %r in config property %s" % (
        arg_2, arg_1))

    return bool(arg_2)

Retrieve the requested property and return it as a bool . If property does not exist then KeyError will be raised . If the property value is neither 0 nor 1 then ValueError will be raised


(self, y, x, ildj, event_ndims,
                                     **distribution_kwargs)

def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
                                     **arg_5):
    """Finish computation of log_prob on one element of the inverse image."""
    arg_2 = arg_0._maybe_rotate_dims(arg_2, rotate_right=True)
    arg_6 = arg_0.distribution.log_prob(arg_2, **arg_5)
    if arg_0._is_maybe_event_override:
      arg_6 = tf.reduce_sum(
          input_tensor=arg_6, axis=arg_0._reduce_event_indices)
    arg_6 += tf.cast(arg_3, arg_6.dtype)
    if arg_0._is_maybe_event_override and isinstance(arg_4, int):
      tensorshape_util.set_shape(
          arg_6,
          tf.broadcast_static_shape(
              tensorshape_util.with_rank_at_least(arg_1.shape, 1)[:-arg_4],
              arg_0.batch_shape))
    return arg_6

Finish computation of log_prob on one element of the inverse image .


def Func ( arg_0 , arg_1 = None ) : arg_2 = arg_1 arg_3 , arg_4 = arg_0 . command ( "XGTITLE" , arg_2 ) if arg_3 != 282 : raise NNTPReplyError ( arg_3 , arg_4 ) return arg_0 . info ( arg_3 , arg_4 )

def Func(arg_0, arg_1=None):
        """XGTITLE command.
        """
        arg_2 = arg_1

        arg_3, arg_4 = arg_0.command("XGTITLE", arg_2)
        if arg_3 != 282:
            raise NNTPReplyError(arg_3, arg_4)

        return arg_0.info(arg_3, arg_4)


def Func(arg_0, arg_1, arg_2):
  """
  Returns an array of length size and type dtype that is everywhere 0,
  except in the indices listed in sequence pos.

  :param pos:   A single integer or sequence of integers that specify
         the position of ones to be set.
  :param size:  The total size of the array to be returned.
  :param dtype: The element type (compatible with NumPy array())
         of the array to be returned.
  :returns: An array of length size and element type dtype.
  """
  arg_3 = numpy.zeros(arg_1, arg_2=arg_2)
  if hasattr(arg_0, '__iter__'):
    for arg_4 in arg_0: arg_3[arg_4] = 1
  else: arg_3[arg_0] = 1
  return arg_3

Returns an array of length size and type dtype that is everywhere 0 except in the indices listed in sequence pos .


(name,
                  filename=None,
                  logging_level=logging.DEBUG)

def
Func
(
arg_0
,
arg_1
=
,
arg_2
=
arg_3
.
DEBUG
)
:
arg_5
=
arg_3
.
getLogger
(
arg_0
)
arg_6
=
arg_3
.
Formatter
(
(
'%(asctime)s - %(name)s - '
'%(levelname)-8s - %(message)s'
)
)
if
arg_1
:
arg_7
=
arg_3
.
FileHandler
(
arg_1
=
arg_1
)
arg_7
.
setFormatter
(
arg_6
)
arg_5
.
addHandler
(
arg_7
)
arg_8
=
arg_3
.
StreamHandler
(
)
arg_8
.
setFormatter
(
arg_6
)
arg_5
.
addHandler
(
arg_8
)
arg_5
.
setLevel
(
arg_2
)
return
arg_5

def Func(arg_0,
                  arg_1=None,
                  arg_2=arg_3.DEBUG):
    """Create a logger object."""
    arg_5 = arg_3.getLogger(arg_0)
    arg_6 = arg_3.Formatter(('%(asctime)s - %(name)s - '
                                   '%(levelname)-8s - %(message)s'))

    if arg_1:
        arg_7 = arg_3.FileHandler(arg_1=arg_1)
        arg_7.setFormatter(arg_6)
        arg_5.addHandler(arg_7)

    arg_8 = arg_3.StreamHandler()
    arg_8.setFormatter(arg_6)
    arg_5.addHandler(arg_8)

    arg_5.setLevel(arg_2)

    return arg_5


def Func(arg_0) -> None:
        """Conducts cleanup of periodical certificates with expired validation."""
        arg_0.timer = Timer(REFRESH_VALID_CERTS_PERIOD_SECS, arg_0.Func)
        arg_0.timer.start()

        arg_2 = []

        for arg_3, arg_4 in arg_0.valid_certificates.items():
            arg_4: ValidatedCert = arg_4
            arg_5: datetime = arg_4.expiration_timestamp
            if datetime.utcnow() > arg_5:
                arg_2.append(arg_3)

        for arg_6 in arg_2:
            del arg_0.valid_certificates[arg_6]
            log.info(f'Validation period of {expired_cert_url} certificate expired')

Conducts cleanup of periodical certificates with expired validation .


(self, name, collection_id, tag="latest", version=None)

def Func ( arg_0 , arg_1 , arg_2 , arg_3 = "latest" , arg_4 = None ) : from sregistry . database . models import Container if arg_4 is None : arg_5 = Container . query . filter_by ( arg_2 = arg_2 , arg_1 = arg_1 , arg_3 = arg_3 ) . first ( ) else : arg_5 = Container . query . filter_by ( arg_2 = arg_2 , arg_1 = arg_1 , arg_3 = arg_3 , arg_4 = arg_4 ) . first ( ) return arg_5

def Func(arg_0, arg_1, arg_2, arg_3="latest", arg_4=None):
    '''get a container, otherwise return None.
    '''
    from sregistry.database.models import Container
    if arg_4 is None:
        arg_5 = Container.query.filter_by(arg_2 = arg_2,
                                              arg_1 = arg_1,
                                              arg_3 = arg_3).first()
    else:
        arg_5 = Container.query.filter_by(arg_2 = arg_2,
                                              arg_1 = arg_1,
                                              arg_3 = arg_3,
                                              arg_4 = arg_4).first()
    return arg_5


def
Func
(
arg_0
,
arg_1
)
:
if
not
PIL_ENABLED
:
return
arg_2
=
os
.
path
.
join
(
arg_0
,
arg_1
)
arg_3
=
try
:
arg_3
=
Image
.
open
(
arg_2
)
except
IOError
as
exptn
:
print
(
'Error loading image file %s: %s'
%
(
arg_2
,
exptn
)
)
return
arg_3

def Func(arg_0, arg_1):
    """
    Get an instance of PIL.Image from the given file.
    @param {String} dir_path - The directory containing the image file
    @param {String} image_file - The filename of the image file within dir_path
    @return {PIL.Image} An instance of the image file as a PIL Image, or None
        if the functionality is not available. This could be because PIL is not
        present, or because it can't process the given file type.
    """
    # Save ourselves the effort if PIL is not present, and return None now
    if not PIL_ENABLED:
        return None
    # Put together full path
    arg_2 = os.path.join(arg_0, arg_1)
    # Try to read the image
    arg_3 = None
    try:
        arg_3 = Image.open(arg_2)
    except IOError as exptn:
        print('Error loading image file %s: %s' % (arg_2, exptn))
    # Return image or None
    return arg_3

Get an instance of PIL . Image from the given file .


def Func ( arg_0 , arg_1 ) : if isinstance ( arg_1 . parent , astroid . If ) : arg_2 = arg_1 . parent . orelse if arg_2 and arg_2 == [ arg_1 ] : if ( arg_1 . lineno , arg_1 . col_offset ) in arg_0 . _elifs : return True return False

def Func(arg_0, arg_1):
        """Check if the given node is an actual elif

        This is a problem we're having with the builtin ast module,
        which splits `elif` branches into a separate if statement.
        Unfortunately we need to know the exact type in certain
        cases.
        """
        if isinstance(arg_1.parent, astroid.If):
            arg_2 = arg_1.parent.orelse
            # current if node must directly follow an "else"
            if arg_2 and arg_2 == [arg_1]:
                if (arg_1.lineno, arg_1.col_offset) in arg_0._elifs:
                    return True
        return False


def
Func
(
arg_0
,
arg_1
)
:
assert
arg_0
.
options
for
arg_2
in
arg_0
.
options
:
if
arg_2
[
0
]
==
arg_1
:
return
arg_2
[
1
]
raise
optparse
.
OptionError
(
"no such option %s in section %r"
%
(
arg_1
,
arg_0
.
name
)
,
arg_1
)

def Func(arg_0, arg_1):
        """return the dictionary defining an option given its name"""
        assert arg_0.options
        for arg_2 in arg_0.options:
            if arg_2[0] == arg_1:
                return arg_2[1]
        raise optparse.OptionError(
            "no such option %s in section %r" % (arg_1, arg_0.name), arg_1
        )


def Func ( arg_0 , arg_1 , ** arg_2 ) : return ( ( ( arg_0 - arg_1 ) / ( arg_0 + arg_1 ) ) ** 2 ) if arg_0 + arg_1 != 0 else 0

def Func(arg_0, arg_1, **arg_2):
    """Metric for ratio data."""
    return (((arg_0 - arg_1) / (arg_0 + arg_1)) ** 2) if arg_0 + arg_1 != 0 else 0


def
Func
(
arg_0
,
arg_1
=
100
)
:
arg_2
=
0
if
isinstance
(
arg_0
,
str
)
:
arg_0
=
json_iter
(
arg_0
)
for
arg_3
in
arg_0
:
if
not
isinstance
(
arg_3
,
SummarySent
)
:
arg_4
=
SummarySent
(
**
arg_3
)
else
:
arg_4
=
arg_3
arg_5
=
arg_4
.
text
.
strip
(
)
.
split
(
" "
)
arg_6
=
len
(
arg_5
)
if
(
arg_2
+
arg_6
)
>
arg_1
:
break
else
:
arg_2
+=
arg_6
yield
arg_5
,
arg_4
.
idx

def Func (arg_0, arg_1=100):
    """
    iterator for the most significant sentences, up to a specified limit
    """
    arg_2 = 0

    if isinstance(arg_0, str):
        arg_0 = json_iter(arg_0)

    for arg_3 in arg_0:
        if not isinstance(arg_3, SummarySent):
            arg_4 = SummarySent(**arg_3)
        else:
            arg_4 = arg_3

        arg_5 = arg_4.text.strip().split(" ")
        arg_6 = len(arg_5)

        if (arg_2 + arg_6) > arg_1:
            break
        else:
            arg_2 += arg_6
            yield arg_5, arg_4.idx

iterator for the most significant sentences up to a specified limit


(
            self, topic_hostname, events, custom_headers=None, raw=False, **operation_config)

def
Func
(
arg_0
,
arg_1
,
arg_2
,
arg_3
=
,
arg_4
=
False
,
**
arg_5
)
:
arg_6
=
arg_0
.
Func
.
metadata
[
'url'
]
arg_7
=
{
'topicHostname'
:
arg_0
.
_serialize
.
url
(
"topic_hostname"
,
arg_1
,
'str'
,
skip_quote
=
True
)
}
arg_6
=
arg_0
.
_client
.
format_url
(
arg_6
,
**
arg_7
)
arg_8
=
{
}
arg_8
[
'api-version'
]
=
arg_0
.
_serialize
.
query
(
"self.api_version"
,
arg_0
.
api_version
,
'str'
)
arg_9
=
{
}
arg_9
[
'Content-Type'
]
=
'application/json; charset=utf-8'
if
arg_3
:
arg_9
.
update
(
arg_3
)
arg_10
=
arg_0
.
_serialize
.
body
(
arg_2
,
'[EventGridEvent]'
)
arg_11
=
arg_0
.
_client
.
post
(
arg_6
,
arg_8
)
arg_12
=
arg_0
.
_client
.
send
(
arg_11
,
arg_9
,
arg_10
,
stream
=
False
,
**
arg_5
)
if
arg_12
.
status_code
not
in
[
200
]
:
raise
HttpOperationError
(
arg_0
.
_deserialize
,
arg_12
)
if
arg_4
:
arg_13
=
ClientRawResponse
(
,
arg_12
)
return
arg_13

def Func(
            arg_0, arg_1, arg_2, arg_3=None, arg_4=False, **arg_5):
        """Publishes a batch of events to an Azure Event Grid topic.

        :param topic_hostname: The host name of the topic, e.g.
         topic1.westus2-1.eventgrid.azure.net
        :type topic_hostname: str
        :param events: An array of events to be published to Event Grid.
        :type events: list[~azure.eventgrid.models.EventGridEvent]
        :param dict custom_headers: headers that will be added to the request
        :param bool raw: returns the direct response alongside the
         deserialized response
        :param operation_config: :ref:`Operation configuration
         overrides<msrest:optionsforoperations>`.
        :return: None or ClientRawResponse if raw=true
        :rtype: None or ~msrest.pipeline.ClientRawResponse
        :raises:
         :class:`HttpOperationError<msrest.exceptions.HttpOperationError>`
        """
        # Construct URL
        arg_6 = arg_0.Func.metadata['url']
        arg_7 = {
            'topicHostname': arg_0._serialize.url("topic_hostname", arg_1, 'str', skip_quote=True)
        }
        arg_6 = arg_0._client.format_url(arg_6, **arg_7)

        # Construct parameters
        arg_8 = {}
        arg_8['api-version'] = arg_0._serialize.query("self.api_version", arg_0.api_version, 'str')

        # Construct headers
        arg_9 = {}
        arg_9['Content-Type'] = 'application/json; charset=utf-8'
        if arg_3:
            arg_9.update(arg_3)

        # Construct body
        arg_10 = arg_0._serialize.body(arg_2, '[EventGridEvent]')

        # Construct and send request
        arg_11 = arg_0._client.post(arg_6, arg_8)
        arg_12 = arg_0._client.send(
            arg_11, arg_9, arg_10, stream=False, **arg_5)

        if arg_12.status_code not in [200]:
            raise HttpOperationError(arg_0._deserialize, arg_12)

        if arg_4:
            arg_13 = ClientRawResponse(None, arg_12)
            return arg_13

Publishes a batch of events to an Azure Event Grid topic .


def Func ( arg_0 , arg_1 = "{}" , ** arg_2 ) : if isinstance ( arg_1 , basestring ) : arg_3 = arg_1 arg_1 = json . loads ( arg_1 ) else : arg_3 = json . dumps ( arg_1 ) Draft4Validator . check_schema ( arg_1 ) arg_2 [ "schema" ] = arg_3 arg_0 . metadata = arg_0 . db . Func ( arg_0 . path , arg_2 ) . json ( )

def Func(arg_0, arg_1="{}", **arg_2):
        """Creates a stream given an optional JSON schema encoded as a python dict. You can also add other properties
        of the stream, such as the icon, datatype or description. Create accepts both a string schema and
        a dict-encoded schema."""
        if isinstance(arg_1, basestring):
            arg_3 = arg_1
            arg_1 = json.loads(arg_1)
        else:
            arg_3 = json.dumps(arg_1)
        Draft4Validator.check_schema(arg_1)
        arg_2["schema"] = arg_3
        arg_0.metadata = arg_0.db.Func(arg_0.path, arg_2).json()

Creates a stream given an optional JSON schema encoded as a python dict . You can also add other properties of the stream such as the icon datatype or description . Create accepts both a string schema and a dict - encoded schema .


def Func(arg_0):
        """
        Returns a snakebite HDFSClient object.
        """
        # When using HAClient, proxy_user must be the same, so is ok to always
        # take the first.
        arg_1 = arg_0.proxy_user
        arg_2 = arg_0.autoconfig
        arg_3 = configuration.conf.get('core', 'security') == 'kerberos'

        try:
            arg_4 = arg_0.Funcections(arg_0.hdfs_conn_id)

            if not arg_1:
                arg_1 = arg_4[0].login
            if not arg_2:
                arg_2 = arg_4[0].extra_dejson.get('autoconfig',
                                                             False)
            arg_5 = arg_4[0].extra_dejson.get(
                'hdfs_namenode_principal')
        except AirflowException:
            if not arg_2:
                raise

        if arg_2:
            # will read config info from $HADOOP_HOME conf files
            arg_6 = AutoConfigClient(arg_1=arg_1,
                                      arg_3=arg_3)
        elif len(arg_4) == 1:
            arg_6 = Client(arg_4[0].host, arg_4[0].port,
                            arg_1=arg_1, arg_3=arg_3,
                            arg_5=arg_5)
        elif len(arg_4) > 1:
            arg_7 = [Namenode(conn.host, conn.port) for conn in arg_4]
            arg_6 = HAClient(arg_7, arg_1=arg_1,
                              arg_3=arg_3,
                              arg_5=arg_5)
        else:
            raise HDFSHookException("conn_id doesn't exist in the repository "
                                    "and autoconfig is not specified")

        return arg_6


def Func ( arg_0 , arg_1 = 0 ) : if type ( arg_0 [ 0 ] ) is ndarray : return concatenate ( arg_0 , axis = arg_1 ) else : return concatenate ( [ Func ( arg_2 , arg_1 + 1 ) for arg_2 in arg_0 ] , axis = arg_1 )

def Func(arg_0, arg_1=0):
    """
    If an ndarray has been split into multiple chunks by splitting it along
    each axis at a number of locations, this function rebuilds the
    original array from chunks.

    Parameters
    ----------
    vals : nested lists of ndarrays
        each level of nesting of the lists representing a dimension of
        the original array.
    """
    if type(arg_0[0]) is ndarray:
        return concatenate(arg_0, axis=arg_1)
    else:
        return concatenate([Func(arg_2, arg_1+1) for arg_2 in arg_0], axis=arg_1)

If an ndarray has been split into multiple chunks by splitting it along each axis at a number of locations this function rebuilds the original array from chunks .


def
Func
(
arg_0
,
arg_1
)
:
with
open
(
arg_0
)
as
f
:
arg_2
=
re
.
search
(
r"^(\s*%s\s*=\s*')(.+?)(')(?sm)"
%
arg_1
,
f
.
read
(
)
)
if
arg_2
:
arg_3
,
arg_4
,
arg_5
=
arg_2
.
groups
(
)
return
arg_4
fail
(
'Could not find {} in {}'
.
format
(
arg_1
,
arg_0
)
)

def Func(arg_0, arg_1):
    """Gets the current version from the specified file.

    This function assumes the file includes a string of the form::

        <pattern> = <version>

    """
    with open(arg_0) as f:
        arg_2 = re.search(r"^(\s*%s\s*=\s*')(.+?)(')(?sm)" % arg_1, f.read())
    if arg_2:
        arg_3, arg_4, arg_5 = arg_2.groups()
        return arg_4
    fail('Could not find {} in {}'.format(arg_1, arg_0))

Gets the current version from the specified file .


(y, sr, hop_length, res_type, n_octaves,
                       nyquist, filter_cutoff, scale)

def Func(arg_0, arg_1, arg_2, arg_3, arg_4,
                       arg_5, arg_6, arg_7):
    '''Perform early downsampling on an audio signal, if it applies.'''

    arg_8 = Func_count(arg_5, arg_6,
                                                arg_2, arg_4)

    if arg_8 > 0 and arg_3 == 'kaiser_fast':
        arg_9 = 2**(arg_8)

        arg_2 //= arg_9

        if len(arg_0) < arg_9:
            raise ParameterError('Input signal length={:d} is too short for '
                                 '{:d}-octave CQT'.format(len(arg_0), arg_4))

        arg_10 = arg_1 / float(arg_9)
        arg_0 = audio.resample(arg_0, arg_1, arg_10,
                           arg_3=arg_3,
                           arg_7=True)

        # If we're not going to length-scale after CQT, we
        # need to compensate for the downsampling factor here
        if not arg_7:
            arg_0 *= np.sqrt(arg_9)

        arg_1 = arg_10

    return arg_0, arg_1, arg_2

Perform early downsampling on an audio signal if it applies .


def
Func
(
arg_0
,
arg_1
)
:
arg_2
=
arg_1
.
get_from
(
)
arg_3
=
arg_2
.
bare
(
)
.
as_unicode
(
)
arg_4
=
arg_0
.
rooms
.
get
(
arg_3
)
if
not
arg_4
:
arg_0
.
__logger
.
debug
(
"groupchat message from unknown source"
)
return
False
arg_4
.
process_groupchat_message
(
arg_1
)
return
True

def Func(arg_0,arg_1):
        """Process a groupchat message from a MUC room.

        :Parameters:
            - `stanza`: the stanza received.
        :Types:
            - `stanza`: `Message`

        :return: `True` if the message was properly recognized as directed to
            one of the managed rooms, `False` otherwise.
        :returntype: `bool`"""
        arg_2=arg_1.get_from()
        arg_3=arg_2.bare().as_unicode()
        arg_4=arg_0.rooms.get(arg_3)
        if not arg_4:
            arg_0.__logger.debug("groupchat message from unknown source")
            return False
        arg_4.process_groupchat_message(arg_1)
        return True

Process a groupchat message from a MUC room .


Get all facts of this node. Additional arguments may also be
        specified that will be passed to the query function.

return self.__api.facts(query=EqualsOperator("certname", self.name),
                                **kwargs)

def Func ( arg_0 , ** arg_1 ) : return arg_0 . __api . Func ( query = EqualsOperator ( "certname" , arg_0 . name ) , ** arg_1 )

def Func(arg_0, **arg_1):
        """Get all Func of this node. Additional arguments may also be
        specified that will be passed to the query function.
        """
        return arg_0.__api.Func(query=EqualsOperator("certname", arg_0.name),
                                **arg_1)

Get all facts of this node . Additional arguments may also be specified that will be passed to the query function .


def Func ( arg_0 = [ ] , arg_1 = [ ] ) : arg_2 = [ ] for arg_3 in arg_0 : arg_4 = re . compile ( arg_3 ) arg_5 = False for arg_6 in arg_1 : arg_7 = arg_4 . match ( arg_6 ) if arg_7 and arg_7 . end ( ) == len ( arg_6 ) : arg_2 . append ( arg_6 ) arg_5 = True if not arg_5 : raise _BadKeyError ( arg_3 ) return arg_2

def Func(arg_0=[], arg_1=[]):
  """
  Extract all items from the 'allKeys' list whose key matches one of the regular
  expressions passed in 'reportKeys'.

  Parameters:
  ----------------------------------------------------------------------------
  reportKeyREs:     List of regular expressions
  allReportKeys:    List of all keys

  retval:         list of keys from allReportKeys that match the regular expressions
                    in 'reportKeyREs'
                  If an invalid regular expression was included in 'reportKeys',
                    then BadKeyError() is raised
  """

  arg_2 = []

  # Extract the report items of interest
  for arg_3 in arg_0:
    # Find all keys that match this regular expression
    arg_4 = re.compile(arg_3)
    arg_5 = False
    for arg_6 in arg_1:
      arg_7 = arg_4.match(arg_6)
      if arg_7 and arg_7.end() == len(arg_6):
        arg_2.append(arg_6)
        arg_5 = True
    if not arg_5:
      raise _BadKeyError(arg_3)

  return arg_2

Extract all items from the allKeys list whose key matches one of the regular expressions passed in reportKeys .


(self,
                         code=RECORD_LENGTH_CHECK_FAILED,
                         message=MESSAGES[RECORD_LENGTH_CHECK_FAILED],
                         modulus=1)

def Func(arg_0,
                         arg_1=arg_2,
                         arg_3=arg_4[arg_2],
                         arg_5=1):
        """
        Add a record length check, i.e., check whether the length of a record is
        consistent with the number of expected fields.

        Arguments
        ---------

        `code` - problem code to report if a record is not valid, defaults to
        `RECORD_LENGTH_CHECK_FAILED`

        `message` - problem message to report if a record is not valid

        `modulus` - apply the check to every nth record, defaults to 1 (check
        every record)

        """

        arg_6 = arg_1, arg_3, arg_5
        arg_0._record_length_checks.append(arg_6)

Add a record length check i . e . check whether the length of a record is consistent with the number of expected fields .


return render_template(
        template,
        pid=pid,
        record=record,
        jsonschema=current_deposit.jsonschemas[deposit_type],
        schemaform=current_deposit.schemaforms[deposit_type],
    )

def Func ( arg_0 , arg_1 , arg_2 = None ) : record_viewed . send ( current_app . _get_current_object ( ) , arg_0 = arg_0 , arg_1 = arg_1 , ) arg_3 = request . values . get ( 'type' ) return render_template ( arg_2 , arg_0 = arg_0 , arg_1 = arg_1 , jsonschema = current_deposit . jsonschemas [ arg_3 ] , schemaform = current_deposit . schemaforms [ arg_3 ] , )

def Func(arg_0, arg_1, arg_2=None):
    """Default view method.

    Sends ``record_viewed`` signal and renders template.
    """
    record_viewed.send(
        current_app._get_current_object(),
        arg_0=arg_0,
        arg_1=arg_1,
    )

    arg_3 = request.values.get('type')

    return render_template(
        arg_2,
        arg_0=arg_0,
        arg_1=arg_1,
        jsonschema=current_deposit.jsonschemas[arg_3],
        schemaform=current_deposit.schemaforms[arg_3],
    )


def Func(arg_0):
  """Loads the experiment description file from the path.

  :param path: (string) The path to a directory containing a description.py file
         or the file itself.
  :returns: (config, control)
  """
  if not os.path.isdir(arg_0):
    arg_0 = os.path.dirname(arg_0)
  arg_1 = FuncDescriptionScriptFromDir(arg_0)
  arg_2 = getExperimentDescriptionInterfaceFromModule(arg_1)
  return arg_2.getModelDescription(), arg_2.getModelControl()

Loads the experiment description file from the path .


def Func ( arg_0 , arg_1 ) : xmltodict . unparse ( arg_0 . object ( ) , arg_1 , pretty = True )

def Func(arg_0, arg_1):
        """dump to the file"""
        xmltodict.unparse(arg_0.object(), arg_1, pretty=True)


Print help; same as using ``?`` in ``ipython``. long=True also gives call signature.

def
Func
(
arg_0
,
arg_1
=
False
)
:
print
(
"\ncommand: {0!s}\n\n"
.
format
(
arg_0
.
command_name
)
)
print
(
arg_0
.
__doc__
)
if
arg_1
:
print
(
"\ncall method: command():\n"
)
print
(
arg_0
.
__call__
.
__doc__
)

def Func(arg_0, arg_1=False):
        """Print Func; same as using ``?`` in ``ipython``. long=True also gives call signature."""
        print("\ncommand: {0!s}\n\n".format(arg_0.command_name))
        print(arg_0.__doc__)
        if arg_1:
            print("\ncall method: command():\n")
            print(arg_0.__call__.__doc__)

Print help ; same as using ? in ipython . long = True also gives call signature .


(self, f_start=None, f_stop=None, if_id=0, logged=True, orientation='h', MJD_time=False, **kwargs)

def
Func
(
arg_0
,
arg_1
=
,
arg_2
=
,
arg_3
=
0
,
arg_4
=
True
,
arg_5
=
'h'
,
arg_6
=
False
,
**
arg_7
)
:
arg_8
=
plt
.
gca
(
)
arg_9
,
arg_10
=
arg_0
.
grab_data
(
arg_1
,
arg_2
,
arg_3
)
if
arg_4
and
arg_0
.
header
[
b'nbits'
]
>=
8
:
arg_10
=
db
(
arg_10
)
if
len
(
arg_10
.
shape
)
>
1
:
arg_10
=
arg_10
.
mean
(
axis
=
1
)
else
:
arg_10
=
arg_10
.
mean
(
)
arg_11
=
arg_0
.
_calc_extent
(
arg_9
=
arg_9
,
arg_12
=
arg_0
.
timestamps
,
arg_6
=
arg_6
)
arg_12
=
np
.
linspace
(
arg_11
[
2
]
,
arg_11
[
3
]
,
len
(
arg_0
.
timestamps
)
)
if
arg_6
:
arg_13
=
"Time [MJD]"
else
:
arg_13
=
"Time [s]"
if
arg_4
:
arg_14
=
"Power [dB]"
else
:
arg_14
=
"Power [counts]"
if
'v'
in
arg_5
:
plt
.
plot
(
arg_10
,
arg_12
,
**
arg_7
)
plt
.
xlabel
(
arg_14
)
else
:
plt
.
plot
(
arg_12
,
arg_10
,
**
arg_7
)
plt
.
xlabel
(
arg_13
)
plt
.
ylabel
(
arg_14
)
arg_8
.
autoscale
(
axis
=
'both'
,
tight
=
True
)

def Func(arg_0, arg_1=None, arg_2=None, arg_3=0, arg_4=True, arg_5='h', arg_6=False, **arg_7):
        """ Plot the time series.

         Args:
            f_start (float): start frequency, in MHz
            f_stop (float): stop frequency, in MHz
            logged (bool): Plot in linear (False) or dB units (True),
            kwargs: keyword args to be passed to matplotlib imshow()
        """

        arg_8 = plt.gca()
        arg_9, arg_10 = arg_0.grab_data(arg_1, arg_2, arg_3)

        if arg_4 and arg_0.header[b'nbits'] >= 8:
            arg_10 = db(arg_10)

        #Since the data has been squeezed, the axis for time goes away if only one bin, causing a bug with axis=1
        if len(arg_10.shape) > 1:
            arg_10 = arg_10.mean(axis=1)
        else:
            arg_10 = arg_10.mean()

        #Make proper time axis for plotting (but only for plotting!). Note that this makes the values inclusive.
        arg_11 = arg_0._calc_extent(arg_9=arg_9,arg_12=arg_0.timestamps,arg_6=arg_6)
        arg_12 = np.linspace(arg_11[2],arg_11[3],len(arg_0.timestamps))

        if arg_6:
            arg_13 = "Time [MJD]"
        else:
            arg_13 = "Time [s]"

        if arg_4:
            arg_14 = "Power [dB]"
        else:
            arg_14 = "Power [counts]"

        # Reverse oder if vertical orientation.
        if 'v' in arg_5:
            plt.plot(arg_10, arg_12, **arg_7)
            plt.xlabel(arg_14)

        else:
            plt.plot(arg_12, arg_10, **arg_7)
            plt.xlabel(arg_13)
            plt.ylabel(arg_14)

        arg_8.autoscale(axis='both',tight=True)


def Func ( arg_0 , arg_1 ) : with open ( arg_0 . path_to ( str ( arg_1 ) ) ) as f : arg_2 = f . Func ( ) return arg_2

def Func(arg_0, arg_1):
        """
        Read a file from the directory.
        """
        with open(arg_0.path_to(str(arg_1))) as f:
            arg_2 = f.Func()
        return arg_2


def Func(arg_0, arg_1=0.05):
    """ benjamini hocheberg fdr correction. inspired by statsmodels
    """
    # Implement copy from GOATools.
    arg_0 = np.asarray(arg_0)
    arg_2 = np.argsort(arg_0)
    arg_3 = np.take(arg_0, arg_2)

    arg_4 = _ecdf(arg_3)
    arg_5 = arg_3 <= arg_4*arg_1
    if arg_5.any():
        arg_6 = max(np.nonzero(arg_5)[0])
        arg_5[:arg_6] = True
    arg_7 = arg_3 / arg_4
    arg_8 = np.minimum.accumulate(arg_7[::-1])[::-1]
    del arg_7
    arg_8[arg_8>1] = 1
    arg_9 = np.empty_like(arg_8)
    arg_9[arg_2] = arg_8
    del arg_8
    arg_10 = np.empty_like(arg_5)
    arg_10[arg_2] = arg_5
    return arg_10, arg_9

benjamini hocheberg fdr correction . inspired by statsmodels


def Func ( arg_0 ) : arg_1 = arg_0 . xmlnode . prop ( "category" ) if not arg_1 : arg_1 = "?" return arg_1 . decode ( "utf-8" )

def Func(arg_0):
        """Get the category of the item.

        :return: the category of the item.
        :returntype: `unicode`"""
        arg_1 = arg_0.xmlnode.prop("category")
        if not arg_1:
            arg_1 = "?"
        return arg_1.decode("utf-8")


def Func ( ) : return dict ( ip_address = request . remote_addr , user_agent = request . user_agent . string , user_id = ( current_user . get_id ( ) if current_user . is_authenticated else None ) , session_id = session . get ( 'sid_s' ) )

def Func():
    """User information.

    .. note::

       **Privacy note** A users IP address, user agent string, and user id
       (if logged in) is sent to a message queue, where it is stored for about
       5 minutes. The information is used to:

       - Detect robot visits from the user agent string.
       - Generate an anonymized visitor id (using a random salt per day).
       - Detect the users host contry based on the IP address.

       The information is then discarded.
    """
    return dict(
        ip_address=request.remote_addr,
        user_agent=request.user_agent.string,
        user_id=(
            current_user.get_id() if current_user.is_authenticated else None
        ),
        session_id=session.get('sid_s')
    )


def
Func
(
arg_0
)
:
arg_1
=
arg_0
.
stats
arg_2
=
arg_1
.
pop
(
"contains_updates"
,
False
)
if
arg_1
else
False
if
not
arg_2
:
arg_3
=
'{} rows affected.'
.
format
(
len
(
arg_0
)
)
else
:
arg_3
=
''
for
arg_4
,
arg_5
in
arg_1
.
items
(
)
:
if
arg_5
:
arg_3
=
"{}\n{} {}."
.
format
(
arg_3
,
arg_5
,
arg_4
.
replace
(
"_"
,
" "
)
)
return
arg_3
.
strip
(
)

def Func(arg_0):
    """Generates the string to be shown as updates after the execution of a
    Cypher query

    :param results: ``ResultSet`` with the raw results of the execution of
                    the Cypher query
    """
    arg_1 = arg_0.stats
    arg_2 = arg_1.pop("contains_updates", False) if arg_1 else False
    if not arg_2:
        arg_3 = '{} rows affected.'.format(len(arg_0))
    else:
        arg_3 = ''
        for arg_4, arg_5 in arg_1.items():
            if arg_5:
                arg_3 = "{}\n{} {}.".format(arg_3, arg_5,
                                             arg_4.replace("_", " "))
    return arg_3.strip()


def Func(arg_0, arg_1):
    r"""
    Colorizes text a single color using ansii tags.

    Args:
        text (str): text to colorize
        color (str): may be one of the following: yellow, blink, lightgray,
            underline, darkyellow, blue, darkblue, faint, fuchsia, black,
            white, red, brown, turquoise, bold, darkred, darkgreen, reset,
            standout, darkteal, darkgray, overline, purple, green, teal, fuscia

    Returns:
        str: text : colorized text.
            If pygments is not installed plain text is returned.

    CommandLine:
        python -c "import pygments.console; print(sorted(pygments.console.codes.keys()))"
        python -m ubelt.util_colors Func

    Example:
        >>> text = 'raw text'
        >>> import pytest
        >>> import ubelt as ub
        >>> if ub.modname_to_modpath('pygments'):
        >>>     # Colors text only if pygments is installed
        >>>     assert Func(text, 'red') == '\x1b[31;01mraw text\x1b[39;49;00m'
        >>>     assert Func(text, None) == 'raw text'
        >>> else:
        >>>     # Otherwise text passes through unchanged
        >>>     assert Func(text, 'red') == 'raw text'
        >>>     assert Func(text, None) == 'raw text'
    """
    if arg_1 is None:
        return arg_0
    try:
        import pygments
        import pygments.console

        if sys.platform.startswith('win32'):  # nocover
            # Hack on win32 to support colored output
            import colorama
            colorama.init()

        arg_2 = pygments.console.colorize(arg_1, arg_0)
        return arg_2
    except ImportError:  # nocover
        import warnings
        warnings.warn('pygments is not installed, text will not be colored')
        return arg_0

r"""
    Colorizes text a single color using ansii tags.

    Args:
        text (str): text to colorize
        color (str): may be one of the following: yellow, blink, lightgray,
            underline, darkyellow, blue, darkblue, faint, fuchsia, black,
            white, red, brown, turquoise, bold, darkred, darkgreen, reset,
            standout, darkteal, darkgray, overline, purple, green, teal, fuscia

    Returns:
        str: text : colorized text.
            If pygments is not installed plain text is returned.

    CommandLine:
        python -c "import pygments.console; print(sorted(pygments.console.codes.keys()))"
        python -m ubelt.util_colors color_text

    Example:
        >>> text = 'raw text'
        >>> import pytest
        >>> import ubelt as ub
        >>> if ub.modname_to_modpath('pygments'):
        >>>     # Colors text only if pygments is installed
        >>>     assert color_text(text, 'red') == '\x1b[31;01mraw text\x1b[39;49;00m'
        >>>     assert color_text(text, None) == 'raw text'
        >>> else:
        >>>     # Otherwise text passes through unchanged
        >>>     assert color_text(text, 'red') == 'raw text'
        >>>     assert color_text(text, None) == 'raw text'

r Colorizes text a single color using ansii tags .


def
Func
(
arg_0
)
:
arg_0
.
calculate_cache_access
(
)
arg_0
.
calculate_cycles
(
)
arg_0
.
results
[
'flops per iteration'
]
=
sum
(
arg_0
.
kernel
.
_flops
.
values
(
)
)
return
arg_0
.
results

def Func(arg_0):
        """Run complete anaylysis and return results."""
        arg_0.calculate_cache_access()
        arg_0.calculate_cycles()
        arg_0.results['flops per iteration'] = sum(arg_0.kernel._flops.values())

        return arg_0.results

Run complete anaylysis and return results .


(context, vcf, vcf_sv, vcf_cancer, vcf_str, owner, ped, update, config,
         no_variants, peddy_ped, peddy_sex, peddy_check)

def Func(arg_0, arg_1, arg_2, arg_3, arg_4, arg_5, arg_6, arg_7, arg_8,
         arg_9, arg_10, arg_11, arg_12):
    """Load a Func into the database.

    A Func can be loaded without specifying vcf files and/or bam files
    """
    arg_13 = arg_0.obj['adapter']

    if arg_8 is None and arg_6 is None:
        LOG.warning("Please provide either scout config or ped file")
        arg_0.abort()

    # Scout needs a config object with the neccessary information
    # If no config is used create a dictionary
    arg_14 = yaml.load(arg_8) if arg_8 else {}

    try:
        arg_15 = parse_Func_data(
            arg_8=arg_14,
            arg_6=arg_6,
            arg_5=arg_5,
            vcf_snv=arg_1,
            arg_2=arg_2,
            arg_4=arg_4,
            arg_3=arg_3,
            arg_10=arg_10,
            arg_11=arg_11,
            arg_12=arg_12
        )
    except SyntaxError as err:
        LOG.warning(err)
        arg_0.abort()

    LOG.info("Use family %s" % arg_15['family'])

    try:
        arg_16 = arg_13.load_Func(arg_15, arg_7)
    except Exception as err:
        LOG.error("Something went wrong during loading")
        LOG.warning(err)
        arg_0.abort()

Load a case into the database.

    A case can be loaded without specifying vcf files and/or bam files


def Func(arg_0, arg_1, arg_2=None):
    """ Parse the given XML file and return a dict describing the file.

    Parameters:
    ----------------------------------------------------------------
    filename:  name of XML file to parse (no path)
    path:      path of the XML file. If None, then use the standard
                  configuration search path.
    retval:    returns a dict with each property as a key and a dict of all
               the property's attributes as value
    """

    arg_3 = dict()

    # Get the path to the config files.
    if arg_2 is None:
      arg_4 = arg_0.findConfigFile(arg_1)
    else:
      arg_4 = os.path.join(arg_2, arg_1)

    # ------------------------------------------------------------------
    # Read in the config file
    try:
      if arg_4 is not None:
        try:
          # Use warn since console log level is set to warning
          _getLoggerBase().debug("Loading config file: %s", arg_4)
          with open(arg_4, 'r') as inp:
            arg_5 = inp.read()
        except Exception:
          raise RuntimeError("Expected configuration file at %s" % arg_4)
      else:
        # If the file was not found in the normal search paths, which includes
        # checking the NTA_CONF_PATH, we'll try loading it from pkg_resources.
        try:
          arg_5 = resource_string("nupic.support", arg_1)
        except Exception as resourceException:
          # We expect these to be read, and if they don't exist we'll just use
          # an empty configuration string.
          if arg_1 in [USER_CONFIG, CUSTOM_CONFIG]:
            arg_5 = '<configuration/>'
          else:
            raise resourceException

      arg_6 = ElementTree.XML(arg_5)

      if arg_6.tag != 'configuration':
        raise RuntimeError("Expected top-level element to be 'configuration' "
                           "but got '%s'" % (arg_6.tag))

      # ------------------------------------------------------------------
      # Add in each property found
      arg_7 = arg_6.findall('./property')

      for arg_8 in arg_7:

        arg_9 = dict()

        # Parse this property element
        arg_10 = list(arg_8)
        for arg_11 in arg_10:
          arg_9[arg_11.tag] = arg_11.text

        # Get the name
        arg_13 = arg_9.get('name', None)

        # value is allowed to be empty string
        if 'value' in arg_9 and arg_9['value'] is None:
          arg_14 = ''
        else:
          arg_14 = arg_9.get('value', None)

          if arg_14 is None:
            if 'novalue' in arg_9:
              # Placeholder "novalue" properties are intended to be overridden
              # via dynamic configuration or another configuration layer.
              continue
            else:
              raise RuntimeError("Missing 'value' element within the property "
                                 "element: => %s " % (str(arg_9)))

        # The value is allowed to contain substitution tags of the form
        # ${env.VARNAME}, which should be substituted with the corresponding
        # environment variable values
        arg_15 = arg_14
        arg_14 = ''
        while True:
          # Find the beginning of substitution tag
          arg_16 = arg_15.find('${env.')
          if arg_16 == -1:
            # No more environment variable substitutions
            arg_14 += arg_15
            break

          # Append prefix to value accumulator
          arg_14 += arg_15[0:arg_16]

          # Find the end of current substitution tag
          arg_17 = arg_15.find('}', arg_16)
          if arg_17 == -1:
            raise RuntimeError(
              "Trailing environment variable tag delimiter '}'"
              " not found in %r" % (arg_15))

          # Extract environment variable name from tag
          arg_18 = arg_15[arg_16 + 6:arg_17]
          if arg_18 not in os.environ:
            raise RuntimeError("Attempting to use the value of the environment"
                               " variable %r, which is not defined" % (
                               arg_18))
          arg_19 = os.environ[arg_18]

          arg_14 += arg_19

          arg_15 = arg_15[arg_17 + 1:]

        # Check for errors
        if arg_13 is None:
          raise RuntimeError(
            "Missing 'name' element within following property "
            "element:\n => %s " % (str(arg_9)))

        arg_9['value'] = arg_14
        arg_3[arg_13] = arg_9

      return arg_3
    except Exception:
      _getLoggerBase().exception("Error while parsing configuration file: %s.",
                             arg_4)
      raise

Parse the given XML file and return a dict describing the file .


def Func(arg_0, arg_1):
        """Get authorization code response from a URI. This method will
        ignore the domain and path of the request, instead
        automatically parsing the query string parameters.

        :param uri: URI to parse for authorization information.
        :type uri: str
        :rtype: requests.Response
        """
        arg_2 = utils.url_query_params(arg_1)
        try:
            if 'response_type' not in arg_2:
                raise TypeError('Missing parameter response_type in URL query')

            if 'client_id' not in arg_2:
                raise TypeError('Missing parameter client_id in URL query')

            if 'redirect_uri' not in arg_2:
                raise TypeError('Missing parameter redirect_uri in URL query')

            return arg_0.get_authorization_code(**arg_2)
        except TypeError as exc:
            arg_0._handle_exception(exc)

            # Catch missing parameters in request
            arg_3 = 'invalid_request'
            if 'redirect_uri' in arg_2:
                arg_4 = arg_2['redirect_uri']
                return arg_0._make_redirect_error_response(arg_4, arg_3)
            else:
                return arg_0._invalid_redirect_uri_response()
        except StandardError as exc:
            arg_0._handle_exception(exc)

            # Catch all other server errors
            arg_3 = 'server_error'
            arg_4 = arg_2['redirect_uri']
            return arg_0._make_redirect_error_response(arg_4, arg_3)

Get authorization code response from a URI . This method will ignore the domain and path of the request instead automatically parsing the query string parameters .


def Func(arg_0, arg_1):
    """Use the central arc-second coordinate of every unmasked pixelization grid's pixels and mapping between each
    pixelization pixel and unmasked pixelization pixel to compute the central arc-second coordinate of every masked
    pixelization grid pixel.

    Parameters
    -----------
    unmasked_sparse_grid : ndarray
        The (y,x) arc-second centre of every unmasked pixelization grid pixel.
    sparse_to_unmasked_sparse : ndarray
        The index mapping between every pixelization pixel and masked pixelization pixel.
    """
    arg_2 = arg_1.shape[0]

    arg_3 = np.zeros((arg_2, 2))

    for arg_4 in range(arg_2):
        arg_3[arg_4, 0] = arg_0[arg_1[arg_4], 0]
        arg_3[arg_4, 1] = arg_0[arg_1[arg_4], 1]

    return arg_3

Use the central arc - second coordinate of every unmasked pixelization grid s pixels and mapping between each pixelization pixel and unmasked pixelization pixel to compute the central arc - second coordinate of every masked pixelization grid pixel .


def Func(arg_0, arg_1):
    """Adds commit information to the trajectory."""

    arg_2 = time.strftime('%Y_%m_%d_%Hh%Mm%Ss', time.localtime(arg_1.committed_date))

    arg_3 = str(arg_1.hexsha[0:7])
    arg_4 = 'commit_%s_' % arg_3
    arg_4 = 'git.' + arg_4 + arg_2

    if not arg_0.f_contains('config.'+arg_4, shortcuts=False):

        arg_4 += '.'
        # Add the hexsha
        arg_0.f_add_config(arg_4+'hexsha', arg_1.hexsha,
                          comment='SHA-1 hash of commit')

        # Add the description string
        arg_0.f_add_config(arg_4+'name_rev', arg_1.name_rev,
                          comment='String describing the commits hex sha based on '
                                  'the closest Reference')

        # Add unix epoch
        arg_0.f_add_config(arg_4+'committed_date',
                          arg_1.committed_date, comment='Date of commit as unix epoch seconds')

        # Add commit message
        arg_0.f_add_config(arg_4+'message', str(arg_1.message),
                          comment='The commit message')

Adds commit information to the trajectory .


return s.st_mode & getattr(stat, 'S_I{}{}'.format(perm, pos))

def Func ( arg_0 , arg_1 , arg_2 ) : arg_1 = arg_1 . upper ( ) arg_2 = arg_2 . upper ( ) assert arg_1 in [ 'R' , 'W' , 'X' ] assert arg_2 in [ 'USR' , 'GRP' , 'OTH' ] return arg_0 . st_mode & getattr ( stat , 'S_I{}{}' . format ( arg_1 , arg_2 ) )

def Func(arg_0, arg_1, arg_2):
    """Returns zero if there are no permissions for a bit of the perm. of a file. Otherwise it returns a positive value

    :param os.stat_result s: os.stat(file) object
    :param str perm: R (Read) or W (Write) or X (eXecute)
    :param str pos: USR (USeR) or GRP (GRouP) or OTH (OTHer)
    :return: mask value
    :rtype: int
    """
    arg_1 = arg_1.upper()
    arg_2 = arg_2.upper()
    assert arg_1 in ['R', 'W', 'X']
    assert arg_2 in ['USR', 'GRP', 'OTH']
    return arg_0.st_mode & getattr(stat, 'S_I{}{}'.format(arg_1, arg_2))

Returns zero if there are no permissions for a bit of the perm . of a file . Otherwise it returns a positive value


def Func ( arg_0 ) -> ast . stmt : if arg_0 . in_optional : return ast . Pass ( ) if arg_0 . in_try : return ast . Raise ( ast . Call ( ast . Name ( 'AltFalse' , ast . Load ( ) ) , [ ] , [ ] , None , None ) , None ) if arg_0 . in_loop : return ast . Break ( ) return ast . Return ( ast . Name ( 'False' , ast . Load ( ) ) )

def Func(arg_0) -> ast.stmt:
        """Create the appropriate scope exiting statement.

        The documentation only shows one level and always uses
        'return False' in examples.

        'raise AltFalse()' within a try.
        'break' within a loop.
        'return False' otherwise.
        """
        if arg_0.in_optional:
            return ast.Pass()
        if arg_0.in_try:
            return ast.Raise(
                ast.Call(ast.Name('AltFalse', ast.Load()), [], [], None, None),
                None)
        if arg_0.in_loop:
            return ast.Break()
        return ast.Return(ast.Name('False', ast.Load()))

Create the appropriate scope exiting statement .


def Func ( arg_0 ) : arg_1 = urlsplit ( arg_0 . url ) arg_2 = arg_1 . path . split ( "/" ) [ - 1 ] if not os . path . exists ( arg_0 . cache_directory ) : os . makedirs ( arg_0 . cache_directory ) arg_3 = os . path . join ( arg_0 . cache_directory , arg_2 ) arg_4 = urllib_request . urlopen ( arg_0 . url ) with open ( arg_3 , "wb" ) as image : image . write ( arg_4 . read ( ) ) return arg_3

def Func(arg_0):
        """
        Download the image and return the
        local path to the image file.
        """
        arg_1 = urlsplit(arg_0.url)
        arg_2 = arg_1.path.split("/")[-1]

        # Ensure the directory to store the image cache exists
        if not os.path.exists(arg_0.cache_directory):
            os.makedirs(arg_0.cache_directory)

        arg_3 = os.path.join(arg_0.cache_directory, arg_2)

        arg_4 = urllib_request.urlopen(arg_0.url)
        with open(arg_3, "wb") as image:
            image.write(arg_4.read())

        return arg_3

Download the image and return the local path to the image file .


def Func ( arg_0 , arg_1 , arg_2 ) : arg_0 . reset_annotations ( ) if validations . validate_annotator ( arg_2 ) : arg_1 . add_annotation ( annotation . Annotation ( arg_2 = arg_2 ) ) return True else : raise SPDXValueError ( 'Annotation::Annotator' )

def Func(arg_0, arg_1, arg_2):
        """Adds an annotator to the SPDX Document.
        Annotator is an entity created by an EntityBuilder.
        Raises SPDXValueError if not a valid annotator type.
        """
        # Each annotator marks the start of a new annotation object.
        # FIXME: this state does not make sense
        arg_0.reset_annotations()
        if validations.validate_annotator(arg_2):
            arg_1.add_annotation(annotation.Annotation(arg_2=arg_2))
            return True
        else:
            raise SPDXValueError('Annotation::Annotator')

Adds an annotator to the SPDX Document . Annotator is an entity created by an EntityBuilder . Raises SPDXValueError if not a valid annotator type .


def Func(arg_0):
        """Defines any necessary environment variables for the pod executor"""
        arg_1 = {}

        for arg_2, arg_3 in six.iteritems(arg_0.kube_config.kube_env_vars):
            arg_1[arg_2] = arg_3

        arg_1["AIRFLOW__CORE__EXECUTOR"] = "LocalExecutor"

        if arg_0.kube_config.airflow_configmap:
            arg_1['AIRFLOW_HOME'] = arg_0.worker_airflow_home
            arg_1['AIRFLOW__CORE__DAGS_FOLDER'] = arg_0.worker_airflow_dags
        if (not arg_0.kube_config.airflow_configmap and
                'AIRFLOW__CORE__SQL_ALCHEMY_CONN' not in arg_0.kube_config.kube_secrets):
            arg_1['AIRFLOW__CORE__SQL_ALCHEMY_CONN'] = conf.get("core", "SQL_ALCHEMY_CONN")
        if arg_0.kube_config.git_dags_folder_mount_point:
            # /root/airflow/dags/repo/dags
            arg_4 = os.path.join(
                arg_0.kube_config.git_dags_folder_mount_point,
                arg_0.kube_config.git_sync_dest,  # repo
                arg_0.kube_config.git_subpath     # dags
            )
            arg_1['AIRFLOW__CORE__DAGS_FOLDER'] = arg_4
        return arg_1


(self, x="x", y="y", radius_out="r_polar", azimuth_out="phi_polar",
                                               propagate_uncertainties=False,
                                               radians=False)

def Func(arg_0, arg_1="x", arg_2="y", arg_3="r_polar", arg_4="phi_polar",
                                               arg_5=False,
                                               arg_6=False):
        """Convert cartesian to polar coordinates

        :param x: expression for x
        :param y: expression for y
        :param radius_out: name for the virtual column for the radius
        :param azimuth_out: name for the virtual column for the azimuth angle
        :param propagate_uncertainties: {propagate_uncertainties}
        :param radians: if True, azimuth is in radians, defaults to degrees
        :return:
        """
        arg_1 = arg_0[arg_1]
        arg_2 = arg_0[arg_2]
        if arg_6:
            arg_7 = ""
        else:
            arg_7 = "*180/pi"
        arg_8 = np.sqrt(arg_1**2 + arg_2**2)
        arg_0[arg_3] = arg_8
        arg_9 = np.arctan2(arg_2, arg_1)
        if not arg_6:
            arg_9 = arg_9 * 180/np.pi
        arg_0[arg_4] = arg_9
        if arg_5:
            arg_0.propagate_uncertainties([arg_0[arg_3], arg_0[arg_4]])


def Func ( arg_0 , arg_1 ) : if arg_1 != 'epoch' : return datetime . strptime ( arg_0 , arg_1 ) . timestamp ( ) else : return float ( arg_0 )

def Func(arg_0, arg_1):
    """
    Convert a date in a given format to epoch time. Mostly a wrapper for
    datetime's strptime.
    """
    if arg_1 != 'epoch':
        return datetime.strptime(arg_0, arg_1).timestamp()
    else:
        return float(arg_0)

Convert a date in a given format to epoch time . Mostly a wrapper for datetime s strptime .


def Func ( arg_0 ) : arg_1 = arg_0 . _data ( ) if isinstance ( arg_1 , dict ) and isinstance ( arg_0 , ListFile ) : arg_0 . __class__ = DictFile elif isinstance ( arg_1 , list ) and isinstance ( arg_0 , DictFile ) : arg_0 . __class__ = ListFile

def Func(arg_0):
        """Make sure that the class behaves like the data structure that it
        is, so that we don't get a ListFile trying to represent a dict."""
        arg_1 = arg_0._data()
        # Change type if needed
        if isinstance(arg_1, dict) and isinstance(arg_0, ListFile):
            arg_0.__class__ = DictFile
        elif isinstance(arg_1, list) and isinstance(arg_0, DictFile):
            arg_0.__class__ = ListFile

Make sure that the class behaves like the data structure that it is so that we don t get a ListFile trying to represent a dict .


def Func ( arg_0 ) : if arg_0 . _tapFileIn is not None : arg_0 . _tapFileIn . close ( ) arg_0 . _tapFileIn = None if arg_0 . _tapFileOut is not None : arg_0 . _tapFileOut . close ( ) arg_0 . _tapFileOut = None

def Func(arg_0):
    """
    Disable writing of output tap files.
    """

    if arg_0._tapFileIn is not None:
      arg_0._tapFileIn.close()
      arg_0._tapFileIn = None
    if arg_0._tapFileOut is not None:
      arg_0._tapFileOut.close()
      arg_0._tapFileOut = None


(self, model_instance, field, is_insert: bool)

def Func(arg_0, arg_1, arg_2, arg_3: arg_4):
        """Verifies whether this field is gonna modify something
        on its own.

        "Magical" means that a field modifies the field value
        during the pre_save.

        Arguments:
            model_instance:
                The model instance the field is defined on.

            field:
                The field to get of whether the field is
                magical.

            is_insert:
                Pretend whether this is an insert?

        Returns:
            True when this field modifies something.
        """

        # does this field modify someting upon insert?
        arg_5 = getattr(arg_1, arg_2.name, None)
        arg_2.pre_save(arg_1, arg_3)
        arg_6 = getattr(arg_1, arg_2.name, None)

        return arg_5 != arg_6

Verifies whether this field is gonna modify something on its own .


Resizes the layer to the given width and height.

        When width w or height h is a floating-point number,
        scales percentual,
        otherwise scales to the given size in pixels.

def Func ( arg_0 , arg_1 = 1.0 , arg_2 = 1.0 ) : from types import FloatType arg_3 , arg_4 = arg_0 . img . size if type ( arg_1 ) == FloatType : arg_1 = int ( arg_1 * arg_3 ) if type ( arg_2 ) == FloatType : arg_2 = int ( arg_2 * arg_4 ) arg_0 . img = arg_0 . img . resize ( ( arg_1 , arg_2 ) , INTERPOLATION ) arg_0 . w = arg_1 arg_0 . h = arg_2

def Func(arg_0, arg_1=1.0, arg_2=1.0):

        """Resizes the layer to the given width and height.

        When width w or height h is a floating-point number,
        Funcs percentual,
        otherwise Funcs to the given size in pixels.

        """

        from types import FloatType
        arg_3, arg_4 = arg_0.img.size
        if type(arg_1) == FloatType: arg_1 = int(arg_1*arg_3)
        if type(arg_2) == FloatType: arg_2 = int(arg_2*arg_4)

        arg_0.img = arg_0.img.resize((arg_1,arg_2), INTERPOLATION)
        arg_0.w = arg_1
        arg_0.h = arg_2

Resizes the layer to the given width and height . When width w or height h is a floating - point number scales percentual otherwise scales to the given size in pixels .


def Func ( arg_0 , arg_1 ) : arg_2 = { } arg_2 [ arg_1 [ 'id' ] ] = json . loads ( arg_0 . client . get_comments ( arg_1 [ 'id' ] ) ) for arg_3 in arg_1 [ 'answer_ids' ] : arg_2 [ arg_3 ] = json . loads ( arg_0 . client . get_comments ( arg_3 ) ) return arg_2

def Func(arg_0, arg_1):
        """Fetch all the comments of an Askbot question and answers.

        The method fetchs the list of every comment existing in a question and
        its answers.

        :param question: item with the question itself

        :returns: a list of comments with the ids as hashes
        """
        arg_2 = {}
        arg_2[arg_1['id']] = json.loads(arg_0.client.get_comments(arg_1['id']))
        for arg_3 in arg_1['answer_ids']:
            arg_2[arg_3] = json.loads(arg_0.client.get_comments(arg_3))
        return arg_2

Fetch all the comments of an Askbot question and answers .


def
Func
(
arg_0
,
arg_1
,
arg_2
)
:
arg_3
=
False
arg_4
=
arg_0
.
Colors
arg_5
=
[
]
arg_6
=
arg_4
.
excName
+
arg_1
.
__name__
+
arg_4
.
Normal
if
arg_2
is
:
arg_5
.
append
(
str
(
arg_6
)
+
'\n'
)
else
:
if
arg_1
is
SyntaxError
:
arg_3
=
True
if
not
arg_2
.
filename
:
arg_2
.
filename
=
"<string>"
arg_5
.
append
(
'%s  File %s"%s"%s, line %s%d%s\n'
%
(
arg_4
.
normalEm
,
arg_4
.
filenameEm
,
arg_2
.
filename
,
arg_4
.
normalEm
,
arg_4
.
linenoEm
,
arg_2
.
lineno
,
arg_4
.
Normal
)
)
if
arg_2
.
text
is
not
:
arg_8
=
0
while
arg_8
<
len
(
arg_2
.
text
)
and
arg_2
.
text
[
arg_8
]
.
isspace
(
)
:
arg_8
+=
1
arg_5
.
append
(
'%s    %s%s\n'
%
(
arg_4
.
line
,
arg_2
.
text
.
strip
(
)
,
arg_4
.
Normal
)
)
if
arg_2
.
offset
is
not
:
arg_9
=
'    '
for
arg_10
in
arg_2
.
text
[
arg_8
:
arg_2
.
offset
1
]
:
if
arg_10
.
isspace
(
)
:
arg_9
+=
arg_10
else
:
arg_9
+=
' '
arg_5
.
append
(
'%s%s^%s\n'
%
(
arg_4
.
caret
,
arg_9
,
arg_4
.
Normal
)
)
try
:
arg_9
=
arg_2
.
msg
except
Exception
:
arg_9
=
arg_0
.
_some_str
(
arg_2
)
if
arg_9
:
arg_5
.
append
(
'%s%s:%s %s\n'
%
(
str
(
arg_6
)
,
arg_4
.
excName
,
arg_4
.
Normal
,
arg_9
)
)
else
:
arg_5
.
append
(
'%s\n'
%
str
(
arg_6
)
)
if
arg_3
:
arg_11
=
ipapi
.
get
(
)
if
arg_11
is
not
:
arg_11
.
hooks
.
synchronize_with_editor
(
arg_2
.
filename
,
arg_2
.
lineno
,
0
)
return
arg_5

def Func(arg_0, arg_1, arg_2):
        """Format the exception part of a traceback.

        The arguments are the exception type and value such as given by
        sys.exc_info()[:2]. The return value is a list of strings, each ending
        in a newline.  Normally, the list contains a single string; however,
        for SyntaxError exceptions, it contains several lines that (when
        printed) display detailed information about where the syntax error
        occurred.  The message indicating which exception occurred is the
        always last string in the list.

        Also lifted nearly verbatim from traceback.py
        """

        arg_3 = False
        arg_4 = arg_0.Colors
        arg_5 = []
        arg_6 = arg_4.excName + arg_1.__name__ + arg_4.Normal
        if arg_2 is None:
            # Not sure if this can still happen in Python 2.6 and above
            arg_5.append( str(arg_6) + '\n')
        else:
            if arg_1 is SyntaxError:
                arg_3 = True
                #print 'filename is',filename  # dbg
                if not arg_2.filename: arg_2.filename = "<string>"
                arg_5.append('%s  File %s"%s"%s, line %s%d%s\n' % \
                        (arg_4.normalEm,
                         arg_4.filenameEm, arg_2.filename, arg_4.normalEm,
                         arg_4.linenoEm, arg_2.lineno, arg_4.Normal  ))
                if arg_2.text is not None:
                    arg_8 = 0
                    while arg_8 < len(arg_2.text) and arg_2.text[arg_8].isspace():
                        arg_8 += 1
                    arg_5.append('%s    %s%s\n' % (arg_4.line,
                                                  arg_2.text.strip(),
                                                  arg_4.Normal))
                    if arg_2.offset is not None:
                        arg_9 = '    '
                        for arg_10 in arg_2.text[arg_8:arg_2.offset-1]:
                            if arg_10.isspace():
                                arg_9 += arg_10
                            else:
                                arg_9 += ' '
                        arg_5.append('%s%s^%s\n' % (arg_4.caret, arg_9,
                                                   arg_4.Normal) )

            try:
                arg_9 = arg_2.msg
            except Exception:
                arg_9 = arg_0._some_str(arg_2)
            if arg_9:
                arg_5.append('%s%s:%s %s\n' % (str(arg_6), arg_4.excName,
                                              arg_4.Normal, arg_9))
            else:
                arg_5.append('%s\n' % str(arg_6))

        # sync with user hooks
        if arg_3:
            arg_11 = ipapi.get()
            if arg_11 is not None:
                arg_11.hooks.synchronize_with_editor(arg_2.filename, arg_2.lineno, 0)

        return arg_5

Format the exception part of a traceback .


def Func ( arg_0 , arg_1 : arg_2 . Callable ) -> dict : arg_4 = arg_1 . __doc__ if not arg_4 : return { } arg_4 = arg_4 . split ( "---" ) [ - 1 ] arg_5 = yaml . safe_load ( arg_4 ) if not isinstance ( arg_5 , dict ) : return { } return arg_5

def Func(arg_0, arg_1: arg_2.Callable) -> dict:
        """
        Given a function, parse the docstring as YAML and return a dictionary of info.
        """
        arg_4 = arg_1.__doc__
        if not arg_4:
            return {}

        # We support having regular docstrings before the schema
        # definition. Here we return just the schema part from
        # the docstring.
        arg_4 = arg_4.split("---")[-1]

        arg_5 = yaml.safe_load(arg_4)

        if not isinstance(arg_5, dict):
            # A regular docstring (not yaml formatted) can return
            # a simple string here, which wouldn't follow the schema.
            return {}

        return arg_5

Given a function parse the docstring as YAML and return a dictionary of info .


def Func ( arg_0 , arg_1 ) : if arg_1 : return sum ( map ( lambda galaxy : galaxy . deflections_from_grid ( arg_0 ) , arg_1 ) ) else : return np . full ( ( arg_0 . shape [ 0 ] , 2 ) , 0.0 )

def Func(arg_0, arg_1):
    """Compute the deflections of a list of galaxies from an input sub-grid, by summing the individual deflections \
    of each galaxy's mass profile.

    The deflections are calculated on the sub-grid and binned-up to the original regular grid by taking the mean value \
    of every set of sub-pixels.

    If no galaxies are entered into the function, an array of all zeros is returned.

    Parameters
    -----------
    sub_grid : RegularGrid
        The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \
        deflections is calculated on.
    galaxies : [galaxy.Galaxy]
        The galaxies whose mass profiles are used to compute the surface densities.
    """
    if arg_1:
        return sum(map(lambda galaxy: galaxy.deflections_from_grid(arg_0), arg_1))
    else:
        return np.full((arg_0.shape[0], 2), 0.0)

Compute the deflections of a list of galaxies from an input sub - grid by summing the individual deflections \ of each galaxy s mass profile .


def
Func
(
arg_0
,
arg_1
,
arg_2
=
)
:
arg_3
=
arg_1
.
get
(
'content'
,
{
}
)
if
arg_3
is
:
arg_3
=
arg_0
.
elif
isinstance
(
arg_3
,
dict
)
:
arg_3
=
arg_0
.
pack
(
arg_3
)
elif
isinstance
(
arg_3
,
bytes
)
:
pass
elif
isinstance
(
arg_3
,
unicode
)
:
arg_3
=
arg_3
.
encode
(
'utf8'
)
else
:
raise
TypeError
(
"Content incorrect type: %s"
%
type
(
arg_3
)
)
arg_4
=
[
arg_0
.
pack
(
arg_1
[
'header'
]
)
,
arg_0
.
pack
(
arg_1
[
'parent_header'
]
)
,
arg_3
]
arg_5
=
[
]
if
isinstance
(
arg_2
,
list
)
:
arg_5
.
extend
(
arg_2
)
elif
arg_2
is
not
:
arg_5
.
append
(
arg_2
)
arg_5
.
append
(
DELIM
)
arg_6
=
arg_0
.
sign
(
arg_4
)
arg_5
.
append
(
arg_6
)
arg_5
.
extend
(
arg_4
)
return
arg_5

def Func(arg_0, arg_1, arg_2=None):
        """Serialize the message components to bytes.

        This is roughly the inverse of unFunc. The Func/unFunc
        methods work with full message lists, whereas pack/unpack work with
        the individual message parts in the message list.

        Parameters
        ----------
        msg : dict or Message
            The nexted message dict as returned by the self.msg method.

        Returns
        -------
        msg_list : list
            The list of bytes objects to be sent with the format:
            [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content,
             buffer1,buffer2,...]. In this list, the p_* entities are
            the packed or Funcd versions, so if JSON is used, these
            are utf8 encoded JSON strings.
        """
        arg_3 = arg_1.get('content', {})
        if arg_3 is None:
            arg_3 = arg_0.none
        elif isinstance(arg_3, dict):
            arg_3 = arg_0.pack(arg_3)
        elif isinstance(arg_3, bytes):
            # content is already packed, as in a relayed message
            pass
        elif isinstance(arg_3, unicode):
            # should be bytes, but JSON often spits out unicode
            arg_3 = arg_3.encode('utf8')
        else:
            raise TypeError("Content incorrect type: %s"%type(arg_3))

        arg_4 = [arg_0.pack(arg_1['header']),
                        arg_0.pack(arg_1['parent_header']),
                        arg_3
        ]

        arg_5 = []

        if isinstance(arg_2, list):
            # accept list of idents
            arg_5.extend(arg_2)
        elif arg_2 is not None:
            arg_5.append(arg_2)
        arg_5.append(DELIM)

        arg_6 = arg_0.sign(arg_4)
        arg_5.append(arg_6)

        arg_5.extend(arg_4)

        return arg_5

Serialize the message components to bytes.

        This is roughly the inverse of unserialize. The serialize/unserialize
        methods work with full message lists, whereas pack/unpack work with
        the individual message parts in the message list.

        Parameters
        ----------
        msg : dict or Message
            The nexted message dict as returned by the self.msg method.

        Returns
        -------
        msg_list : list
            The list of bytes objects to be sent with the format:
            [ident1,ident2,...,DELIM,HMAC,p_header,p_parent,p_content,
             buffer1,buffer2,...]. In this list, the p_* entities are
            the packed or serialized versions, so if JSON is used, these
            are utf8 encoded JSON strings.

Serialize the message components to bytes .


def Func(arg_0, arg_1):
        '''
        Saves an AnswerFactory Recipe

        Args:
            recipe (dict): Dictionary specifying a recipe

        Returns:
            AnswerFactory Recipe id
        '''
        # test if this is a create vs. an update
        if 'id' in arg_1 and arg_1['id'] is not None:
            # update -> use put op
            arg_0.logger.debug("Updating existing recipe: " + json.dumps(arg_1))
            arg_2 = '%(base_url)s/recipe/json/%(recipe_id)s' % {
                'base_url': arg_0.base_url, 'recipe_id': arg_1['id']
            }
            arg_3 = arg_0.gbdx_connection.put(arg_2, json=arg_1)
            try:
                arg_3.raise_for_status()
            except:
                print(arg_3.text)
                raise
            return arg_1['id']
        else:
            # create -> use post op
            arg_0.logger.debug("Creating new recipe: " + json.dumps(arg_1))
            arg_2 = '%(base_url)s/recipe/json' % {
                'base_url': arg_0.base_url
            }
            arg_3 = arg_0.gbdx_connection.post(arg_2, json=arg_1)
            try:
                arg_3.raise_for_status()
            except:
                print(arg_3.text)
                raise
            arg_4 = arg_3.json()
            return arg_4['id']


(name, value, target_unit, unit_framework)

def Func(arg_0, arg_1, arg_2, arg_3):
    """
    Check that a value has physical type consistent with user-specified units

    Note that this does not convert the value, only check that the units have
    the right physical dimensionality.

    Parameters
    ----------
    name : str
        The name of the value to check (used for error messages).
    value : `numpy.ndarray` or instance of `numpy.ndarray` subclass
        The value to check.
    target_unit : unit
        The unit that the value should be convertible to.
    unit_framework : str
        The unit framework to use
    """

    if arg_3 == ASTROPY:

        from astropy.units import Quantity

        if not isinstance(arg_1, Quantity):
            raise TraitError("{0} should be given as an Astropy Quantity instance".format(arg_0))

        if not arg_2.is_equivalent(arg_1.unit):
            raise TraitError("{0} should be in units convertible to {1}".format(arg_0, arg_2))

    elif arg_3 == PINT:

        from pint.unit import UnitsContainer

        if not (hasattr(arg_1, 'dimensionality') and isinstance(arg_1.dimensionality, UnitsContainer)):
            raise TraitError("{0} should be given as a Pint Quantity instance".format(arg_0))

        if arg_1.dimensionality != arg_2.dimensionality:
            raise TraitError("{0} should be in units convertible to {1}".format(arg_0, arg_2))

    elif arg_3 == QUANTITIES:

        from quantities import Quantity

        if not isinstance(arg_1, Quantity):
            raise TraitError("{0} should be given as a quantities Quantity instance".format(arg_0))

        if arg_1.dimensionality.simplified != arg_2.dimensionality.simplified:
            raise TraitError("{0} should be in units convertible to {1}".format(arg_0, arg_2.dimensionality.string))

Check that a value has physical type consistent with user - specified units


def Func ( arg_0 , arg_1 , arg_2 ) : arg_3 = PendingEnterpriseCustomerUser . objects . filter ( enterprise_customer__uuid = arg_2 ) if arg_1 is not None : arg_3 = arg_3 . filter ( user_email__icontains = arg_1 ) return arg_3

def Func(arg_0, arg_1, arg_2):
        """
        Get the list of PendingEnterpriseCustomerUsers we want to render.

        Args:
            search_keyword (str): The keyword to search for in pending users' email addresses.
            customer_uuid (str): A unique identifier to filter down to only pending users
            linked to a particular EnterpriseCustomer.
        """
        arg_3 = PendingEnterpriseCustomerUser.objects.filter(
            enterprise_customer__uuid=arg_2
        )

        if arg_1 is not None:
            arg_3 = arg_3.filter(user_email__icontains=arg_1)

        return arg_3

Get the list of PendingEnterpriseCustomerUsers we want to render .


def Func ( arg_0 , arg_1 ) : arg_2 = b64decode ( arg_1 ) try : return ( arg_2 . decode ( 'utf-8' ) , 'text' ) except UnicodeError : pass return arg_1 . decode ( 'ascii' ) , 'base64'

def Func(arg_0, arg_1):
    """
    Decode base64 data of unknown format.

    Attempts to interpret data as utf-8, falling back to ascii on failure.
    """
    arg_2 = b64decode(arg_1)
    try:
        return (arg_2.decode('utf-8'), 'text')
    except UnicodeError:
        pass
    return arg_1.decode('ascii'), 'base64'


def Func ( arg_0 , arg_1 ) : arg_2 = arg_0 . error_handler_spec . get ( request . blueprint ) if arg_1 . code is None : return arg_1 if arg_2 and arg_1 . code in arg_2 : arg_3 = arg_2 [ arg_1 . code ] else : arg_3 = arg_0 . error_handler_spec [ None ] . get ( arg_1 . code ) if arg_3 is None : return arg_1 return arg_3 ( arg_1 )

def Func(arg_0, arg_1):
        """Handles an HTTP exception.  By default this will invoke the
        registered error handlers and fall back to returning the
        exception as response.

        .. versionadded:: 0.3
        """
        arg_2 = arg_0.error_handler_spec.get(request.blueprint)
        # Proxy exceptions don't have error codes.  We want to always return
        # those unchanged as errors
        if arg_1.code is None:
            return arg_1
        if arg_2 and arg_1.code in arg_2:
            arg_3 = arg_2[arg_1.code]
        else:
            arg_3 = arg_0.error_handler_spec[None].get(arg_1.code)
        if arg_3 is None:
            return arg_1
        return arg_3(arg_1)

Handles an HTTP exception . By default this will invoke the registered error handlers and fall back to returning the exception as response .


def Func ( arg_0 , arg_1 ) : arg_2 = arg_0 . get_content_metadata_exporter ( arg_1 ) arg_3 = arg_0 . get_content_metadata_transmitter ( ) arg_3 . transmit ( arg_2 . export ( ) )

def Func(arg_0, arg_1):
        """
        Transmit content metadata to integrated channel.
        """
        arg_2 = arg_0.get_content_metadata_exporter(arg_1)
        arg_3 = arg_0.get_content_metadata_transmitter()
        arg_3.transmit(arg_2.export())

Transmit content metadata to integrated channel .


def Func(arg_0,):
        """Refresh access token
        """
        logger.debug("REFRESHING TOKEN")
        arg_0.token_time = time.time()
        arg_2 = {
            'token_time': arg_0.token_time
        }

        if arg_0.oauth_version == 'oauth1':
            arg_0.access_token, arg_0.access_token_secret = arg_0.oauth.get_access_token(arg_0.access_token, arg_0.access_token_secret, params={"oauth_session_handle": arg_0.session_handle})
            arg_2.update({
                'access_token': arg_0.access_token,
                'access_token_secret': arg_0.access_token_secret,
                'session_handle': arg_0.session_handle,
                'token_time': arg_0.token_time
            })
        else:
            arg_5 = arg_0.generate_oauth2_headers()

            arg_6 = arg_0.oauth.get_raw_access_token(data={"refresh_token": arg_0.refresh_token, 'redirect_uri': arg_0.callback_uri,'grant_type':'refresh_token'}, arg_5=arg_5)
            arg_2.update(arg_0.oauth2_access_parser(arg_6))

        return arg_2


def Func ( arg_0 , arg_1 ) : assert arg_1 == "" or arg_1 . startswith ( "/" ) if arg_1 == "/" : arg_1 = "" assert arg_1 in ( "" , "/" ) or not arg_1 . endswith ( "/" ) arg_0 . share_path = arg_1

def Func(arg_0, arg_1):
        """Set application location for this resource provider.

        @param share_path: a UTF-8 encoded, unquoted byte string.
        """
        # if isinstance(share_path, unicode):
        #     share_path = share_path.encode("utf8")
        assert arg_1 == "" or arg_1.startswith("/")
        if arg_1 == "/":
            arg_1 = ""  # This allows to code 'absPath = share_path + path'
        assert arg_1 in ("", "/") or not arg_1.endswith("/")
        arg_0.share_path = arg_1

Set application location for this resource provider .


def Func ( arg_0 , arg_1 ) : return re . split ( b'|' . join ( arg_0 . LINE_TERMINATORS ) , arg_1 )

def Func(arg_0, arg_1):
        """
        Split data into lines where lines are separated by LINE_TERMINATORS.

        :param data: Any chunk of binary data.
        :return: List of lines without any characters at LINE_TERMINATORS.
        """
        return re.split(b'|'.join(arg_0.LINE_TERMINATORS), arg_1)

Split data into lines where lines are separated by LINE_TERMINATORS .


def Func(arg_0):
    """
    Returns a randomly generated permanence value for a synapses that is to be
    initialized in a non-connected state.
    """
    arg_1 = arg_0._synPermConnected * arg_0._random.getReal64()

    # Ensure we don't have too much unnecessary precision. A full 64 bits of
    # precision causes numerical stability issues across platforms and across
    # implementations
    arg_1 = int(arg_1*100000) / 100000.0
    return arg_1

Returns a randomly generated permanence value for a synapses that is to be initialized in a non - connected state .


def Func(arg_0, arg_1, arg_2):
        """
        Registering a plugin

        Params
        ------
        what: Nature of the plugin (backend, instrumentation, repo)
        obj: Instance of the plugin
        """
        # print("Registering pattern", name, pattern)
        arg_3 = arg_2.name
        arg_4 = arg_2.version
        arg_5 = arg_2.enable
        if arg_5 == 'n':
            return

        arg_6 = Key(arg_3, arg_4)
        arg_0.plugins[arg_1][arg_6] = arg_2


Half-duplex SPI read.  The specified length of bytes will be clocked
        in the MISO line and returned as a bytearray object.

def Func(arg_0, arg_1):
        """Half-duplex SPI Func.  The specified length of bytes will be clocked
        in the MISO line and returned as a bytearray object.
        """
        #check for hardware limit of FT232H and similar MPSSE chips
        if (1 > arg_1 > 65536):
            print('the FTDI chip is limited to 65536 bytes (64 KB) of input/output per command!')
            print('use for loops for larger Funcs')
            exit(1)
        # Build command to Func SPI data.
        arg_2 = 0x20 | (arg_0.lsbfirst << 3) | (arg_0.Func_clock_ve << 2)
        logger.debug('SPI Func with command {0:2X}.'.format(arg_2))
        # Compute length low and high bytes.
        # NOTE: Must actually send length minus one because the MPSSE engine
        # considers 0 a length of 1 and FFFF a length of 65536
	#force odd numbers to round up instead of down
	arg_3 = arg_1
	if arg_1 % 2 == 1:
	    arg_3 += 1
	arg_3 = arg_3/2
	#when odd length requested, get the remainder instead of the same number
	arg_4 = arg_1 - arg_3
        arg_5  = (arg_3 - 1) & 0xFF
        arg_6 = ((arg_3 - 1) >> 8) & 0xFF
        arg_0._assert_cs()
        # Send command and length.
        # Perform twice to prevent error from hardware defect/limits
        arg_0._ft232h._write(str(bytearray((arg_2, arg_5, arg_6))))
        arg_7 = arg_0._ft232h._poll_Func(arg_3)
        arg_0._ft232h._write(str(bytearray((arg_2, arg_5, arg_6))))
        arg_8 = arg_0._ft232h._poll_Func(arg_4)
        arg_0._deassert_cs()
        # Read response bytes
        return bytearray(arg_7 + arg_8)

Half - duplex SPI read . The specified length of bytes will be clocked in the MISO line and returned as a bytearray object .


(csv_filepath, json_filepath, fieldnames, ignore_first_line=True)

def Func ( arg_0 , arg_1 , arg_2 , arg_3 = True ) : import csv import json arg_4 = open ( arg_0 , 'r' ) arg_5 = open ( arg_1 , 'w' ) arg_6 = csv . DictReader ( arg_4 , arg_2 ) arg_7 = [ ] if arg_3 : next ( arg_6 ) for arg_8 in arg_6 : arg_7 . append ( arg_8 ) json . dump ( arg_7 , arg_5 ) arg_5 . close ( ) arg_4 . close ( )

def Func(arg_0, arg_1, arg_2, arg_3=True):
    """ Convert a CSV file in `csv_filepath` into a JSON file in `json_filepath`.

    Parameters
    ----------
    csv_filepath: str
        Path to the input CSV file.

    json_filepath: str
        Path to the output JSON file. Will be overwritten if exists.

    fieldnames: List[str]
        Names of the fields in the CSV file.

    ignore_first_line: bool
    """
    import csv
    import json

    arg_4 = open(arg_0, 'r')
    arg_5 = open(arg_1, 'w')

    arg_6 = csv.DictReader(arg_4, arg_2)
    arg_7 = []
    if arg_3:
        next(arg_6)

    for arg_8 in arg_6:
        arg_7.append(arg_8)

    json.dump(arg_7, arg_5)
    arg_5.close()
    arg_4.close()

Convert a CSV file in csv_filepath into a JSON file in json_filepath .


def Func ( arg_0 ) : def train ( arg_1 ) : arg_2 = [ learner ( arg_1 ) for learner in arg_0 ] def predict ( arg_3 ) : return mode ( arg_4 ( arg_3 ) for arg_4 in arg_2 ) return predict return train

def Func(arg_0):
    """Given a list of learning algorithms, have them vote."""
    def train(arg_1):
        arg_2 = [learner(arg_1) for learner in arg_0]
        def predict(arg_3):
            return mode(arg_4(arg_3) for arg_4 in arg_2)
        return predict
    return train

Given a list of learning algorithms have them vote .


def Func ( arg_0 ) : Func = arg_0 . _json_data . get ( 'created' ) if Func : return WebexTeamsDateTime . strptime ( Func ) else : return None

def Func(arg_0):
        """Creation date and time in ISO8601 format."""
        Func = arg_0._json_data.get('created')
        if Func:
            return WebexTeamsDateTime.strptime(Func)
        else:
            return None

Creation date and time in ISO8601 format .


def Func(arg_0, arg_1):
        """
        APA102 & SK9822 support on-chip brightness control, allowing greater
        color depth.

        APA102 superimposes a 440Hz PWM on the 19kHz base PWM to control
        brightness. SK9822 uses a base 4.7kHz PWM but controls brightness with a
        variable current source.

        Because of this SK9822 will have much less flicker at lower levels.
        Either way, this option is better and faster than scaling in
        BiblioPixel.
        """
        # bitshift to scale from 8 bit to 5
        arg_0._chipset_brightness = (arg_1 >> 3)
        arg_0._brightness_list = [0xE0 + arg_0._chipset_brightness] * arg_0.numLEDs
        arg_0._packet[arg_0._start_frame:arg_0._pixel_stop:4] = (
            arg_0._brightness_list)

APA102 & SK9822 support on - chip brightness control allowing greater color depth .


def
Func
(
)
:
arg_0
=
core
.
run
(
"virsh net-list --all"
)
arg_1
=
{
}
arg_2
=
[
n
.
strip
(
)
for
n
in
arg_0
.
splitlines
(
)
[
2
:
]
]
for
arg_3
in
arg_2
:
if
not
arg_3
:
continue
arg_4
,
arg_5
,
arg_6
=
arg_3
.
split
(
)
arg_1
[
arg_4
]
=
arg_5
==
"active"
return
arg_1

def Func():
    """Return a dictionary of network name to active status bools.

        Sample virsh net-list output::

    Name                 State      Autostart
    -----------------------------------------
    default              active     yes
    juju-test            inactive   no
    foobar               inactive   no

    Parsing the above would return::
    {"default": True, "juju-test": False, "foobar": False}

    See: http://goo.gl/kXwfC
    """
    arg_0 = core.run("virsh net-list --all")
    arg_1 = {}

    # Take the header off and normalize whitespace.
    arg_2 = [n.strip() for n in arg_0.splitlines()[2:]]
    for arg_3 in arg_2:
        if not arg_3:
            continue
        arg_4, arg_5, arg_6 = arg_3.split()
        arg_1[arg_4] = arg_5 == "active"
    return arg_1

Return a dictionary of network name to active status bools .


def
Func
(
arg_0
,
arg_1
=
"("
,
arg_2
=
")"
)
:
arg_3
=
pyparsing
.
Word
(
pyparsing
.
alphas
+
"_"
,
pyparsing
.
alphanums
+
"_"
)
arg_4
=
pyparsing
.
Literal
(
"."
)
arg_5
=
pyparsing
.
CaselessLiteral
(
"E"
)
arg_6
=
pyparsing
.
Combine
(
pyparsing
.
Word
(
"+-"
+
pyparsing
.
nums
,
pyparsing
.
nums
)
+
pyparsing
.
Optional
(
arg_4
+
pyparsing
.
Optional
(
pyparsing
.
Word
(
pyparsing
.
nums
)
)
)
+
pyparsing
.
Optional
(
arg_5
+
pyparsing
.
Word
(
"+-"
+
pyparsing
.
nums
,
pyparsing
.
nums
)
)
)
arg_7
=
arg_3
|
arg_6
arg_8
=
[
(
pyparsing
.
Literal
(
"**"
)
,
2
,
pyparsing
.
opAssoc
.
RIGHT
)
,
(
pyparsing
.
oneOf
(
"+ - ~"
)
,
1
,
pyparsing
.
opAssoc
.
RIGHT
)
,
(
pyparsing
.
oneOf
(
"* / // %"
)
,
2
,
pyparsing
.
opAssoc
.
LEFT
)
,
(
pyparsing
.
oneOf
(
"+ -"
)
,
2
,
pyparsing
.
opAssoc
.
LEFT
)
,
(
pyparsing
.
oneOf
(
"<< >>"
)
,
2
,
pyparsing
.
opAssoc
.
LEFT
)
,
(
pyparsing
.
Literal
(
"&"
)
,
2
,
pyparsing
.
opAssoc
.
LEFT
)
,
(
pyparsing
.
Literal
(
"^"
)
,
2
,
pyparsing
.
opAssoc
.
LEFT
)
,
(
pyparsing
.
Literal
(
"|"
)
,
2
,
pyparsing
.
opAssoc
.
LEFT
)
,
]
arg_9
=
pyparsing
.
infixNotation
(
arg_7
,
arg_8
,
lpar
=
pyparsing
.
Suppress
(
arg_1
)
,
rpar
=
pyparsing
.
Suppress
(
arg_2
)
)
return
arg_9
.
parseString
(
arg_0
)
[
0
]

def Func(arg_0, arg_1="(", arg_2=")"):
    """Parse mathematical expression using PyParsing."""
    arg_3 = pyparsing.Word(pyparsing.alphas + "_", pyparsing.alphanums + "_")
    arg_4 = pyparsing.Literal(".")
    arg_5 = pyparsing.CaselessLiteral("E")
    arg_6 = pyparsing.Combine(
        pyparsing.Word("+-" + pyparsing.nums, pyparsing.nums)
        + pyparsing.Optional(arg_4 + pyparsing.Optional(pyparsing.Word(pyparsing.nums)))
        + pyparsing.Optional(
            arg_5 + pyparsing.Word("+-" + pyparsing.nums, pyparsing.nums)
        )
    )
    arg_7 = arg_3 | arg_6
    arg_8 = [
        (pyparsing.Literal("**"), 2, pyparsing.opAssoc.RIGHT),
        (pyparsing.oneOf("+ - ~"), 1, pyparsing.opAssoc.RIGHT),
        (pyparsing.oneOf("* / // %"), 2, pyparsing.opAssoc.LEFT),
        (pyparsing.oneOf("+ -"), 2, pyparsing.opAssoc.LEFT),
        (pyparsing.oneOf("<< >>"), 2, pyparsing.opAssoc.LEFT),
        (pyparsing.Literal("&"), 2, pyparsing.opAssoc.LEFT),
        (pyparsing.Literal("^"), 2, pyparsing.opAssoc.LEFT),
        (pyparsing.Literal("|"), 2, pyparsing.opAssoc.LEFT),
    ]
    # Get functions
    arg_9 = pyparsing.infixNotation(
        arg_7, arg_8, lpar=pyparsing.Suppress(arg_1), rpar=pyparsing.Suppress(arg_2)
    )
    return arg_9.parseString(arg_0)[0]

Parse mathematical expression using PyParsing .


def Func ( arg_0 , arg_1 ) : arg_0 = asarray ( arg_0 , 'int' ) arg_2 = zeros ( arg_1 , dtype = bool ) arg_2 [ arg_0 ] = True return arg_2

def Func(arg_0, arg_1):
        """
        Obtain a binary mask by setting a subset of entries to true.

        Parameters
        ----------
        inds : array-like
            Which indices to set as true.

        n : int
            The length of the target mask.
        """
        arg_0 = asarray(arg_0, 'int')
        arg_2 = zeros(arg_1, dtype=bool)
        arg_2[arg_0] = True
        return arg_2

Obtain a binary mask by setting a subset of entries to true .


def
Func
(
)
:
arg_0
=
int
(
os
.
getenv
(
DEVSHELL_ENV
,
0
)
)
if
arg_0
==
0
:
raise
NoDevshellServer
(
)
arg_1
=
socket
.
socket
(
)
arg_1
.
connect
(
(
'localhost'
,
arg_0
)
)
arg_2
=
CREDENTIAL_INFO_REQUEST_JSON
arg_3
=
'{0}\n{1}'
.
format
(
len
(
arg_2
)
,
arg_2
)
arg_1
.
sendall
(
_helpers
.
_to_bytes
(
arg_3
,
encoding
=
'utf-8'
)
)
arg_4
=
arg_1
.
recv
(
6
)
.
decode
(
)
if
'\n'
not
in
arg_4
:
raise
CommunicationError
(
'saw no newline in the first 6 bytes'
)
arg_5
,
arg_6
=
arg_4
.
split
(
'\n'
,
1
)
arg_7
=
int
(
arg_5
)
len
(
arg_6
)
if
arg_7
>
0
:
arg_6
+=
arg_1
.
recv
(
arg_7
,
socket
.
MSG_WAITALL
)
.
decode
(
)
return
CredentialInfoResponse
(
arg_6
)

def Func():
    """Communicate with the Developer Shell server socket."""

    arg_0 = int(os.getenv(DEVSHELL_ENV, 0))
    if arg_0 == 0:
        raise NoDevshellServer()

    arg_1 = socket.socket()
    arg_1.connect(('localhost', arg_0))

    arg_2 = CREDENTIAL_INFO_REQUEST_JSON
    arg_3 = '{0}\n{1}'.format(len(arg_2), arg_2)
    arg_1.sendall(_helpers._to_bytes(arg_3, encoding='utf-8'))

    arg_4 = arg_1.recv(6).decode()
    if '\n' not in arg_4:
        raise CommunicationError('saw no newline in the first 6 bytes')
    arg_5, arg_6 = arg_4.split('\n', 1)
    arg_7 = int(arg_5) - len(arg_6)
    if arg_7 > 0:
        arg_6 += arg_1.recv(arg_7, socket.MSG_WAITALL).decode()

    return CredentialInfoResponse(arg_6)

Communicate with the Developer Shell server socket .


def Func(arg_0):
        """Get authorization object representing status of authentication."""
        arg_1 = arg_0.authorization_class()
        arg_2 = arg_0.Func_header()
        if not arg_2 or not arg_2.split:
            return arg_1
        arg_2 = arg_2.split()
        if len(arg_2) > 1 and arg_2[0] == 'Bearer':
            arg_1.is_oauth = True
            arg_4 = arg_2[1]
            arg_0.validate_access_token(arg_4, arg_1)
            if not arg_1.is_valid:
                arg_1.error = 'access_denied'
        return arg_1

Get authorization object representing status of authentication .