Generate symbolic graph for adversarial examples and return.

    :param x: The model's symbolic inputs.
    :param kwargs: Keyword arguments for the base attacker
773406
def generate(self, x, **kwargs):
    

    assert self.parse_params(**kwargs)
    labels, _nb_classes = self.get_or_guess_labels(x, kwargs)
    adv_x = self.attack(x, labels)

    return adv_x
199001
def gradients_X(self, dL_dK, X, X2, target):
        """"""
        if X2==None or X2 is X:
            dL_dKdiag = dL_dK.flat[::dL_dK.shape[0]+1]
            self.dKdiag_dX(dL_dKdiag, X, target)
1242364
def _process_gradient_args(f, kwargs):
    """"""
    axes = kwargs.get('axes', range(f.ndim))

    def _check_length(positions):
        if 'axes' in kwargs and len(positions) < len(axes):
            raise ValueError('Length of "coordinates" or "deltas" cannot be less than that '
                             'of "axes".')
        elif 'axes' not in kwargs and len(positions) != len(axes):
            raise ValueError('Length of "coordinates" or "deltas" must match the number of '
                             'dimensions of "f" when "axes" is not given.')

    if 'deltas' in kwargs:
        if 'coordinates' in kwargs or 'x' in kwargs:
            raise ValueError('Cannot specify both "coordinates" and "deltas".')
        _check_length(kwargs['deltas'])
        return 'delta', kwargs['deltas'], axes
    elif 'coordinates' in kwargs:
        _check_length(kwargs['coordinates'])
        return 'x', kwargs['coordinates'], axes
    elif 'x' in kwargs:
        warnings.warn('The use of "x" as a parameter for coordinate values has been '
                      'deprecated. Use "coordinates" instead.', metpyDeprecation)
        _check_length(kwargs['x'])
        return 'x', kwargs['x'], axes
    elif isinstance(f, xr.DataArray):
        return 'pass', axes, axes  # only the axis argument matters
    else:
        raise ValueError('Must specify either "coordinates" or "deltas" for value positions '
                         'when "f" is not a DataArray.')
1163773
def generate_random_graph(node_num, edge_num, self_loops=False, multi_edges=False):
    '''
    
    '''
    g = Graph.Graph()

    if not multi_edges:
        if self_loops:
            max_edges = node_num * node_num
        else:
            max_edges = node_num * (node_num-1)

        if edge_num > max_edges:
            raise GraphError("inconsistent arguments to 'generate_random_graph'")

    nodes = range(node_num)

    for node in nodes:
        g.add_node(node)

    while 1:
        head = random.choice(nodes)
        tail = random.choice(nodes)

        # loop defense
        if head == tail and not self_loops:
            continue

        # multiple edge defense
        if g.edge_by_node(head,tail) is not None and not multi_edges:
            continue

        # add the edge
        g.add_edge(head, tail)
        if g.number_of_edges() >= edge_num:
            break

    return g
211150
def propagate(self, *arg, **kw):
        
        output = Network.propagate(self, *arg, **kw)
        if self.interactive:
            self.updateGraphics()
        # IMPORTANT: convert results from numpy.floats to conventional floats 
        if type(output) == dict:
            for layerName in output:
                output[layerName] = [float(x) for x in output[layerName]]
            return output
        else:
            return [float(x) for x in output]
605625
def mk_kwargs(cls, kwargs):
        
        ret = {}
        kws = ['row_factory', 'body', 'parent']
        for k in kws:
            if k in kwargs:
                ret[k] = kwargs.pop(k)

        return ret
770637
def get_predicted_class(self, x, **kwargs):
    
    return tf.argmax(self.get_logits(x, **kwargs), axis=1)
831390
def load_kwargs(*args, **kwargs):
    
    def handle_scene():
        """
        Load a scene from our kwargs:

        class:      Scene
        geometry:   dict, name: Trimesh kwargs
        graph:      list of dict, kwargs for scene.graph.update
        base_frame: str, base frame of graph
        """
        scene = Scene()
        scene.geometry.update({k: load_kwargs(v) for
                               k, v in kwargs['geometry'].items()})
        for k in kwargs['graph']:
            if isinstance(k, dict):
                scene.graph.update(**k)
            elif util.is_sequence(k) and len(k) == 3:
                scene.graph.update(k[1], k[0], **k[2])
        if 'base_frame' in kwargs:
            scene.graph.base_frame = kwargs['base_frame']
        if 'metadata' in kwargs:
            scene.metadata.update(kwargs['metadata'])

        return scene

    def handle_trimesh_kwargs():
        """
        Load information with vertices and faces into a mesh
        or PointCloud object.
        """
        if (isinstance(kwargs['vertices'], dict) or
                isinstance(kwargs['faces'], dict)):
            return Trimesh(**misc.load_dict(kwargs))
        elif kwargs['faces'] is None:
            # vertices without faces returns a PointCloud
            return PointCloud(**kwargs)
        else:
            return Trimesh(**kwargs)

    def handle_trimesh_export():
        data, file_type = kwargs['data'], kwargs['file_type']
        if not isinstance(data, dict):
            data = util.wrap_as_stream(data)
        k = mesh_loaders[file_type](data,
                                    file_type=file_type)
        return Trimesh(**k)

    # if we've been passed a single dict instead of kwargs
    # substitute the dict for kwargs
    if (len(kwargs) == 0 and
        len(args) == 1 and
            isinstance(args[0], dict)):
        kwargs = args[0]

    # function : list of expected keys
    handlers = {handle_scene: ('graph', 'geometry'),
                handle_trimesh_kwargs: ('vertices', 'faces'),
                handle_trimesh_export: ('file_type', 'data')}

    # loop through handler functions and expected key
    handler = None
    for func, expected in handlers.items():
        if all(i in kwargs for i in expected):
            # all expected kwargs exist
            handler = func
            # exit the loop as we found one
            break

    if handler is None:
        raise ValueError('unable to determine type!')

    return handler()
1280145
def generate(self, x, **kwargs):
    
    # Parse and save attack-specific parameters
    assert self.parse_params(**kwargs)

    from cleverhans.attacks_tf import spm

    labels, _ = self.get_or_guess_labels(x, kwargs)

    return spm(
        x,
        self.model,
        y=labels,
        n_samples=self.n_samples,
        dx_min=self.dx_min, dx_max=self.dx_max, n_dxs=self.n_dxs,
        dy_min=self.dy_min, dy_max=self.dy_max, n_dys=self.n_dys,
        angle_min=self.angle_min, angle_max=self.angle_max,
        n_angles=self.n_angles, black_border_size=self.black_border_size)
838958
def get_model_args_kwargs(self):
        
        source = self.get_model()
        if not source:
            return [], {}

        argspec = inspect.getargspec(source)
        
        kk = list(zip(*[reversed(l) for l in (argspec.args, argspec.defaults or [])]))
        kk.reverse()
        kwargs = OrderedDict(kk)
        args = [x for x in argspec.args if x not in kwargs.keys()]
        if args and args[0] == 'cls':
            args = args[1:]
        return args, kwargs
1292449
def genargs(prog: Optional[str] = None) -> ArgumentParser:
    
    parser = ArgumentParser(prog)
    parser.add_argument("rdf", help="Input RDF file or SPARQL endpoint if slurper or sparql options")
    parser.add_argument("shex", help="ShEx specification")
    parser.add_argument("-f", "--format", help="Input RDF Format", default="turtle")
    parser.add_argument("-s", "--start", help="Start shape. If absent use ShEx start node.")
    parser.add_argument("-ut", "--usetype", help="Start shape is rdf:type of focus", action="store_true")
    parser.add_argument("-sp", "--startpredicate", help="Start shape is object of this predicate")
    parser.add_argument("-fn", "--focus", help="RDF focus node")
    parser.add_argument("-A", "--allsubjects", help="Evaluate all non-bnode subjects in the graph", action="store_true")
    parser.add_argument("-d", "--debug", action="store_true", help="Add debug output")
    parser.add_argument("-ss", "--slurper", action="store_true", help="Use SPARQL slurper graph")
    parser.add_argument("-cf", "--flattener", action="store_true", help="Use RDF Collections flattener graph")
    parser.add_argument("-sq", "--sparql", help="SPARQL query to generate focus nodes")
    parser.add_argument("-se", "--stoponerror", help="Stop on an error", action="store_true")
    parser.add_argument("--stopafter", help="Stop after N nodes", type=int)
    parser.add_argument("-ps", "--printsparql", help="Print SPARQL queries as they are executed", action="store_true")
    parser.add_argument("-pr", "--printsparqlresults", help="Print SPARQL query and results", action="store_true")
    parser.add_argument("-gn", "--graphname", help="Specific SPARQL graph to query - use '' for any named graph")
    parser.add_argument("-pb", "--persistbnodes", help="Treat BNodes as persistent in SPARQL endpoint",
                        action="store_true")
    return parser
656058
def plot(self, xmin, xmax, idx_input=0, idx_output=0, points=100,
             **kwargs) -> None:
        
        for toy, ann_ in self:
            ann_.plot(xmin, xmax,
                      idx_input=idx_input, idx_output=idx_output,
                      points=points,
                      label=str(toy),
                      **kwargs)
        pyplot.legend()
1119742
def graph_memoized(func):
    

    # TODO it keeps the graph alive
    from ..compat import tfv1
    GRAPH_ARG_NAME = '__IMPOSSIBLE_NAME_FOR_YOU__'

    @memoized
    def func_with_graph_arg(*args, **kwargs):
        kwargs.pop(GRAPH_ARG_NAME)
        return func(*args, **kwargs)

    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        assert GRAPH_ARG_NAME not in kwargs, "No Way!!"
        graph = tfv1.get_default_graph()
        kwargs[GRAPH_ARG_NAME] = graph
        return func_with_graph_arg(*args, **kwargs)
    return wrapper
837629
def xargs(cmd, varargs, **kwargs):
    
    negate = kwargs.pop('negate', False)
    target_concurrency = kwargs.pop('target_concurrency', 1)
    max_length = kwargs.pop('_max_length', _get_platform_max_length())
    retcode = 0
    stdout = b''
    stderr = b''

    try:
        cmd = parse_shebang.normalize_cmd(cmd)
    except parse_shebang.ExecutableNotFoundError as e:
        return e.to_output()

    partitions = partition(cmd, varargs, target_concurrency, max_length)

    def run_cmd_partition(run_cmd):
        return cmd_output(*run_cmd, encoding=None, retcode=None, **kwargs)

    threads = min(len(partitions), target_concurrency)
    with _thread_mapper(threads) as thread_map:
        results = thread_map(run_cmd_partition, partitions)

        for proc_retcode, proc_out, proc_err in results:
            # This is *slightly* too clever so I'll explain it.
            # First the xor boolean table:
            #     T | F |
            #   +-------+
            # T | F | T |
            # --+-------+
            # F | T | F |
            # --+-------+
            # When negate is True, it has the effect of flipping the return
            # code. Otherwise, the returncode is unchanged.
            retcode |= bool(proc_retcode) ^ negate
            stdout += proc_out
            stderr += proc_err

    return retcode, stdout, stderr
140097
def get_logits(self, x):
    
    logits_name = self._get_logits_name()
    logits_layer = self.get_layer(x, logits_name)

    # Need to deal with the case where softmax is part of the
    # logits layer
    if logits_name == self._get_softmax_name():
      softmax_logit_layer = self.get_layer(x, logits_name)

      # The final op is the softmax. Return its input
      logits_layer = softmax_logit_layer._op.inputs[0]

    return logits_layer
678928
def init_from_adversarial_batches(self, adv_batches):
    
    for idx, (adv_batch_id, adv_batch_val) in enumerate(iteritems(adv_batches)):
      work_id = ATTACK_WORK_ID_PATTERN.format(idx)
      self.work[work_id] = {
          'claimed_worker_id': None,
          'claimed_worker_start_time': None,
          'is_completed': False,
          'error': None,
          'elapsed_time': None,
          'submission_id': adv_batch_val['submission_id'],
          'shard_id': None,
          'output_adversarial_batch_id': adv_batch_id,
      }
532402
def convert_softmax(node, **kwargs):
    
    name, input_nodes, attrs = get_inputs(node, kwargs)

    axis = int(attrs.get("axis", -1))

    softmax_node = onnx.helper.make_node(
        "Softmax",
        input_nodes,
        [name],
        axis=axis,
        name=name
    )

    return [softmax_node]