function_name stringlengths 1 63 | docstring stringlengths 50 5.89k | masked_code stringlengths 50 882k | implementation stringlengths 169 12.9k | start_line int32 1 14.6k | end_line int32 16 14.6k | file_content stringlengths 274 882k |
|---|---|---|---|---|---|---|
__getattribute__ | When getting a filter attribute, looks for the corresponding filter
state and returns that instead of the filter object. If none is found,
looks for the default value on the filter object. If that's not found
either, then returns none. | from django import forms
from django.http import QueryDict
from django.forms.formsets import formset_factory
from abc import ABCMeta, abstractmethod
from collections import OrderedDict
from datetime import date
import itertools
import re
from fields import SubmitButtonField, SubmitButtonWidget
class Filter(object):
... | def __getattribute__(self, name):
"""
When getting a filter attribute, looks for the corresponding filter
state and returns that instead of the filter object. If none is found,
looks for the default value on the filter object. If that's not found
either, then returns none.
... | 170 | 191 | from django import forms
from django.http import QueryDict
from django.forms.formsets import formset_factory
from abc import ABCMeta, abstractmethod
from collections import OrderedDict
from datetime import date
import itertools
import re
from fields import SubmitButtonField, SubmitButtonWidget
class Filter(object):
... |
mailman_add | Add a Satchmo contact to a mailman mailing list.
Parameters:
- `Contact`: A Satchmo Contact
- `listname`: the Mailman listname, defaulting to whatever you have set in settings.NEWSLETTER_NAME
- `send_welcome_msg`: True or False, defaulting to the list default
- `admin_notify`: True of False, defaulting... | """A Mailman newsletter subscription interface.
To use this plugin, enable the newsletter module and set the newsletter module and name settings
in the admin settings page.
"""
from django.utils.translation import ugettext as _
from Mailman import MailList, Errors
from models import Subscription
from satchmo.configur... | def mailman_add(contact, listname=None, send_welcome_msg=None, admin_notify=None):
"""Add a Satchmo contact to a mailman mailing list.
Parameters:
- `Contact`: A Satchmo Contact
- `listname`: the Mailman listname, defaulting to whatever you have set in settings.NEWSLETTER_NAME
- `send_w... | 66 | 110 | """A Mailman newsletter subscription interface.
To use this plugin, enable the newsletter module and set the newsletter module and name settings
in the admin settings page.
"""
from django.utils.translation import ugettext as _
from Mailman import MailList, Errors
from models import Subscription
from satchmo.configur... |
test | Runs an object detection test configuration
This runs an object detection test configuration. This involves
1. Download and build a model architecture (or use cached).
2. Optimize the model architecrue
3. Benchmark the optimized model against a dataset
4. (optional) Run assertions to check the benchmark output
The ... | # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://w... | def test(test_config_path):
"""Runs an object detection test configuration
This runs an object detection test configuration. This involves
1. Download and build a model architecture (or use cached).
2. Optimize the model architecrue
3. Benchmark the optimized model against a dataset
4... | 23 | 95 | # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://w... |
write_input | Get the string representation of the main input file and write it.
Also writes the data file if the lammps_data attribute is set.
Args:
input_filename (string): name of the input file
data_filename (string): override the data file name with this | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, print_function, unicode_literals, absolute_import
"""
This module implements classes for reading and generating Lammps inputset.
For the ease of management we divide LAMMPS in... | def write_input(self, input_filename, data_filename=None):
"""
Get the string representation of the main input file and write it.
Also writes the data file if the lammps_data attribute is set.
Args:
input_filename (string): name of the input file
data_filenam... | 62 | 79 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, print_function, unicode_literals, absolute_import
"""
This module implements classes for reading and generating Lammps inputset.
For the ease of management we divide LAMMPS in... |
transforms | :param item: sample = deepcopy(self.items[index])
:param cfg: cfg
:return:
eval() transform str to list, dict, tuple. Here is a series of the transform methods in turn. | from .hflip import hflip
from .resize import resize
from .pad import pad
from .random_crop import random_crop
from .to_tensor import to_tensor
from .random_erasing import random_erasing
from .random_sized_rect_crop import random_sized_rect_crop
# MASKED: transforms function (lines 10-30) | def transforms(item, cfg, mode):
"""
:param item: sample = deepcopy(self.items[index])
:param cfg: cfg
:return:
eval() transform str to list, dict, tuple. Here is a series of the transform methods in turn.
"""
transforms_dataset_factory = {
'train': cfg.dataset.train,
'test'... | 10 | 30 | from .hflip import hflip
from .resize import resize
from .pad import pad
from .random_crop import random_crop
from .to_tensor import to_tensor
from .random_erasing import random_erasing
from .random_sized_rect_crop import random_sized_rect_crop
def transforms(item, cfg, mode):
"""
:param item: sample = deepco... |
load_image_from_file | Given a filename, try to open the file. If failed, return None.
Args:
filename: location of the image file
shape: the shape of the image file to be scaled
Returns:
the image if succeeds, None if fails.
Rasies:
exception if the image was not the right shape. | """
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
di... | def load_image_from_file(self, filename, shape):
"""Given a filename, try to open the file. If failed, return None.
Args:
filename: location of the image file
shape: the shape of the image file to be scaled
Returns:
the image if succeeds, None if fails.
Rasies:
exception if ... | 107 | 137 | """
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
di... |
get | Get the resulted command-line options.
Decode and merge specified command-line options with the default one.
Returns
-------
dict
Decoded and verified config value. | # Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... | @classmethod
def get(self):
"""
Get the resulted command-line options.
Decode and merge specified command-line options with the default one.
Returns
-------
dict
Decoded and verified config value.
"""
custom_parameters = super().get()... | 387 | 404 | # Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... |
bulk | Used by the monitoring features to send monitoring data.
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.10/monitor-elasticsearch-cluster.html>`_
.. warning::
This API is **experimental** so may include breaking changes
or be removed in a future version
:arg body: The operation definition and da... | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use ... | @query_params("interval", "system_api_version", "system_id")
def bulk(self, body, doc_type=None, params=None, headers=None):
"""
Used by the monitoring features to send monitoring data.
`<https://www.elastic.co/guide/en/elasticsearch/reference/7.10/monitor-elasticsearch-cluster.html>`_
... | 22 | 53 | # Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use ... |
__init__ | Create a new Polar Axes for a polar plot.
The following optional kwargs are supported:
- *resolution*: The number of points of interpolation between
each pair of data points. Set to 1 to disable
interpolation. | import math
import warnings
import numpy as np
import matplotlib
rcParams = matplotlib.rcParams
from matplotlib.axes import Axes
import matplotlib.axis as maxis
from matplotlib import cbook
from matplotlib import docstring
from matplotlib.patches import Circle
from matplotlib.path import Path
from matplotlib.ticker i... | def __init__(self, *args, **kwargs):
"""
Create a new Polar Axes for a polar plot.
The following optional kwargs are supported:
- *resolution*: The number of points of interpolation between
each pair of data points. Set to 1 to disable
interpolation.
... | 221 | 240 | import math
import warnings
import numpy as np
import matplotlib
rcParams = matplotlib.rcParams
from matplotlib.axes import Axes
import matplotlib.axis as maxis
from matplotlib import cbook
from matplotlib import docstring
from matplotlib.patches import Circle
from matplotlib.path import Path
from matplotlib.ticker i... |
__init__ | *limits* is the view limit of the data. The only part of
its bounds that is used is ymax (for the radius maximum).
The theta range is always fixed to (0, 2pi). | import math
import warnings
import numpy as np
import matplotlib
rcParams = matplotlib.rcParams
from matplotlib.axes import Axes
import matplotlib.axis as maxis
from matplotlib import cbook
from matplotlib import docstring
from matplotlib.patches import Circle
from matplotlib.path import Path
from matplotlib.ticker i... | def __init__(self, scale_transform, limits):
"""
*limits* is the view limit of the data. The only part of
its bounds that is used is ymax (for the radius maximum).
The theta range is always fixed to (0, 2pi).
"""
Affine2DBase.__init__(self... | 101 | 111 | import math
import warnings
import numpy as np
import matplotlib
rcParams = matplotlib.rcParams
from matplotlib.axes import Axes
import matplotlib.axis as maxis
from matplotlib import cbook
from matplotlib import docstring
from matplotlib.patches import Circle
from matplotlib.path import Path
from matplotlib.ticker i... |
cire | Cross-iteration redundancies elimination.
Parameters
----------
cluster : Cluster
Input Cluster, subject of the optimization pass.
mode : str
The transformation mode. Accepted: ['invariants', 'sops'].
* 'invariants' is for sub-expressions that are invariant w.r.t. one or
more Dimensions.
* 'sops'... | from collections import OrderedDict, defaultdict, namedtuple
from functools import partial
from itertools import groupby
from cached_property import cached_property
import numpy as np
from devito.ir import (SEQUENTIAL, PARALLEL, PARALLEL_IF_PVT, ROUNDABLE, DataSpace,
Forward, IterationInstance,... | @timed_pass(name='cire')
def cire(clusters, mode, sregistry, options, platform):
"""
Cross-iteration redundancies elimination.
Parameters
----------
cluster : Cluster
Input Cluster, subject of the optimization pass.
mode : str
The transformation mode. Accepted: ['invariants', 's... | 22 | 109 | from collections import OrderedDict, defaultdict, namedtuple
from functools import partial
from itertools import groupby
from cached_property import cached_property
import numpy as np
from devito.ir import (SEQUENTIAL, PARALLEL, PARALLEL_IF_PVT, ROUNDABLE, DataSpace,
Forward, IterationInstance,... |
translated | True if ``self`` is translated w.r.t. ``other``, False otherwise.
Examples
--------
Two candidates are translated if their bases are the same and
their offsets are pairwise translated.
c := A[i,j] op A[i,j+1] -> Toffsets = {i: [0,0], j: [0,1]}
u := A[i+1,j] op A[i+1,j+1] -> Toffsets = {i: [1,1], j: [0,1]}
Then `... | from collections import OrderedDict, defaultdict, namedtuple
from functools import partial
from itertools import groupby
from cached_property import cached_property
import numpy as np
from devito.ir import (SEQUENTIAL, PARALLEL, PARALLEL_IF_PVT, ROUNDABLE, DataSpace,
Forward, IterationInstance,... | def translated(self, other):
"""
True if ``self`` is translated w.r.t. ``other``, False otherwise.
Examples
--------
Two candidates are translated if their bases are the same and
their offsets are pairwise translated.
c := A[i,j] op A[i,j+1] -> Toffsets ... | 895 | 927 | from collections import OrderedDict, defaultdict, namedtuple
from functools import partial
from itertools import groupby
from cached_property import cached_property
import numpy as np
from devito.ir import (SEQUENTIAL, PARALLEL, PARALLEL_IF_PVT, ROUNDABLE, DataSpace,
Forward, IterationInstance,... |
create_working_dir | Creates a directory in `basedir` with a prefix of `dirprefix`.
The directory will have a random 5 character string appended to `dirprefix`.
Returns the path to the working directory.
:rtype : str
:param basedir: str, the directory in which to create the working directory
:param dirprefix: str, prefix to pre... | #!/usr/bin/env python
import os
import sys
import platform
import tempfile
import urllib2
import shutil
import boto
from boto.exception import BotoClientError
def merge_dicts(a, b):
"""
Merge two dictionaries. If there is a key collision, `b` overrides `a`.
:param a: Dictionary of default settings
:param ... | def create_working_dir(basedir, dirprefix):
"""
Creates a directory in `basedir` with a prefix of `dirprefix`.
The directory will have a random 5 character string appended to `dirprefix`.
Returns the path to the working directory.
:rtype : str
:param basedir: str, the directory in which to create the workin... | 131 | 148 | #!/usr/bin/env python
import os
import sys
import platform
import tempfile
import urllib2
import shutil
import boto
from boto.exception import BotoClientError
def merge_dicts(a, b):
"""
Merge two dictionaries. If there is a key collision, `b` overrides `a`.
:param a: Dictionary of default settings
:param ... |
get_system_params | Returns a dictionary of OS platform-specific parameters.
:param system: str, the system type as returned by `platform.system`
:rtype : dict
| #!/usr/bin/env python
import os
import sys
import platform
import tempfile
import urllib2
import shutil
import boto
from boto.exception import BotoClientError
def merge_dicts(a, b):
"""
Merge two dictionaries. If there is a key collision, `b` overrides `a`.
:param a: Dictionary of default settings
:param ... | def get_system_params(system):
"""
Returns a dictionary of OS platform-specific parameters.
:param system: str, the system type as returned by `platform.system`
:rtype : dict
"""
a = {}
workingdirprefix = 'systemprep-'
if 'Linux' in system:
tempdir = '/usr/tmp/'
a['pathsepar... | 151 | 179 | #!/usr/bin/env python
import os
import sys
import platform
import tempfile
import urllib2
import shutil
import boto
from boto.exception import BotoClientError
def merge_dicts(a, b):
"""
Merge two dictionaries. If there is a key collision, `b` overrides `a`.
:param a: Dictionary of default settings
:param ... |
score | Log probability for a given data `x`.
Attributes
----------
x : ndarray
Data to evaluate.
%(_doc_default_callparams)s
Returns
-------
log_prob : float
The log probability of the data. | from __future__ import division, print_function, absolute_import
# noinspection PyUnresolvedReferences
from six.moves import range
import numpy as np
from scipy.misc import doccer
from ...stats import nonuniform
from ...auxiliary.array import normalize, nunique, accum
__all__ = ['markov']
_doc_default_callparams =... | def score(self, x, startprob, transmat):
"""Log probability for a given data `x`.
Attributes
----------
x : ndarray
Data to evaluate.
%(_doc_default_callparams)s
Returns
-------
log_prob : float
The log probability of the data... | 91 | 117 | from __future__ import division, print_function, absolute_import
# noinspection PyUnresolvedReferences
from six.moves import range
import numpy as np
from scipy.misc import doccer
from ...stats import nonuniform
from ...auxiliary.array import normalize, nunique, accum
__all__ = ['markov']
_doc_default_callparams =... |
getInputSpecification | Method to get a reference to a class that specifies the input data for
class cls.
@ Out, inputSpecification, InputData.ParameterInput, class to use for
specifying input of cls. |
# Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | @classmethod
def getInputSpecification(cls):
"""
Method to get a reference to a class that specifies the input data for
class cls.
@ Out, inputSpecification, InputData.ParameterInput, class to use for
specifying input of cls.
"""
specs = super(PolynomialRegression, cls).getInpu... | 30 | 43 |
# Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
handleInput | Reads user inputs into this object.
@ In, inp, InputData.InputParams, input specifications
@ Out, settings, dict, initialization settings for this algorithm |
# Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | def handleInput(self, spec):
"""
Reads user inputs into this object.
@ In, inp, InputData.InputParams, input specifications
@ Out, settings, dict, initialization settings for this algorithm
"""
settings = super().handleInput(spec)
settings['degree'] = spec.findFirst('degree').value
... | 58 | 66 |
# Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
characterize | Determines the charactistics of the signal based on this algorithm.
@ In, signal, np.ndarray, time series with dims [time, target]
@ In, pivot, np.1darray, time-like parameter values
@ In, targets, list(str), names of targets in same order as signal
@ In, settings, dict, additional settings specific to this algorithm
@... |
# Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... | def characterize(self, signal, pivot, targets, settings):
"""
Determines the charactistics of the signal based on this algorithm.
@ In, signal, np.ndarray, time series with dims [time, target]
@ In, pivot, np.1darray, time-like parameter values
@ In, targets, list(str), names of targets in... | 68 | 92 |
# Copyright 2017 Battelle Energy Alliance, LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
__init__ | The set of arguments for constructing a PrivateEndpointConnection resource.
:param pulumi.Input[str] account_name: Cosmos DB database account name.
:param pulumi.Input[str] resource_group_name: The name of the resource group. The name is case insensitive.
:param pulumi.Input[str] group_id: Group id of the private endpo... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | def __init__(__self__, *,
account_name: pulumi.Input[str],
resource_group_name: pulumi.Input[str],
group_id: Optional[pulumi.Input[str]] = None,
private_endpoint: Optional[pulumi.Input['PrivateEndpointPropertyArgs']] = None,
privat... | 17 | 46 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
get | Get an existing PrivateEndpointConnection resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | @staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'PrivateEndpointConnection':
"""
Get an existing PrivateEndpointConnection resource's state with the given name, id, and optional extra
properties us... | 223 | 245 | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
__init__ | The WOQLClient constructor.
Parameters
----------
server_url : str
URL of the server that this client will connect to.
\**kwargs
Extra configuration options | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def __init__(self, server_url: str, **kwargs) -> None:
r"""The WOQLClient constructor.
Parameters
----------
server_url : str
URL of the server that this client will connect to.
\**kwargs
Extra configuration options
"""
self.server_ur... | 157 | 178 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
connect | Connect to a Terminus server at the given URI with an API key.
Stores the connection settings and necessary meta-data for the connected server. You need to connect before most database operations.
Parameters
----------
team: str
Name of the team, default to be "admin"
db: optional, str
Name of the database co... | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def connect(
self,
team: str = "admin",
db: Optional[str] = None,
remote_auth: str = None,
use_token: bool = False,
jwt_token: Optional[str] = None,
api_token: Optional[str] = None,
key: str = "root",
user: str = "admin",
branch: str = ... | 263 | 359 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
set_db | Set the connection to another database. This will reset the connection.
Parameters
----------
dbid : str
Database identifer to set in the config.
team : str
Team identifer to set in the config. If not passed in, it will use the current one.
Returns
-------
str
The current database identifier.
Examples
--... | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def set_db(self, dbid: str, team: Optional[str] = None) -> str:
"""Set the connection to another database. This will reset the connection.
Parameters
----------
dbid : str
Database identifer to set in the config.
team : str
Team identifer to set in th... | 528 | 563 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
resource | Create a resource identifier string based on the current config.
Parameters
----------
ttype : ResourceType
Type of resource.
val : str, optional
Branch or commit identifier.
Returns
-------
str
The constructed resource string.
Examples
--------
>>> client = WOQLClient("https://127.0.0.1:6363")
>>> clien... | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def resource(self, ttype: ResourceType, val: Optional[str] = None) -> str:
"""Create a resource identifier string based on the current config.
Parameters
----------
ttype : ResourceType
Type of resource.
val : str, optional
Branch or commit identifier... | 565 | 605 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
create_database | Create a TerminusDB database by posting
a terminus:Database document to the Terminus Server.
Parameters
----------
dbid : str
Unique identifier of the database.
team : str, optional
ID of the Team in which to create the DB (defaults to 'admin')
label : str, optional
Database name.
description : str, option... | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def create_database(
self,
dbid: str,
team: Optional[str] = None,
label: Optional[str] = None,
description: Optional[str] = None,
prefixes: Optional[dict] = None,
include_schema: bool = True,
) -> None:
"""Create a TerminusDB database by posting
... | 617 | 689 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
query_document | Retrieves all documents that match a given document template
Parameters
----------
document_template : dict
Template for the document that is being retrived
graph_type : str, optional
Graph type, either "instance" or "schema".
as_list: bool
If the result returned as list rather than an iterator.
get_data_v... | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def query_document(
self,
document_template: dict,
graph_type: str = "instance",
skip: int = 0,
count: Optional[int] = None,
as_list: bool = False,
get_data_version: bool = False,
**kwargs,
) -> Union[Iterable, list]:
"""Retrieves all docum... | 852 | 917 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
get_document | Retrieves the document of the iri_id
Parameters
----------
iri_id : str
Iri id for the docuemnt that is retriving
graph_type : str, optional
Graph type, either "instance" or "schema".
get_data_version: bool
If the data version of the document(s) should be obtained. If True, the method return the result and... | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def get_document(
self,
iri_id: str,
graph_type: str = "instance",
get_data_version: bool = False,
**kwargs,
) -> dict:
"""Retrieves the document of the iri_id
Parameters
----------
iri_id : str
Iri id for the docuemnt that is ... | 919 | 968 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
get_documents_by_type | Retrieves the documents by type
Parameters
----------
doc_type : str
Specific type for the docuemnts that is retriving
graph_type : str, optional
Graph type, either "instance" or "schema".
skip: int
The starting posiion of the returning results, default to be 0
count: int or None
The maximum number of ... | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def get_documents_by_type(
self,
doc_type: str,
graph_type: str = "instance",
skip: int = 0,
count: Optional[int] = None,
as_list: bool = False,
get_data_version=False,
**kwargs,
) -> Union[Iterable, list]:
"""Retrieves the documents by typ... | 970 | 1,039 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
get_all_documents | Retrieves all avalibale the documents
Parameters
----------
graph_type : str, optional
Graph type, either "instance" or "schema".
skip: int
The starting posiion of the returning results, default to be 0
count: int or None
The maximum number of returned result, if None (default) it will return all of the av... | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def get_all_documents(
self,
graph_type: str = "instance",
skip: int = 0,
count: Optional[int] = None,
as_list: bool = False,
get_data_version: bool = False,
**kwargs,
) -> Union[Iterable, list, tuple]:
"""Retrieves all avalibale the documents
... | 1,041 | 1,107 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
has_doc | Check if a certain document exist in a database
Parameters
----------
doc_id: str
Id of document to be checked.
graph_type : str
Graph type, either "instance" or "schema".
returns
-------
Bool
if the document exist | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def has_doc(self, doc_id: str, graph_type: str = "instance") -> bool:
"""Check if a certain document exist in a database
Parameters
----------
doc_id: str
Id of document to be checked.
graph_type : str
Graph type, either "instance" or "schema".
... | 1,450 | 1,469 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
get_class_frame | Get the frame of the class of class_name. Provide information about all the avaliable properties of that class.
Parameters
----------
class_name: str
Name of the class
returns
-------
dict
Dictionary containing information | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def get_class_frame(self, class_name):
"""Get the frame of the class of class_name. Provide information about all the avaliable properties of that class.
Parameters
----------
class_name: str
Name of the class
returns
-------
dict
Dic... | 1,471 | 1,492 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
reset | Reset the current branch HEAD to the specified commit path. If `soft` is not True, it will be a hard reset, meaning reset to that commit in the backend and newer commit will be wipped out. If `soft` is True, the client will only reference to that commit and can be reset to the newest commit when done.
Raises
------
In... | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def reset(
self, commit: Optional[str] = None, soft: bool = False, use_path: bool = False
) -> None:
"""Reset the current branch HEAD to the specified commit path. If `soft` is not True, it will be a hard reset, meaning reset to that commit in the backend and newer commit will be wipped out. If ... | 1,827 | 1,882 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
squash | Squash the current branch HEAD into a commit
Raises
------
InterfaceError
if the client does not connect to a database
Notes
-----
The "remote" repo can live in the local database.
Parameters
----------
message : string
Message for the newly created squash commit
author : string
Author of the commit
rese... | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def squash(
self,
message: Optional[str] = None,
author: Optional[str] = None,
reset: bool = False,
) -> str:
"""Squash the current branch HEAD into a commit
Raises
------
InterfaceError
if the client does not connect to a database
... | 1,918 | 1,973 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
diff | Perform diff on 2 set of document(s), result in a Patch object.
Do not connect when using public API.
Returns
-------
obj
Patch object
Examples
--------
>>> client = WOQLClient("https://127.0.0.1:6363/")
>>> client.connect(user="admin", key="root", team="admin", db="some_db")
>>> result = client.diff({ "@id" : "... | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def diff(
self,
before: Union[
str,
dict,
List[dict],
"WOQLSchema", # noqa:F821
"DocumentTemplate", # noqa:F821
List["DocumentTemplate"], # noqa:F821
],
after: Union[
str,
dict,
... | 1,985 | 2,052 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
patch | Apply the patch object to the before object and return an after object. Note that this change does not commit changes to the graph.
Do not connect when using public API.
Returns
-------
dict
After object
Examples
--------
>>> client = WOQLClient("https://127.0.0.1:6363/")
>>> client.connect(user="admin", key="ro... | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def patch(
self,
before: Union[
dict,
List[dict],
"WOQLSchema", # noqa:F821
"DocumentTemplate", # noqa:F821
List["DocumentTemplate"], # noqa:F821
],
patch: Patch,
):
"""Apply the patch object to the before obj... | 2,054 | 2,105 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
clonedb | Clone a remote repository and create a local copy.
Parameters
----------
clone_source : str
The source url of the repo to be cloned.
newid : str
Identifier of the new repository to create.
Description : str, optional
Optional description about the cloned database.
Raises
------
InterfaceError
if the c... | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def clonedb(
self, clone_source: str, newid: str, description: Optional[str] = None
) -> None:
"""Clone a remote repository and create a local copy.
Parameters
----------
clone_source : str
The source url of the repo to be cloned.
newid : str
... | 2,107 | 2,143 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
_generate_commit | Pack the specified commit info into a dict format expected by the server.
Parameters
----------
msg : str
Commit message.
author : str
Commit author.
Returns
-------
dict
Formatted commit info.
Examples
--------
>>> client = WOQLClient("https://127.0.0.1:6363/")
>>> client._generate_commit("<message>", "... | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... | def _generate_commit(
self, msg: Optional[str] = None, author: Optional[str] = None
) -> dict:
"""Pack the specified commit info into a dict format expected by the server.
Parameters
----------
msg : str
Commit message.
author : str
Commit... | 2,145 | 2,174 | """woqlClient.py
WOQLClient is the Python public API for TerminusDB"""
import copy
import gzip
import json
import os
import urllib.parse as urlparse
import warnings
from collections.abc import Iterable
from datetime import datetime
from enum import Enum
from typing import Any, Dict, List, Optional, Union
import reques... |
split_array_as_array | Group ndarray into ndarray by means of reshaping
Parameters
----------
values : ndarray_like, [index.size, ...]
Returns
-------
ndarray, [groups, group_size, ...]
values grouped by key
Raises
------
AssertionError
This operation is only possible if index.uniform==True | """grouping module"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
import itertools
import numpy as np
from numpy_indexed.index import as_index
import numpy_indexed as npi
__author__ = "Eelco Hoogendoorn"
__license__ = "LGPL"
__email__ = "hoogendoorn.eelco... | def split_array_as_array(self, values):
"""Group ndarray into ndarray by means of reshaping
Parameters
----------
values : ndarray_like, [index.size, ...]
Returns
-------
ndarray, [groups, group_size, ...]
values grouped by key
Raises
... | 140 | 161 | """grouping module"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
import itertools
import numpy as np
from numpy_indexed.index import as_index
import numpy_indexed as npi
__author__ = "Eelco Hoogendoorn"
__license__ = "LGPL"
__email__ = "hoogendoorn.eelco... |
split_array_as_list | Group values as a list of arrays, or a jagged-array
Parameters
----------
values : ndarray, [keys, ...]
Returns
-------
list of length self.groups of ndarray, [key_count, ...] | """grouping module"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
import itertools
import numpy as np
from numpy_indexed.index import as_index
import numpy_indexed as npi
__author__ = "Eelco Hoogendoorn"
__license__ = "LGPL"
__email__ = "hoogendoorn.eelco... | def split_array_as_list(self, values):
"""Group values as a list of arrays, or a jagged-array
Parameters
----------
values : ndarray, [keys, ...]
Returns
-------
list of length self.groups of ndarray, [key_count, ...]
"""
values = np.asarray(... | 163 | 176 | """grouping module"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
import itertools
import numpy as np
from numpy_indexed.index import as_index
import numpy_indexed as npi
__author__ = "Eelco Hoogendoorn"
__license__ = "LGPL"
__email__ = "hoogendoorn.eelco... |
mean | compute the mean over each group
Parameters
----------
values : array_like, [keys, ...]
values to take average of per group
axis : int, optional
alternative reduction axis for values
weights : ndarray, [keys, ...], optional
weight to use for each value
dtype : output dtype
Returns
-------
unique: ndarray,... | """grouping module"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
import itertools
import numpy as np
from numpy_indexed.index import as_index
import numpy_indexed as npi
__author__ = "Eelco Hoogendoorn"
__license__ = "LGPL"
__email__ = "hoogendoorn.eelco... | def mean(self, values, axis=0, weights=None, dtype=None):
"""compute the mean over each group
Parameters
----------
values : array_like, [keys, ...]
values to take average of per group
axis : int, optional
alternative reduction axis for values
... | 258 | 288 | """grouping module"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
import itertools
import numpy as np
from numpy_indexed.index import as_index
import numpy_indexed as npi
__author__ = "Eelco Hoogendoorn"
__license__ = "LGPL"
__email__ = "hoogendoorn.eelco... |
var | compute the variance over each group
Parameters
----------
values : array_like, [keys, ...]
values to take variance of per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...]
value array, reduced over g... | """grouping module"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
import itertools
import numpy as np
from numpy_indexed.index import as_index
import numpy_indexed as npi
__author__ = "Eelco Hoogendoorn"
__license__ = "LGPL"
__email__ = "hoogendoorn.eelco... | def var(self, values, axis=0, weights=None, dtype=None):
"""compute the variance over each group
Parameters
----------
values : array_like, [keys, ...]
values to take variance of per group
axis : int, optional
alternative reduction axis for values
... | 290 | 321 | """grouping module"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
import itertools
import numpy as np
from numpy_indexed.index import as_index
import numpy_indexed as npi
__author__ = "Eelco Hoogendoorn"
__license__ = "LGPL"
__email__ = "hoogendoorn.eelco... |
median | compute the median value over each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the median of per group
axis : int, optional
alternative reduction axis for values
average : bool, optional
when average is true, the average of the two central values is taken for groups with... | """grouping module"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
import itertools
import numpy as np
from numpy_indexed.index import as_index
import numpy_indexed as npi
__author__ = "Eelco Hoogendoorn"
__license__ = "LGPL"
__email__ = "hoogendoorn.eelco... | def median(self, values, axis=0, average=True):
"""compute the median value over each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the median of per group
axis : int, optional
alternative reduction axis for values
... | 343 | 382 | """grouping module"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
import itertools
import numpy as np
from numpy_indexed.index import as_index
import numpy_indexed as npi
__author__ = "Eelco Hoogendoorn"
__license__ = "LGPL"
__email__ = "hoogendoorn.eelco... |
mode | compute the mode within each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the mode of per group
weights : array_like, [keys], float, optional
optional weight associated with each entry in values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [gr... | """grouping module"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
import itertools
import numpy as np
from numpy_indexed.index import as_index
import numpy_indexed as npi
__author__ = "Eelco Hoogendoorn"
__license__ = "LGPL"
__email__ = "hoogendoorn.eelco... | def mode(self, values, weights=None):
"""compute the mode within each group.
Parameters
----------
values : array_like, [keys, ...]
values to compute the mode of per group
weights : array_like, [keys], float, optional
optional weight associated with e... | 384 | 407 | """grouping module"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
import itertools
import numpy as np
from numpy_indexed.index import as_index
import numpy_indexed as npi
__author__ = "Eelco Hoogendoorn"
__license__ = "LGPL"
__email__ = "hoogendoorn.eelco... |
any | compute if any item evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reduction axis for values
Returns
-------
unique: ndarray, [groups]
unique keys
reduced : ndarray, [groups, ...], np.b... | """grouping module"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
import itertools
import numpy as np
from numpy_indexed.index import as_index
import numpy_indexed as npi
__author__ = "Eelco Hoogendoorn"
__license__ = "LGPL"
__email__ = "hoogendoorn.eelco... | def any(self, values, axis=0):
"""compute if any item evaluates to true in each group
Parameters
----------
values : array_like, [keys, ...]
values to take boolean predicate over per group
axis : int, optional
alternative reduction axis for values
... | 489 | 509 | """grouping module"""
from __future__ import absolute_import, division, print_function, unicode_literals
from builtins import *
import itertools
import numpy as np
from numpy_indexed.index import as_index
import numpy_indexed as npi
__author__ = "Eelco Hoogendoorn"
__license__ = "LGPL"
__email__ = "hoogendoorn.eelco... |
is_duplicate | :return boolean: Returns True if the gadgets are a semantic match. Used for non-locality gadget metrics.
Semantic match is defined as the exact same sequence of equivalent instructions. | """
Gadget class
"""
# Standard Library Imports
# Third Party Imports
# Local Imports
from static_analyzer.Instruction import Instruction
class Gadget(object):
"""
The Gadget class represents a single gadget.
"""
def __init__(self, raw_gadget):
"""
Gadget constructor
:param... | def is_duplicate(self, rhs):
"""
:return boolean: Returns True if the gadgets are a semantic match. Used for non-locality gadget metrics.
Semantic match is defined as the exact same sequence of equivalent instructions.
"""
if len(self.instructions) != len(rhs... | 291 | 303 | """
Gadget class
"""
# Standard Library Imports
# Third Party Imports
# Local Imports
from static_analyzer.Instruction import Instruction
class Gadget(object):
"""
The Gadget class represents a single gadget.
"""
def __init__(self, raw_gadget):
"""
Gadget constructor
:param... |
is_JOP_COP_dispatcher | :return boolean: Returns True if the gadget is a JOP or COP dispatcher. Defined as a gadget that begins with a
arithmetic operation on a register and ends with a branch to a deference of that register. Used
to iterate through instructions in payload. Only restrictions on the arithmetic... | """
Gadget class
"""
# Standard Library Imports
# Third Party Imports
# Local Imports
from static_analyzer.Instruction import Instruction
class Gadget(object):
"""
The Gadget class represents a single gadget.
"""
def __init__(self, raw_gadget):
"""
Gadget constructor
:param... | def is_JOP_COP_dispatcher(self):
"""
:return boolean: Returns True if the gadget is a JOP or COP dispatcher. Defined as a gadget that begins with a
arithmetic operation on a register and ends with a branch to a deference of that register. Used
to ite... | 305 | 330 | """
Gadget class
"""
# Standard Library Imports
# Third Party Imports
# Local Imports
from static_analyzer.Instruction import Instruction
class Gadget(object):
"""
The Gadget class represents a single gadget.
"""
def __init__(self, raw_gadget):
"""
Gadget constructor
:param... |
is_JOP_COP_dataloader | :return boolean: Returns True if the gadget is a JOP or COP data loader. Defined as a gadget that begins with a
pop opcode to a non-memory location, that is also not the target of the GPI. Used to pop a
necessary value off stack en masse before redirecting to the dispatcher. | """
Gadget class
"""
# Standard Library Imports
# Third Party Imports
# Local Imports
from static_analyzer.Instruction import Instruction
class Gadget(object):
"""
The Gadget class represents a single gadget.
"""
def __init__(self, raw_gadget):
"""
Gadget constructor
:param... | def is_JOP_COP_dataloader(self):
"""
:return boolean: Returns True if the gadget is a JOP or COP data loader. Defined as a gadget that begins with a
pop opcode to a non-memory location, that is also not the target of the GPI. Used to pop a
necessary ... | 332 | 345 | """
Gadget class
"""
# Standard Library Imports
# Third Party Imports
# Local Imports
from static_analyzer.Instruction import Instruction
class Gadget(object):
"""
The Gadget class represents a single gadget.
"""
def __init__(self, raw_gadget):
"""
Gadget constructor
:param... |
is_JOP_trampoline | :return boolean: Returns True if the gadget is a JOP trampoline. Defined as a gadget that begins with a
pop opcode to a non-memory location, and that ends in a dereference of that value. Used to
redirect execution to value stored in memory. | """
Gadget class
"""
# Standard Library Imports
# Third Party Imports
# Local Imports
from static_analyzer.Instruction import Instruction
class Gadget(object):
"""
The Gadget class represents a single gadget.
"""
def __init__(self, raw_gadget):
"""
Gadget constructor
:param... | def is_JOP_trampoline(self):
"""
:return boolean: Returns True if the gadget is a JOP trampoline. Defined as a gadget that begins with a
pop opcode to a non-memory location, and that ends in a dereference of that value. Used to
redirect execution to ... | 356 | 370 | """
Gadget class
"""
# Standard Library Imports
# Third Party Imports
# Local Imports
from static_analyzer.Instruction import Instruction
class Gadget(object):
"""
The Gadget class represents a single gadget.
"""
def __init__(self, raw_gadget):
"""
Gadget constructor
:param... |
is_COP_strong_trampoline | :return boolean: Returns True if the gadget is a COP strong trampoline. Defined as a gadget that begins with a
pop opcode, and contains at least one other pop operation. The last non-pop all operation must
target the call target. | """
Gadget class
"""
# Standard Library Imports
# Third Party Imports
# Local Imports
from static_analyzer.Instruction import Instruction
class Gadget(object):
"""
The Gadget class represents a single gadget.
"""
def __init__(self, raw_gadget):
"""
Gadget constructor
:param... | def is_COP_strong_trampoline(self):
"""
:return boolean: Returns True if the gadget is a COP strong trampoline. Defined as a gadget that begins with a
pop opcode, and contains at least one other pop operation. The last non-pop all operation must
targ... | 407 | 437 | """
Gadget class
"""
# Standard Library Imports
# Third Party Imports
# Local Imports
from static_analyzer.Instruction import Instruction
class Gadget(object):
"""
The Gadget class represents a single gadget.
"""
def __init__(self, raw_gadget):
"""
Gadget constructor
:param... |
is_COP_intrastack_pivot | :return boolean: Returns True if the gadget is a COP Intra-stack pivot gadget. Defined as a gadget that begins
with an additive operation on the stack pointer register. Used to move around in shellcode
during COP exploits. Only restriction on the arithmetic operation is that the second... | """
Gadget class
"""
# Standard Library Imports
# Third Party Imports
# Local Imports
from static_analyzer.Instruction import Instruction
class Gadget(object):
"""
The Gadget class represents a single gadget.
"""
def __init__(self, raw_gadget):
"""
Gadget constructor
:param... | def is_COP_intrastack_pivot(self):
"""
:return boolean: Returns True if the gadget is a COP Intra-stack pivot gadget. Defined as a gadget that begins
with an additive operation on the stack pointer register. Used to move around in shellcode
during CO... | 439 | 454 | """
Gadget class
"""
# Standard Library Imports
# Third Party Imports
# Local Imports
from static_analyzer.Instruction import Instruction
class Gadget(object):
"""
The Gadget class represents a single gadget.
"""
def __init__(self, raw_gadget):
"""
Gadget constructor
:param... |
equal_up_to_global_phase | Determine whether two objects are equal up to global phase.
If `val` implements a `_equal_up_to_global_phase_` method then it is
invoked and takes precedence over all other checks:
- For complex primitive type the magnitudes of the values are compared.
- For `val` and `other` both iterable of the same length, consec... | # Copyright 2019 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... | def equal_up_to_global_phase(val: Any, other: Any, *, atol: Union[int, float] = 1e-8) -> bool:
"""Determine whether two objects are equal up to global phase.
If `val` implements a `_equal_up_to_global_phase_` method then it is
invoked and takes precedence over all other checks:
- For complex primitive... | 49 | 100 | # Copyright 2019 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
load_checkpoint | Returns `CheckpointReader` for checkpoint found in `ckpt_dir_or_file`.
If `ckpt_dir_or_file` resolves to a directory with multiple checkpoints,
reader for the latest checkpoint is returned.
Args:
ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint
file.
Returns:
`CheckpointReader` object.... | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | @tf_export("train.load_checkpoint")
def load_checkpoint(ckpt_dir_or_file):
"""Returns `CheckpointReader` for checkpoint found in `ckpt_dir_or_file`.
If `ckpt_dir_or_file` resolves to a directory with multiple checkpoints,
reader for the latest checkpoint is returned.
Args:
ckpt_dir_or_file: Directory with... | 45 | 67 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
load_variable | Returns the tensor value of the given variable in the checkpoint.
Args:
ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint.
name: Name of the variable to return.
Returns:
A numpy `ndarray` with a copy of the value of this variable. | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | @tf_export("train.load_variable")
def load_variable(ckpt_dir_or_file, name):
"""Returns the tensor value of the given variable in the checkpoint.
Args:
ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint.
name: Name of the variable to return.
Returns:
A numpy `ndarray` with a cop... | 70 | 85 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
list_variables | Returns list of all variables in the checkpoint.
Args:
ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint.
Returns:
List of tuples `(name, shape)`. | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | @tf_export("train.list_variables")
def list_variables(ckpt_dir_or_file):
"""Returns list of all variables in the checkpoint.
Args:
ckpt_dir_or_file: Directory with checkpoints file or path to checkpoint.
Returns:
List of tuples `(name, shape)`.
"""
reader = load_checkpoint(ckpt_dir_or_file)
variab... | 88 | 104 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
wait_for_new_checkpoint | Waits until a new checkpoint file is found.
Args:
checkpoint_dir: The directory in which checkpoints are saved.
last_checkpoint: The last checkpoint path used or `None` if we're expecting
a checkpoint for the first time.
seconds_to_sleep: The number of seconds to sleep for before looking for a
new checkp... | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | def wait_for_new_checkpoint(checkpoint_dir,
last_checkpoint=None,
seconds_to_sleep=1,
timeout=None):
"""Waits until a new checkpoint file is found.
Args:
checkpoint_dir: The directory in which checkpoints are saved.
last_ch... | 107 | 135 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
checkpoints_iterator | Continuously yield new checkpoint files as they appear.
The iterator only checks for new checkpoints when control flow has been
reverted to it. This means it can miss checkpoints if your code takes longer
to run between iterations than `min_interval_secs` or the interval at which
new checkpoints are written.
The `tim... | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | @tf_export("train.checkpoints_iterator")
def checkpoints_iterator(checkpoint_dir,
min_interval_secs=0,
timeout=None,
timeout_fn=None):
"""Continuously yield new checkpoint files as they appear.
The iterator only checks for new checkpoints w... | 138 | 201 | # Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
read_const | Look up constant number *index* inside the environment body.
A borrowed reference is returned.
The returned LLVM value may have NULL value at runtime which indicates
an error at runtime. | from collections import namedtuple
import contextlib
import pickle
import hashlib
from llvmlite import ir
from llvmlite.llvmpy.core import Type, Constant
import llvmlite.llvmpy.core as lc
import ctypes
from numba import _helperlib
from numba.core import (
types, utils, config, lowering, cgutils, imputils, seriali... | def read_const(self, index):
"""
Look up constant number *index* inside the environment body.
A borrowed reference is returned.
The returned LLVM value may have NULL value at runtime which indicates
an error at runtime.
"""
assert index < len(self.env.consts)... | 130 | 155 | from collections import namedtuple
import contextlib
import pickle
import hashlib
from llvmlite import ir
from llvmlite.llvmpy.core import Type, Constant
import llvmlite.llvmpy.core as lc
import ctypes
from numba import _helperlib
from numba.core import (
types, utils, config, lowering, cgutils, imputils, seriali... |
string_as_string_and_size | Returns a tuple of ``(ok, buffer, length)``.
The ``ok`` is i1 value that is set if ok.
The ``buffer`` is a i8* of the output buffer.
The ``length`` is a i32/i64 (py_ssize_t) of the length of the buffer. | from collections import namedtuple
import contextlib
import pickle
import hashlib
from llvmlite import ir
from llvmlite.llvmpy.core import Type, Constant
import llvmlite.llvmpy.core as lc
import ctypes
from numba import _helperlib
from numba.core import (
types, utils, config, lowering, cgutils, imputils, seriali... | def string_as_string_and_size(self, strobj):
"""
Returns a tuple of ``(ok, buffer, length)``.
The ``ok`` is i1 value that is set if ok.
The ``buffer`` is a i8* of the output buffer.
The ``length`` is a i32/i64 (py_ssize_t) of the length of the buffer.
"""
p_l... | 1,075 | 1,093 | from collections import namedtuple
import contextlib
import pickle
import hashlib
from llvmlite import ir
from llvmlite.llvmpy.core import Type, Constant
import llvmlite.llvmpy.core as lc
import ctypes
from numba import _helperlib
from numba.core import (
types, utils, config, lowering, cgutils, imputils, seriali... |
string_as_string_size_and_kind | Returns a tuple of ``(ok, buffer, length, kind)``.
The ``ok`` is i1 value that is set if ok.
The ``buffer`` is a i8* of the output buffer.
The ``length`` is a i32/i64 (py_ssize_t) of the length of the buffer.
The ``kind`` is a i32 (int32) of the Unicode kind constant
The ``hash`` is a long/uint64_t (py_hash_t) of the U... | from collections import namedtuple
import contextlib
import pickle
import hashlib
from llvmlite import ir
from llvmlite.llvmpy.core import Type, Constant
import llvmlite.llvmpy.core as lc
import ctypes
from numba import _helperlib
from numba.core import (
types, utils, config, lowering, cgutils, imputils, seriali... | def string_as_string_size_and_kind(self, strobj):
"""
Returns a tuple of ``(ok, buffer, length, kind)``.
The ``ok`` is i1 value that is set if ok.
The ``buffer`` is a i8* of the output buffer.
The ``length`` is a i32/i64 (py_ssize_t) of the length of the buffer.
The `... | 1,095 | 1,123 | from collections import namedtuple
import contextlib
import pickle
import hashlib
from llvmlite import ir
from llvmlite.llvmpy.core import Type, Constant
import llvmlite.llvmpy.core as lc
import ctypes
from numba import _helperlib
from numba.core import (
types, utils, config, lowering, cgutils, imputils, seriali... |
from_native_value | Box the native value of the given Numba type. A Python object
pointer is returned (NULL if an error occurred).
This method steals any native (NRT) reference embedded in *val*. | from collections import namedtuple
import contextlib
import pickle
import hashlib
from llvmlite import ir
from llvmlite.llvmpy.core import Type, Constant
import llvmlite.llvmpy.core as lc
import ctypes
from numba import _helperlib
from numba.core import (
types, utils, config, lowering, cgutils, imputils, seriali... | def from_native_value(self, typ, val, env_manager=None):
"""
Box the native value of the given Numba type. A Python object
pointer is returned (NULL if an error occurred).
This method steals any native (NRT) reference embedded in *val*.
"""
from numba.core.boxing imp... | 1,391 | 1,402 | from collections import namedtuple
import contextlib
import pickle
import hashlib
from llvmlite import ir
from llvmlite.llvmpy.core import Type, Constant
import llvmlite.llvmpy.core as lc
import ctypes
from numba import _helperlib
from numba.core import (
types, utils, config, lowering, cgutils, imputils, seriali... |
get_package_list | Get a list of all the package names.
Parameters
----------
ftype : str
Type of package, 'RIV', 'LPF', etc.
Returns
-------
val : list of strings
Can be used to see what packages are in the model, and can then
be used with get_package to pull out individual packages. | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... | def get_package_list(self, ftype=None):
"""
Get a list of all the package names.
Parameters
----------
ftype : str
Type of package, 'RIV', 'LPF', etc.
Returns
-------
val : list of strings
Can be used to see what packages are ... | 182 | 204 | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... |
_check | Check model data for common errors.
Parameters
----------
f : str or file handle
String defining file name or file handle for summary file
of check method output. If a string is passed a file handle
is created. If f is None, check method does not write
results to a summary file. (default is None)
verbo... | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... | def _check(self, chk, level=1):
"""
Check model data for common errors.
Parameters
----------
f : str or file handle
String defining file name or file handle for summary file
of check method output. If a string is passed a file handle
is c... | 206 | 283 | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... |
add_output_file | Add an ascii or binary output file for a package
Parameters
----------
unit : int
unit number of external array
fname : str
filename of external array. (default is None)
extension : str
extension to use for the cell-by-cell file. Only used if fname
is None. (default is cbc)
binflag : bool
boolean f... | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... | def add_output_file(
self, unit, fname=None, extension="cbc", binflag=True, package=None
):
"""
Add an ascii or binary output file for a package
Parameters
----------
unit : int
unit number of external array
fname : str
filename of... | 712 | 776 | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... |
add_output | Assign an external array so that it will be listed as a DATA or
DATA(BINARY) entry in the name file. This will allow an outside
file package to refer to it.
Parameters
----------
fname : str
filename of external array
unit : int
unit number of external array
binflag : boolean
binary or not. (default is Fa... | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... | def add_output(self, fname, unit, binflag=False, package=None):
"""
Assign an external array so that it will be listed as a DATA or
DATA(BINARY) entry in the name file. This will allow an outside
file package to refer to it.
Parameters
----------
fname : str... | 778 | 819 | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... |
add_external | Assign an external array so that it will be listed as a DATA or
DATA(BINARY) entry in the name file. This will allow an outside
file package to refer to it.
Parameters
----------
fname : str
filename of external array
unit : int
unit number of external array
binflag : boolean
binary or not. (default is Fa... | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... | def add_external(self, fname, unit, binflag=False, output=False):
"""
Assign an external array so that it will be listed as a DATA or
DATA(BINARY) entry in the name file. This will allow an outside
file package to refer to it.
Parameters
----------
fname : s... | 969 | 1,010 | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... |
add_existing_package | Add an existing package to a model instance.
Parameters
----------
filename : str
the name of the file to add as a package
ptype : optional
the model package type (e.g. "lpf", "wel", etc). If None,
then the file extension of the filename arg is used
copy_to_model_ws : bool
flag to copy the package fi... | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... | def add_existing_package(
self, filename, ptype=None, copy_to_model_ws=True
):
"""
Add an existing package to a model instance.
Parameters
----------
filename : str
the name of the file to add as a package
ptype : optional
the mod... | 1,048 | 1,093 | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... |
has_package | Check if package name is in package list.
Parameters
----------
name : str
Name of the package, 'DIS', 'BAS6', etc. (case-insensitive).
Returns
-------
bool
True if package name exists, otherwise False if not found. | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... | def has_package(self, name):
"""
Check if package name is in package list.
Parameters
----------
name : str
Name of the package, 'DIS', 'BAS6', etc. (case-insensitive).
Returns
-------
bool
True if package name exists, otherwi... | 1,112 | 1,134 | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... |
get_package | Get a package.
Parameters
----------
name : str
Name of the package, 'RIV', 'LPF', etc. (case-insensitive).
Returns
-------
pp : Package object
Package object of type :class:`flopy.pakbase.Package` | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... | def get_package(self, name):
"""
Get a package.
Parameters
----------
name : str
Name of the package, 'RIV', 'LPF', etc. (case-insensitive).
Returns
-------
pp : Package object
Package object of type :class:`flopy.pakbase.Pack... | 1,136 | 1,157 | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... |
change_model_ws | Change the model work space.
Parameters
----------
new_pth : str
Location of new model workspace. If this path does not exist,
it will be created. (default is None, which will be assigned to
the present working directory).
Returns
-------
val : list of strings
Can be used to see what packages are in ... | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... | def change_model_ws(self, new_pth=None, reset_external=False):
"""
Change the model work space.
Parameters
----------
new_pth : str
Location of new model workspace. If this path does not exist,
it will be created. (default is None, which will be assi... | 1,186 | 1,240 | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... |
check | Check model data for common errors.
Parameters
----------
f : str or file handle
String defining file name or file handle for summary file
of check method output. If a string is passed a file handle
is created. If f is None, check method does not write
results to a summary file. (default is None)
verbo... | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... | def check(self, f=None, verbose=True, level=1):
"""
Check model data for common errors.
Parameters
----------
f : str or file handle
String defining file name or file handle for summary file
of check method output. If a string is passed a file handle
... | 1,485 | 1,539 | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... |
plot | Plot 2-D, 3-D, transient 2-D, and stress period list (MfList)
model input data
Parameters
----------
SelPackList : bool or list
List of of packages to plot. If SelPackList=None all packages
are plotted. (default is None)
**kwargs : dict
filename_base : str
Base file name that will be used to automa... | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... | def plot(self, SelPackList=None, **kwargs):
"""
Plot 2-D, 3-D, transient 2-D, and stress period list (MfList)
model input data
Parameters
----------
SelPackList : bool or list
List of of packages to plot. If SelPackList=None all packages
are p... | 1,541 | 1,592 | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... |
to_shapefile | Wrapper function for writing a shapefile for the model grid. If
package_names is not None, then search through the requested packages
looking for arrays that can be added to the shapefile as attributes
Parameters
----------
filename : string
name of the shapefile to write
package_names : list of package names (e.... | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... | def to_shapefile(self, filename, package_names=None, **kwargs):
"""
Wrapper function for writing a shapefile for the model grid. If
package_names is not None, then search through the requested packages
looking for arrays that can be added to the shapefile as attributes
Para... | 1,594 | 1,620 | """
mbase module
This module contains the base model class from which
all of the other models inherit from.
"""
import abc
import os
import shutil
import threading
import warnings
import queue as Queue
from datetime import datetime
from shutil import which
from subprocess import Popen, PIPE, STDOUT
import copy
im... |
dedent_docstr | Dedent all lines except first n lines
Args:
s (type): some text to dedent
n (int): number of lines to skip, (n == 0 is a normal dedent,
n == 1 is useful for whole docstrings) | # -*- coding: utf-8 -*-
"""Docstring Parsers/Formatters"""
# TODO: break this module up into smaller pieces
import sys
import re
from textwrap import dedent
from collections import OrderedDict
from itertools import islice
from .autodocstring_logging import logger
PY3k = sys.version_info[0] == 3
if PY3k:
string... | def dedent_docstr(s, n=1):
"""Dedent all lines except first n lines
Args:
s (type): some text to dedent
n (int): number of lines to skip, (n == 0 is a normal dedent,
n == 1 is useful for whole docstrings)
"""
lines = s.splitlines(keepends=True)
if lines:
first_n_... | 63 | 77 | # -*- coding: utf-8 -*-
"""Docstring Parsers/Formatters"""
# TODO: break this module up into smaller pieces
import sys
import re
from textwrap import dedent
from collections import OrderedDict
from itertools import islice
from .autodocstring_logging import logger
PY3k = sys.version_info[0] == 3
if PY3k:
string... |
indent_docstr | Add common indentation to all lines except first
Args:
s (str): docstring starting at indentation level 0
indent (str): text used for indentation, in practice
this will be the level of the declaration + 1
n (int): don't indent first n lines
trim (bool): trim whitespace (' ') out of blan... | # -*- coding: utf-8 -*-
"""Docstring Parsers/Formatters"""
# TODO: break this module up into smaller pieces
import sys
import re
from textwrap import dedent
from collections import OrderedDict
from itertools import islice
from .autodocstring_logging import logger
PY3k = sys.version_info[0] == 3
if PY3k:
string... | def indent_docstr(s, indent, n=1, trim=True):
"""Add common indentation to all lines except first
Args:
s (str): docstring starting at indentation level 0
indent (str): text used for indentation, in practice
this will be the level of the declaration + 1
n (int): don't indent... | 96 | 115 | # -*- coding: utf-8 -*-
"""Docstring Parsers/Formatters"""
# TODO: break this module up into smaller pieces
import sys
import re
from textwrap import dedent
from collections import OrderedDict
from itertools import islice
from .autodocstring_logging import logger
PY3k = sys.version_info[0] == 3
if PY3k:
string... |
__init__ | Args:
names (list): list of names
types (str): string describing data types
description (str): description text
tag (int): some meaningful index? not fleshed out yet
descr_only (bool): only description is useful
**kwargs: Description | # -*- coding: utf-8 -*-
"""Docstring Parsers/Formatters"""
# TODO: break this module up into smaller pieces
import sys
import re
from textwrap import dedent
from collections import OrderedDict
from itertools import islice
from .autodocstring_logging import logger
PY3k = sys.version_info[0] == 3
if PY3k:
string... | def __init__(self, names, types, description, tag=None, descr_only=False,
annotated=False, **kwargs):
"""
Args:
names (list): list of names
types (str): string describing data types
description (str): description text
tag (int): some m... | 166 | 186 | # -*- coding: utf-8 -*-
"""Docstring Parsers/Formatters"""
# TODO: break this module up into smaller pieces
import sys
import re
from textwrap import dedent
from collections import OrderedDict
from itertools import islice
from .autodocstring_logging import logger
PY3k = sys.version_info[0] == 3
if PY3k:
string... |
__init__ | Args:
heading (str): heading of the section (should be title case)
text (str, optional): section text
indent (str, optional): used by some formatters | # -*- coding: utf-8 -*-
"""Docstring Parsers/Formatters"""
# TODO: break this module up into smaller pieces
import sys
import re
from textwrap import dedent
from collections import OrderedDict
from itertools import islice
from .autodocstring_logging import logger
PY3k = sys.version_info[0] == 3
if PY3k:
string... | def __init__(self, heading, text="", indent=None, **kwargs):
"""
Args:
heading (str): heading of the section (should be title case)
text (str, optional): section text
indent (str, optional): used by some formatters
"""
self.heading = heading
... | 208 | 234 | # -*- coding: utf-8 -*-
"""Docstring Parsers/Formatters"""
# TODO: break this module up into smaller pieces
import sys
import re
from textwrap import dedent
from collections import OrderedDict
from itertools import islice
from .autodocstring_logging import logger
PY3k = sys.version_info[0] == 3
if PY3k:
string... |
finalize_param | Args:
s (type): Description
tag (int): index of param? not fleshed out yet | # -*- coding: utf-8 -*-
"""Docstring Parsers/Formatters"""
# TODO: break this module up into smaller pieces
import sys
import re
from textwrap import dedent
from collections import OrderedDict
from itertools import islice
from .autodocstring_logging import logger
PY3k = sys.version_info[0] == 3
if PY3k:
string... | @staticmethod
def finalize_param(s, tag):
"""
Args:
s (type): Description
tag (int): index of param? not fleshed out yet
"""
meta = {}
_r = r"([^,\s]+(?:\s*,\s*[^,\s]+)*\s*)(?:\((.*)\))?\s*:\s*(.*)"
m = re.match(_r, s, re.DOTALL | re.MULTIL... | 327 | 347 | # -*- coding: utf-8 -*-
"""Docstring Parsers/Formatters"""
# TODO: break this module up into smaller pieces
import sys
import re
from textwrap import dedent
from collections import OrderedDict
from itertools import islice
from .autodocstring_logging import logger
PY3k = sys.version_info[0] == 3
if PY3k:
string... |
get_transport_class | Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Returns:
The transport class to use. | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | def get_transport_class(
cls, label: str = None,
) -> Type[FeedServiceTransport]:
"""Returns an appropriate transport class.
Args:
label: The name of the desired transport. If none is
provided, then the first transport in the registry is used.
Return... | 55 | 73 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
_get_default_mtls_endpoint | Converts api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[str]): the api endpoint to convert.
Returns:
str: converted mTLS api endpoint. | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | @staticmethod
def _get_default_mtls_endpoint(api_endpoint):
"""Converts api endpoint to mTLS endpoint.
Convert "*.sandbox.googleapis.com" and "*.googleapis.com" to
"*.mtls.sandbox.googleapis.com" and "*.mtls.googleapis.com" respectively.
Args:
api_endpoint (Optional[... | 79 | 107 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
from_service_account_info | Creates an instance of this client using the provided credentials
info.
Args:
info (dict): The service account private key info.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
FeedServiceClient: The constructed client. | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | @classmethod
def from_service_account_info(cls, info: dict, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
info.
Args:
info (dict): The service account private key info.
args: Additional arguments to pass to the constru... | 114 | 131 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
from_service_account_file | Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Additional arguments to pass to the constructor.
kwargs: Additional arguments to pass to the constructor.
Returns:
FeedServiceClient: The c... | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | @classmethod
def from_service_account_file(cls, filename: str, *args, **kwargs):
"""Creates an instance of this client using the provided credentials
file.
Args:
filename (str): The path to the service account private key json
file.
args: Addition... | 133 | 151 | # -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... |
setup_task | Setup the task (e.g., load dictionaries).
Args:
args (argparse.Namespace): parsed command-line arguments | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import itertools
import json
import logging
import os
from argparse import Namespace
import numpy as np
from fairseq import metrics, options,... | @classmethod
def setup_task(cls, args, **kwargs):
"""Setup the task (e.g., load dictionaries).
Args:
args (argparse.Namespace): parsed command-line arguments
"""
args.left_pad_source = utils.eval_bool(args.left_pad_source)
args.left_pad_target = utils.eval_bo... | 243 | 278 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import itertools
import json
import logging
import os
from argparse import Namespace
import numpy as np
from fairseq import metrics, options,... |
load_dataset | Load a given dataset split.
Args:
split (str): name of the split (e.g., train, valid, test) | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import itertools
import json
import logging
import os
from argparse import Namespace
import numpy as np
from fairseq import metrics, options,... | def load_dataset(self, split, epoch=1, combine=False, **kwargs):
"""Load a given dataset split.
Args:
split (str): name of the split (e.g., train, valid, test)
"""
paths = utils.split_paths(self.args.data)
assert len(paths) > 0
if split != getattr(self.ar... | 280 | 315 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import itertools
import json
import logging
import os
from argparse import Namespace
import numpy as np
from fairseq import metrics, options,... |
prepare_transforms | Prepares pre-defined train and test transformation pipelines for some datasets.
Args:
dataset (str): dataset name.
Returns:
Tuple[nn.Module, nn.Module]: training and validation transformation pipelines. | import os
from pathlib import Path
from typing import Callable, Optional, Tuple, Union
import torchvision
from torch import nn
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from torchvision.datasets import STL10, ImageFolder
def build_custom_pipeline():
"""Builds augmentatio... | def prepare_transforms(dataset: str) -> Tuple[nn.Module, nn.Module]:
"""Prepares pre-defined train and test transformation pipelines for some datasets.
Args:
dataset (str): dataset name.
Returns:
Tuple[nn.Module, nn.Module]: training and validation transformation pipelines.
"""
ci... | 39 | 120 | import os
from pathlib import Path
from typing import Callable, Optional, Tuple, Union
import torchvision
from torch import nn
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from torchvision.datasets import STL10, ImageFolder
def build_custom_pipeline():
"""Builds augmentatio... |
prepare_dataloaders | Wraps a train and a validation dataset with a DataLoader.
Args:
train_dataset (Dataset): object containing training data.
val_dataset (Dataset): object containing validation data.
batch_size (int): batch size.
num_workers (int): number of parallel workers.
Returns:
Tuple[DataLoader, DataLoader]: tr... | import os
from pathlib import Path
from typing import Callable, Optional, Tuple, Union
import torchvision
from torch import nn
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from torchvision.datasets import STL10, ImageFolder
def build_custom_pipeline():
"""Builds augmentatio... | def prepare_dataloaders(
train_dataset: Dataset, val_dataset: Dataset, batch_size: int = 64, num_workers: int = 4
) -> Tuple[DataLoader, DataLoader]:
"""Wraps a train and a validation dataset with a DataLoader.
Args:
train_dataset (Dataset): object containing training data.
val_dataset (Dat... | 203 | 232 | import os
from pathlib import Path
from typing import Callable, Optional, Tuple, Union
import torchvision
from torch import nn
from torch.utils.data import DataLoader, Dataset
from torchvision import transforms
from torchvision.datasets import STL10, ImageFolder
def build_custom_pipeline():
"""Builds augmentatio... |
build_fsm_spec_random | Build an FSM spec with the specified number of states.
The FSM spec exploits only single input and single output. As a side
product, a list of output patterns are also returned.
Parameters
----------
num_states : int
The number of states of the FSM.
Returns
-------
dict
The FSM spec that can be consumed by ... | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... | def build_fsm_spec_random(num_states):
"""Build an FSM spec with the specified number of states.
The FSM spec exploits only single input and single output. As a side
product, a list of output patterns are also returned.
Parameters
----------
num_states : int
The number of states of th... | 120 | 159 | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... |
build_fsm_spec_max_in_out | Build an FSM spec using a maximum number of inputs and outputs.
The returned FSM spec has a maximum number of inputs and
outputs. At the same time, the largest available number of
states will be implemented. For example, on PYNQ-Z1, if
FSM_MAX_INPUT_BITS = 8, and FSM_MAX_STATE_INPUT_BITS = 13, we will
implement 2*... | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... | def build_fsm_spec_max_in_out():
"""Build an FSM spec using a maximum number of inputs and outputs.
The returned FSM spec has a maximum number of inputs and
outputs. At the same time, the largest available number of
states will be implemented. For example, on PYNQ-Z1, if
FSM_MAX_INPUT_BITS = 8, ... | 162 | 213 | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... |
build_fsm_spec_free_run | Build a spec that results in a free-running FSM.
This will return an FSM spec with no given inputs.
In this case, the FSM is a free running state machine.
A maximum number of states are deployed.
Returns
-------
dict
The FSM spec that can be consumed by the FSM generator.
list
The output patterns associated ... | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... | def build_fsm_spec_free_run():
"""Build a spec that results in a free-running FSM.
This will return an FSM spec with no given inputs.
In this case, the FSM is a free running state machine.
A maximum number of states are deployed.
Returns
-------
dict
The FSM spec that can be consu... | 216 | 261 | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... |
test_fsm_num_samples | Test for the Finite State Machine Generator class.
In this test, the pattern generated by the FSM will be compared with the
one specified. We will test a minimum number of (FSM period + 1) samples,
and a maximum number of samples. 10MHz and 100MHz clocks are tested
for each case. | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... | @pytest.mark.skipif(not flag, reason="need correct overlay to run")
def test_fsm_num_samples():
"""Test for the Finite State Machine Generator class.
In this test, the pattern generated by the FSM will be compared with the
one specified. We will test a minimum number of (FSM period + 1) samples,
and a... | 264 | 322 | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... |
test_fsm_num_states1 | Test for the Finite State Machine Generator class.
The 4th test will check 1 and (MAX_NUM_STATES + 1) states.
These cases should raise exceptions. For these tests, we use the minimum
number of input and output pins. | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... | @pytest.mark.skipif(not flag, reason="need correct overlay to run")
def test_fsm_num_states1():
"""Test for the Finite State Machine Generator class.
The 4th test will check 1 and (MAX_NUM_STATES + 1) states.
These cases should raise exceptions. For these tests, we use the minimum
number of input and... | 493 | 525 | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... |
test_fsm_num_states2 | Test for the Finite State Machine Generator class.
This test will check 2 and MAX_NUM_STATES states.
These cases should be able to pass random tests.
For these tests, we use the minimum number of input and output pins. | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... | @pytest.mark.skipif(not flag, reason="need correct overlay to run")
def test_fsm_num_states2():
"""Test for the Finite State Machine Generator class.
This test will check 2 and MAX_NUM_STATES states.
These cases should be able to pass random tests.
For these tests, we use the minimum number of input ... | 528 | 572 | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... |
test_fsm_max_in_out | Test for the Finite State Machine Generator class.
This test will test when maximum number of inputs and
outputs are used. At the same time, the largest available number of
states will be implemented. | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... | @pytest.mark.skipif(not flag, reason="need correct overlay to run")
def test_fsm_max_in_out():
"""Test for the Finite State Machine Generator class.
This test will test when maximum number of inputs and
outputs are used. At the same time, the largest available number of
states will be implemented.
... | 575 | 623 | # Copyright (c) 2016, Xilinx, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of con... |
modify_issue | Modify existing issue (PRs are issues)
Arguments:
labels: list of labels to assign to issue
title: new title
body: new body | """Highlevel API for managing PRs on Github"""
import abc
import logging
from copy import copy
from enum import Enum
from typing import Any, Dict, List, Optional
import gidgethub
import gidgethub.aiohttp
import aiohttp
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
#: State for Github Issue... | async def modify_issue(self, number: int,
labels: Optional[List[str]] = None,
title: Optional[str] = None,
body: Optional[str] = None) -> Dict[Any, Any]:
"""Modify existing issue (PRs are issues)
Arguments:
l... | 157 | 189 | """Highlevel API for managing PRs on Github"""
import abc
import logging
from copy import copy
from enum import Enum
from typing import Any, Dict, List, Optional
import gidgethub
import gidgethub.aiohttp
import aiohttp
logger = logging.getLogger(__name__) # pylint: disable=invalid-name
#: State for Github Issue... |
check_specs_against_mirrors | Check all the given specs against buildcaches on the given mirrors and
determine if any of the specs need to be rebuilt. Reasons for needing to
rebuild include binary cache for spec isn't present on a mirror, or it is
present but the full_hash has changed since last time spec was built.
Arguments:
mirrors (dict):... | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import codecs
import os
import re
import tarfile
import shutil
import tempfile
import hashlib
import glob
import platform
... | def check_specs_against_mirrors(mirrors, specs, output_file=None,
rebuild_on_errors=False):
"""Check all the given specs against buildcaches on the given mirrors and
determine if any of the specs need to be rebuilt. Reasons for needing to
rebuild include binary cache for spe... | 994 | 1,037 | # Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
import codecs
import os
import re
import tarfile
import shutil
import tempfile
import hashlib
import glob
import platform
... |
get_model | Returns a pre-defined model by name
Parameters
----------
name : str
Name of the model.
pretrained : bool
Whether to load the pretrained weights for model.
classes : int
Number of classes for the output layer.
ctx : Context, default CPU
The context in which to load the pretrained weights.
root : str, d... | # pylint: disable=wildcard-import, unused-wildcard-import
"""Model store which handles pretrained models from both
mxnet.gluon.model_zoo.vision and gluoncv.models
"""
from mxnet import gluon
from .ssd import *
from .faster_rcnn import *
from .fcn import *
from .pspnet import *
from .cifarresnet import *
from .cifarresn... | def get_model(name, **kwargs):
"""Returns a pre-defined model by name
Parameters
----------
name : str
Name of the model.
pretrained : bool
Whether to load the pretrained weights for model.
classes : int
Number of classes for the output layer.
ctx : Context, default ... | 21 | 110 | # pylint: disable=wildcard-import, unused-wildcard-import
"""Model store which handles pretrained models from both
mxnet.gluon.model_zoo.vision and gluoncv.models
"""
from mxnet import gluon
from .ssd import *
from .faster_rcnn import *
from .fcn import *
from .pspnet import *
from .cifarresnet import *
from .cifarresn... |
contains | Helper for membership check for ``key`` in ``cat``.
This is a helper method for :method:`__contains__`
and :class:`CategoricalIndex.__contains__`.
Returns True if ``key`` is in ``cat.categories`` and the
location of ``key`` in ``categories`` is in ``container``.
Parameters
----------
cat : :class:`Categorical`or :cl... | # pylint: disable=E1101,W0232
import numpy as np
from warnings import warn
import textwrap
from pandas import compat
from pandas.compat import u, lzip
from pandas._libs import lib, algos as libalgos
from pandas.core.dtypes.generic import (
ABCSeries, ABCIndexClass, ABCCategoricalIndex)
from pandas.core.dtypes.mi... | def contains(cat, key, container):
"""
Helper for membership check for ``key`` in ``cat``.
This is a helper method for :method:`__contains__`
and :class:`CategoricalIndex.__contains__`.
Returns True if ``key`` is in ``cat.categories`` and the
location of ``key`` in ``categories`` is in ``conta... | 164 | 212 | # pylint: disable=E1101,W0232
import numpy as np
from warnings import warn
import textwrap
from pandas import compat
from pandas.compat import u, lzip
from pandas._libs import lib, algos as libalgos
from pandas.core.dtypes.generic import (
ABCSeries, ABCIndexClass, ABCCategoricalIndex)
from pandas.core.dtypes.mi... |
_recode_for_categories | Convert a set of codes for to a new set of categories
Parameters
----------
codes : array
old_categories, new_categories : Index
Returns
-------
new_codes : array
Examples
--------
>>> old_cat = pd.Index(['b', 'a', 'c'])
>>> new_cat = pd.Index(['a', 'b'])
>>> codes = np.array([0, 1, 1, 2])
>>> _recode_for_categories... | # pylint: disable=E1101,W0232
import numpy as np
from warnings import warn
import textwrap
from pandas import compat
from pandas.compat import u, lzip
from pandas._libs import lib, algos as libalgos
from pandas.core.dtypes.generic import (
ABCSeries, ABCIndexClass, ABCCategoricalIndex)
from pandas.core.dtypes.mi... | def _recode_for_categories(codes, old_categories, new_categories):
"""
Convert a set of codes for to a new set of categories
Parameters
----------
codes : array
old_categories, new_categories : Index
Returns
-------
new_codes : array
Examples
--------
>>> old_cat = pd.... | 2,457 | 2,486 | # pylint: disable=E1101,W0232
import numpy as np
from warnings import warn
import textwrap
from pandas import compat
from pandas.compat import u, lzip
from pandas._libs import lib, algos as libalgos
from pandas.core.dtypes.generic import (
ABCSeries, ABCIndexClass, ABCCategoricalIndex)
from pandas.core.dtypes.mi... |
_factorize_from_iterable | Factorize an input `values` into `categories` and `codes`. Preserves
categorical dtype in `categories`.
*This is an internal function*
Parameters
----------
values : list-like
Returns
-------
codes : ndarray
categories : Index
If `values` has a categorical dtype, then `categories` is
a CategoricalIndex keepi... | # pylint: disable=E1101,W0232
import numpy as np
from warnings import warn
import textwrap
from pandas import compat
from pandas.compat import u, lzip
from pandas._libs import lib, algos as libalgos
from pandas.core.dtypes.generic import (
ABCSeries, ABCIndexClass, ABCCategoricalIndex)
from pandas.core.dtypes.mi... | def _factorize_from_iterable(values):
"""
Factorize an input `values` into `categories` and `codes`. Preserves
categorical dtype in `categories`.
*This is an internal function*
Parameters
----------
values : list-like
Returns
-------
codes : ndarray
categories : Index
... | 2,504 | 2,541 | # pylint: disable=E1101,W0232
import numpy as np
from warnings import warn
import textwrap
from pandas import compat
from pandas.compat import u, lzip
from pandas._libs import lib, algos as libalgos
from pandas.core.dtypes.generic import (
ABCSeries, ABCIndexClass, ABCCategoricalIndex)
from pandas.core.dtypes.mi... |
astype | Coerce this type to another dtype
Parameters
----------
dtype : numpy dtype or pandas type
copy : bool, default True
By default, astype always returns a newly allocated object.
If copy is set to False and dtype is categorical, the original
object is returned.
.. versionadded:: 0.19.0 | # pylint: disable=E1101,W0232
import numpy as np
from warnings import warn
import textwrap
from pandas import compat
from pandas.compat import u, lzip
from pandas._libs import lib, algos as libalgos
from pandas.core.dtypes.generic import (
ABCSeries, ABCIndexClass, ABCCategoricalIndex)
from pandas.core.dtypes.mi... | def astype(self, dtype, copy=True):
"""
Coerce this type to another dtype
Parameters
----------
dtype : numpy dtype or pandas type
copy : bool, default True
By default, astype always returns a newly allocated object.
If copy is set to False an... | 506 | 528 | # pylint: disable=E1101,W0232
import numpy as np
from warnings import warn
import textwrap
from pandas import compat
from pandas.compat import u, lzip
from pandas._libs import lib, algos as libalgos
from pandas.core.dtypes.generic import (
ABCSeries, ABCIndexClass, ABCCategoricalIndex)
from pandas.core.dtypes.mi... |
_set_categories | Sets new categories inplace
Parameters
----------
fastpath : boolean (default: False)
Don't perform validation of the categories for uniqueness or nulls
Examples
--------
>>> c = pd.Categorical(['a', 'b'])
>>> c
[a, b]
Categories (2, object): [a, b]
>>> c._set_categories(pd.Index(['a', 'c']))
>>> c
[a, c]
Categor... | # pylint: disable=E1101,W0232
import numpy as np
from warnings import warn
import textwrap
from pandas import compat
from pandas.compat import u, lzip
from pandas._libs import lib, algos as libalgos
from pandas.core.dtypes.generic import (
ABCSeries, ABCIndexClass, ABCCategoricalIndex)
from pandas.core.dtypes.mi... | def _set_categories(self, categories, fastpath=False):
""" Sets new categories inplace
Parameters
----------
fastpath : boolean (default: False)
Don't perform validation of the categories for uniqueness or nulls
Examples
--------
>>> c = pd.Catego... | 687 | 718 | # pylint: disable=E1101,W0232
import numpy as np
from warnings import warn
import textwrap
from pandas import compat
from pandas.compat import u, lzip
from pandas._libs import lib, algos as libalgos
from pandas.core.dtypes.generic import (
ABCSeries, ABCIndexClass, ABCCategoricalIndex)
from pandas.core.dtypes.mi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.