Python create target

60 Python code examples are found related to " create target". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: named_tag_scope.py    From dashboard-api-python with MIT License 6 votes vote down vote up
def createNetworkSmTargetGroup(self, networkId: str, **kwargs):
        """
        **Add a target group**
        https://developer.cisco.com/meraki/api/#!create-network-sm-target-group
        
        - networkId (string)
        - name (string): The name of this target group
        - scope (string): The scope and tag options of the target group. Comma separated values beginning with one of withAny, withAll, withoutAny, withoutAll, all, none, followed by tags. Default to none if empty.
        """

        kwargs.update(locals())

        metadata = {
            'tags': ['Named tag scope'],
            'operation': 'createNetworkSmTargetGroup',
        }
        resource = f'/networks/{networkId}/sm/targetGroups'

        body_params = ['name', 'scope']
        payload = {k: v for (k, v) in kwargs.items() if k in body_params}

        return self._session.post(metadata, resource, payload) 
Example 2
Source File: pipelinewise.py    From pipelinewise with Apache License 2.0 6 votes vote down vote up
def create_consumable_target_config(self, target_config, tap_inheritable_config):
        """
        Create consumable target config by appending "inheritable" config to the common target config
        """
        dict_a, dict_b = {}, {}
        try:
            dict_a = utils.load_json(target_config)
            dict_b = utils.load_json(tap_inheritable_config)

            # Copy everything from dictB into dictA - Not a real merge
            dict_a.update(dict_b)

            # Save the new dict as JSON into a temp file
            tempfile_path = utils.create_temp_file(dir=self.get_temp_dir(),
                                                   prefix='target_config_',
                                                   suffix='.json')[1]
            utils.save_json(dict_a, tempfile_path)

            return tempfile_path
        except Exception as exc:
            raise Exception(f'Cannot merge JSON files {dict_a} {dict_b} - {exc}')

    # pylint: disable=too-many-statements,too-many-branches,too-many-nested-blocks,too-many-locals,too-many-arguments 
Example 3
Source File: __init__.py    From designate with Apache License 2.0 6 votes vote down vote up
def create_pool_target(self, context, pool_id, pool_target):
        pool_target.pool_id = pool_id

        pool_target = self._create(
            tables.pool_targets, pool_target, exceptions.DuplicatePoolTarget,
            ['options', 'masters'])

        if pool_target.obj_attr_is_set('options'):
            for pool_target_option in pool_target.options:
                self.create_pool_target_option(
                    context, pool_target.id, pool_target_option)
        else:
            pool_target.options = objects.PoolTargetOptionList()

        if pool_target.obj_attr_is_set('masters'):
            for pool_target_master in pool_target.masters:
                self.create_pool_target_master(
                    context, pool_target.id, pool_target_master)
        else:
            pool_target.masters = objects.PoolTargetMasterList()

        pool_target.obj_reset_changes(['options', 'masters'])

        return pool_target 
Example 4
Source File: deploy_repository.py    From incubator-dlab with Apache License 2.0 6 votes vote down vote up
def create_mount_target(efs_sg_id):
    try:
        mount_target_id = efs_client.create_mount_target(
            FileSystemId=args.efs_id,
            SubnetId=args.subnet_id,
            SecurityGroups=[
                efs_sg_id
            ]
        ).get('MountTargetId')
        while efs_client.describe_mount_targets(
                MountTargetId=mount_target_id).get('MountTargets')[0].get('LifeCycleState') != 'available':
            time.sleep(10)
    except Exception as err:
        traceback.print_exc(file=sys.stdout)
        print('Error with creating AWS mount target: {}'.format(str(err)))
        raise Exception 
Example 5
Source File: actor_network_bn_canonical.py    From programmable-agents_tensorflow with MIT License 6 votes vote down vote up
def create_target_network(self,state_dim,action_dim,net):
		state_input = tf.placeholder("float",[None,state_dim])
		is_training = tf.placeholder(tf.bool)
		ema = tf.train.ExponentialMovingAverage(decay=1-TAU)
		target_update = ema.apply(net)
		target_net = [ema.average(x) for x in net]

		layer0_bn = self.batch_norm_layer(state_input,training_phase=is_training,scope_bn='target_batch_norm_0',activation=tf.identity)

		layer1 = tf.matmul(layer0_bn,target_net[0]) + target_net[1]
		layer1_bn = self.batch_norm_layer(layer1,training_phase=is_training,scope_bn='target_batch_norm_1',activation=tf.nn.relu)
		layer2 = tf.matmul(layer1_bn,target_net[2]) + target_net[3]
		layer2_bn = self.batch_norm_layer(layer2,training_phase=is_training,scope_bn='target_batch_norm_2',activation=tf.nn.relu)

		action_output = tf.tanh(tf.matmul(layer2_bn,target_net[4]) + target_net[5])

		return state_input,action_output,target_update,is_training 
Example 6
Source File: registration_repository.py    From schematizer with Apache License 2.0 6 votes vote down vote up
def create_data_target(name, target_type, destination):
    """Create a new data target of specified target type and destination.

    Args:
        name (string): name to uniquely identify a data target
        target_type (string): string describing the type of the data target
        destination (string): the actual location of the data target, such as
            the url of the cluster.

    Returns:
        :class:models.data_target.DataTarget: the created data target.

    Raises:
        ValueError: if given target type or destination is empty.
    """
    verify_truthy_value(name, "data target name")
    verify_truthy_value(target_type, "data target type")
    verify_truthy_value(destination, "destination of data target")

    return models.DataTarget.create(
        session,
        name=name,
        target_type=target_type,
        destination=destination
    ) 
Example 7
Source File: domainservice.py    From jdcloud-cli with Apache License 2.0 6 votes vote down vote up
def create_monitor_target(self):
        client_factory = ClientFactory('domainservice')
        client = client_factory.get(self.app)
        if client is None:
            return

        try:
            from jdcloud_sdk.services.domainservice.apis.CreateMonitorTargetRequest import CreateMonitorTargetRequest
            params_dict = collect_user_args(self.app)
            headers = collect_user_headers(self.app)
            req = CreateMonitorTargetRequest(params_dict, headers)
            resp = client.send(req)
            Printer.print_result(resp)
        except ImportError:
            print('{"error":"This api is not supported, please use the newer version"}')
        except Exception as e:
            print(e) 
Example 8
Source File: zfs.py    From jdcloud-cli with Apache License 2.0 6 votes vote down vote up
def create_mount_target(self):
        client_factory = ClientFactory('zfs')
        client = client_factory.get(self.app)
        if client is None:
            return

        try:
            from jdcloud_sdk.services.zfs.apis.CreateMountTargetRequest import CreateMountTargetRequest
            params_dict = collect_user_args(self.app)
            headers = collect_user_headers(self.app)
            req = CreateMountTargetRequest(params_dict, headers)
            resp = client.send(req)
            Printer.print_result(resp)
        except ImportError:
            print('{"error":"This api is not supported, please use the newer version"}')
        except Exception as e:
            print(e) 
Example 9
Source File: modeling_decoding.py    From unilm with MIT License 6 votes vote down vote up
def create_target_mask(self, target_ids, num_target_tokens):
        max_target_len = target_ids.size(1)
        target_mask = self.create_mask(target_ids, num_target_tokens)

        target_pos_matrix = torch.arange(
            0, max_target_len, dtype=target_ids.dtype, device=target_ids.device).view(1, -1)

        triangle_attention_mask = \
            target_pos_matrix.view(1, max_target_len, 1) >= target_pos_matrix.view(1, 1, max_target_len)
        triangle_attention_mask = triangle_attention_mask.type_as(target_mask)
        diagonal_attention_mask = \
            target_pos_matrix.view(1, max_target_len, 1) == target_pos_matrix.view(1, 1, max_target_len)
        diagonal_attention_mask = diagonal_attention_mask.type_as(target_mask)
        golden_attention_mask = torch.cat((triangle_attention_mask, torch.zeros_like(triangle_attention_mask)), dim=-1)

        pseudo_attention_mask = torch.cat(
            (triangle_attention_mask - diagonal_attention_mask, diagonal_attention_mask), dim=-1)

        return target_mask, torch.cat((golden_attention_mask, pseudo_attention_mask), dim=1) 
Example 10
Source File: util.py    From deep-learning-from-scratch-2 with MIT License 6 votes vote down vote up
def create_contexts_target(corpus, window_size=1):
    '''コンテキストとターゲットの作成

    :param corpus: コーパス(単語IDのリスト)
    :param window_size: ウィンドウサイズ(ウィンドウサイズが1のときは、単語の左右1単語がコンテキスト)
    :return:
    '''
    target = corpus[window_size:-window_size]
    contexts = []

    for idx in range(window_size, len(corpus)-window_size):
        cs = []
        for t in range(-window_size, window_size + 1):
            if t == 0:
                continue
            cs.append(corpus[idx + t])
        contexts.append(cs)

    return np.array(contexts), np.array(target) 
Example 11
Source File: __init__.py    From luscan-devel with GNU General Public License v2.0 6 votes vote down vote up
def create_target(self, name, hosts, comment=""):
        """
        Creates a target in OpenVAS.

        :param name: name to the target
        :type name: str

        :param hosts: target list. Can be only one target or a list of targets
        :type hosts: str | list(str)

        :param comment: comment to add to task
        :type comment: str

        :return: the ID of the created target.
        :rtype: str

        :raises: ClientError, ServerError
        """
        raise NotImplementedError()

    #---------------------------------------------------------------------- 
Example 12
Source File: parseundp.py    From Semantic-Search-for-Sustainable-Development with Apache License 2.0 6 votes vote down vote up
def create_target_dictionary(development_matches):
    sgd_target_pattern = r'[0-9]+\.[0-9]+' # pattern to match target format
    target_matches = {}
    for development_match in development_matches:
        development_match.replace(np.nan, '', regex=True, inplace = True)
        target = None

        for row in development_match.itertuples():
            match = re.search(sgd_target_pattern, str(row[1]), flags=0)
            if match: # If we found a undp target
                target = match.group()
                if target in target_matches: # Add sentence to the set for that target's key
                    target_matches[target].add(row[1][len(target):])
                else:
                    target_matches[target] = set({row[1][len(target):]})
            # Continue adding to the current target's key if there is text in the data frame
            if target != None and row[2] != '':
                target_matches[target].add(row[2])
        
    return target_matches 
Example 13
Source File: client.py    From pyvas with MIT License 6 votes vote down vote up
def create_target(self, name, hosts, port_list=None, ssh_credential=None, alive_tests=None, comment=None):
        """Creates a target of hosts."""
        if comment is None:
            comment = ""

        data = {"name": name, "hosts": hosts, "comment": comment}
        if port_list:
            data.update({"port_list": {'@id': port_list}})
        if alive_tests:
            data.update({"alive_tests": alive_tests})
        if ssh_credential:
            data.update({"ssh_credential": {'@id': ssh_credential}})

        request = dict_to_lxml(
            "create_target",
            data
        )
        return self._create(request) 
Example 14
Source File: manifest.py    From edx-analytics-pipeline with GNU Affero General Public License v3.0 6 votes vote down vote up
def create_manifest_target(manifest_id, targets):
    # If we are running locally, we need our manifest file to be a local file target, however, if we are running on
    # a real Hadoop cluster, it has to be an HDFS file so that the input format can read it. Luigi makes it a little
    # difficult for us to construct a target that can be one or the other of those types of targets at runtime since
    # it relies on inheritance to signify the difference. We hack the inheritance here, by dynamically choosing the
    # base class at runtime based on the URL of the manifest file.

    # Construct the manifest file URL from the manifest_id and the configuration
    manifest_file_path = get_manifest_file_path(manifest_id)

    # Figure out the type of target that should be used to write/read the file.
    manifest_file_target_class, init_args, init_kwargs = get_target_class_from_url(manifest_file_path)

    # Ensure our constructed target inherits from the appropriate type of file target.
    class ManifestInputTarget(ManifestInputTargetMixin, manifest_file_target_class):
        pass

    # This functionality is inherited from the Mixin which contains all of the substantial logic
    return ManifestInputTarget.from_existing_targets(targets, *init_args, **init_kwargs) 
Example 15
Source File: target.py    From darkc0de-old-stuff with GNU General Public License v3.0 6 votes vote down vote up
def createTargetDirs():
    """
    Create the output directory.
    """

    conf.outputPath = "%s%s%s" % (paths.SQLMAP_OUTPUT_PATH, os.sep, conf.hostname)

    if not os.path.isdir(paths.SQLMAP_OUTPUT_PATH):
        os.makedirs(paths.SQLMAP_OUTPUT_PATH, 0755)

    if not os.path.isdir(conf.outputPath):
        os.makedirs(conf.outputPath, 0755)

    dumper.setOutputFile()

    __createDumpDir()
    __createFilesDir() 
Example 16
Source File: changan.py    From Arsenal with GNU General Public License v3.0 6 votes vote down vote up
def handle_create_target(self, event_data):
        """
        nothing right now
        """
        try:
            interfaces = []
            for interface in event_data.get('target', {})['facts']['interfaces']:
                my_interface = {}
                my_interface['name'] = interface['name']
                my_interface['mac'] = interface['mac_addr']
                my_interface['ips'] = []
                for ip_addr in interface['ip_addrs']:
                    my_interface['ips'].append(ip_addr.split('/')[0])
                interfaces.append(my_interface)
            add_client_data = {'device_name': event_data['name'], 'interface': my_interface}
            requests.put('{}api/v1/devices'.format(self.url), json=add_client_data, verify=False)
        except Exception as exception: #pylint: disable=broad-except
            print(exception) 
Example 17
Source File: target.py    From Arsenal with GNU General Public License v3.0 6 votes vote down vote up
def create_target(params):
    """
    ### Overview
    This API function creates a new target object in the database.

    ### Parameters
    name (unique):      The name given to the target. <str>
    uuid (unique):      The unique identifier of the target. <str>
    facts (optional):   A dictionary of key,value pairs to store for the target. <dict>
    """
    name = params["name"]
    uuid = params["uuid"]
    facts = params.get("facts", {})

    target = Target(name=name, uuid=uuid, facts=facts)
    target.save(force_insert=True)

    # Generate Event
    if not current_app.config.get("DISABLE_EVENTS", False):
        events.trigger_event.delay(event="target_create", target=target.document(True, True, True))

    return success_response() 
Example 18
Source File: actor_network.py    From MADRaS with GNU Affero General Public License v3.0 6 votes vote down vote up
def create_target_network(self,state_dim,action_dim,net):
        state_input = tf.placeholder("float",[None,state_dim])
        ema = tf.train.ExponentialMovingAverage(decay=1-TAU)
        target_update = ema.apply(net)
        target_net = [ema.average(x) for x in net]

        layer1 = tf.nn.relu(tf.matmul(state_input,target_net[0]) + target_net[1])
        layer2 = tf.nn.relu(tf.matmul(layer1,target_net[2]) + target_net[3])

        steer = tf.tanh(tf.matmul(layer2,target_net[4]) + target_net[5])
        accel = tf.sigmoid(tf.matmul(layer2,target_net[6]) + target_net[7])
        brake = tf.sigmoid(tf.matmul(layer2,target_net[8]) + target_net[9])

        # action_output = tf.concat(1, [steer, accel, brake])
        action_output = tf.concat([steer, accel, brake], 1)
        return state_input,action_output,target_update,target_net 
Example 19
Source File: schematizer.py    From data_pipeline with Apache License 2.0 6 votes vote down vote up
def create_data_target(self, name, target_type, destination):
        """ Create and return newly created data target.

        Args:
            name (str): Name to uniquely identify the data target.
            target_type (str): The type of the data target, such as Redshift.
            destination (str): The actual location of the data target, such as
                Url of the Redshift cluster.

        Returns:
            (data_pipeline.schematizer_clientlib.models.data_target.DataTarget):
                The newly created data target.
        """
        response = self._call_api(
            api=self._client.data_targets.create_data_target,
            request_body={
                'name': name,
                'target_type': target_type,
                'destination': destination
            }
        )
        _data_target = _DataTarget.from_response(response)
        self._set_cache_by_data_target(_data_target)
        return _data_target.to_result() 
Example 20
Source File: ezibpy.py    From ezibpy with Apache License 2.0 6 votes vote down vote up
def createTargetOrder(self, quantity, parentId=0,
            target=0., orderType=None, transmit=True, group=None, tif="DAY",
            rth=False, account=None):
        """ Creates TARGET order """
        params = {
            "quantity": quantity,
            "price": target,
            "transmit": transmit,
            "orderType": orderType,
            "ocaGroup": group,
            "parentId": parentId,
            "rth": rth,
            "tif": tif,
            "account": self._get_active_account(account)
        }
        # default order type is "Market if Touched"
        if orderType is None: # or orderType.upper() == "MKT":
            params['orderType'] = dataTypes["ORDER_TYPE_MIT"]
            params['auxPrice'] = target
            del params['price']

        order = self.createOrder(**params)
        return order

    # ----------------------------------------- 
Example 21
Source File: deploy.py    From dynamodb-continuous-backup with Apache License 2.0 6 votes vote down vote up
def create_lambda_cwe_target(lambda_arn):
    existing_targets = cwe_client.list_targets_by_rule(
        Rule=DDB_CREATE_DELETE_RULE_NAME
    )

    if 'Targets' not in existing_targets or len(existing_targets['Targets']) == 0:
        cwe_client.put_targets(
            Rule=DDB_CREATE_DELETE_RULE_NAME,
            Targets=[
                {
                    'Id': shortuuid.uuid(),
                    'Arn': lambda_arn
                }
            ]
        )

        print "Created CloudWatchEvents Target for Rule %s" % (DDB_CREATE_DELETE_RULE_NAME)
    else:
        print "Existing CloudWatchEvents Rule has correct Target Function" 
Example 22
Source File: descriptor.py    From workload-automation with Apache License 2.0 6 votes vote down vote up
def create_target_description(name, *args, **kwargs):
    name = identifier(name)
    for td in _adhoc_target_descriptions:
        if caseless_string(name) == td.name:
            msg = 'Target with name "{}" already exists (from source: {})'
            raise ValueError(msg.format(name, td.source))

    stack = inspect.stack()
    # inspect.stack() returns a list of call frame records for the current thread
    # in reverse call order. So the first entry is for the current frame and next one
    # for the immediate caller. Each entry is a tuple in the format
    #  (frame_object, module_path, line_no, function_name, source_lines, source_lines_index)
    #
    # Here we assign the path of the calling module as the "source" for this description.
    # because this might be invoked via the add_scription_for_target wrapper, we need to
    # check for that, and make sure that we get the info for *its* caller in that case.
    if stack[1][3] == 'add_description_for_target':
        source = stack[2][1]
    else:
        source = stack[1][1]

    _adhoc_target_descriptions.append(TargetDescription(name, source, *args, **kwargs)) 
Example 23
Source File: dataio.py    From open-sesame with Apache License 2.0 5 votes vote down vote up
def create_target_frame_map(luIndex_file,  tf_map):
    sys.stderr.write("\nReading the frame - lexunit map from " + LU_INDEX + " ...\n")

    f = open(luIndex_file, "rb")
    tree = et.parse(f)
    root = tree.getroot()

    multiplicity = 0
    repeated = 0
    tot = 0
    for lu in root.iter('{http://framenet.icsi.berkeley.edu}lu'):
        lu_name = lu.attrib["name"]
        frame = lu.attrib["frameName"]
        if lu_name not in tf_map:
            tf_map[lu_name] = []
        else:
            repeated += 1
        tf_map[lu_name].append(frame)
        if len(tf_map[lu_name]) > multiplicity:
            multiplicity = len(tf_map[lu_name])
        tot += 1
    f.close()

    sys.stderr.write("# unique LUs = " + str(len(tf_map)) + "\n")
    sys.stderr.write("# total LUs = " + str(tot) + "\n")
    sys.stderr.write("# targets with multiple frames = " + str(repeated) + "\n")
    sys.stderr.write("# max frames per target = " + str(multiplicity) + "\n\n")
    return tf_map 
Example 24
Source File: dataio.py    From open-sesame with Apache License 2.0 5 votes vote down vote up
def create_target_lu_map():
    sys.stderr.write("\nReading the lexical unit index file: {}\n".format(LU_INDEX))

    lu_index_file = open(LU_INDEX, "rb")
    tree = et.parse(lu_index_file)
    root = tree.getroot()

    multiplicity = 0
    repeated = 0
    total = 0

    target_lu_map = {}
    lu_names = set([])
    for lu in root.iter('{http://framenet.icsi.berkeley.edu}lu'):
        lu_name = lu.attrib["name"]
        lu_names.add(lu_name)

        target_name = lu_name.split('.')[0]
        LUDICT.addstr(target_name)
        if target_name not in target_lu_map:
            target_lu_map[target_name] = set([])
        else:
            repeated += 1
        target_lu_map[target_name].add(lu_name)
        if len(target_lu_map[target_name]) > multiplicity:
            multiplicity = len(target_lu_map[target_name])
        total += 1
    lu_index_file.close()

    sys.stderr.write("# unique targets = {}\n".format(len(target_lu_map)))
    sys.stderr.write("# total targets = {}\n".format(total))
    sys.stderr.write("# targets with multiple LUs = {}\n".format(repeated))
    sys.stderr.write("# max LUs per target = {}\n\n".format(multiplicity))
    return target_lu_map, lu_names 
Example 25
Source File: helpers.py    From harmony-ops with MIT License 5 votes vote down vote up
def create_name_target_group(shard, id_domain):
    ret = []
    tg_prefix = 'tg-s' + str(shard) + '-api-' + id_domain + '-'
    ret.append(tg_prefix + 'https')
    ret.append(tg_prefix + 'wss')
    return ret 
Example 26
Source File: logperiodic_opt.py    From python-necpp with GNU General Public License v2.0 5 votes vote down vote up
def create_optimization_target():
  def target(args):
      l_1, x_1, tau = args
      if l_1 <= 0 or x_1 <= 0 or tau <= 0:
          return float('inf')

      try:
        result = 0

        vswr_score = 0
        gains_score = 0

        for range_low, range_high in [ (2400, 2500), (5725, 5875) ]:
            freqs, gains, vswrs = get_gain_swr_range(l_1, x_1, tau, start=range_low, stop=range_high)

            for gain in gains:
                gains_score += gain
            for vswr in vswrs:
                if vswr >= 1.8:
                    vswr = np.exp(vswr) # a penalty :)
                vswr_score += vswr

        # VSWR should minimal in both bands, gains maximal:
        result = vswr_score - gains_score

      except:
          print("Caught exception")
          return float('inf')

      print(result)

      return result
  return target 
Example 27
Source File: invert.py    From ssai-cnn with MIT License 5 votes vote down vote up
def create_target(self):
        xp = cuda.cupy if self.args.gpu >= 0 else np
        self.x0_data = xp.asarray(self.img[np.newaxis].copy())
        x0 = chainer.Variable(self.x0_data, volatile=True)

        # Extract feature from target image
        self.y0 = self.extract_feature(x0)
        self.y0.volatile = False
        y0_sigma = np.linalg.norm(cuda.to_cpu(self.y0.data))
        self.lambda_euc = self.args.x0_sigma ** 2 / y0_sigma ** 2 
Example 28
Source File: action.py    From insightconnect-plugins with MIT License 5 votes vote down vote up
def create_target_cell_range(self, direction, start_cell, update_list):
        start_cell_cord = gspread.utils.a1_to_rowcol(start_cell)
        list_size = len(update_list) - 1

        self.logger.info("Direction: " + direction)
        if direction == "column":
            end_cell_cord = (start_cell_cord[0] + list_size, start_cell_cord[1])
        else:
            end_cell_cord = (start_cell_cord[0], start_cell_cord[1] + list_size)

        end_cell = gspread.utils.rowcol_to_a1(end_cell_cord[0], end_cell_cord[1])
        cell_range = start_cell + ":" + end_cell
        self.logger.info("Target range: " + str(cell_range))

        return cell_range 
Example 29
Source File: decoder.py    From lingvo with Apache License 2.0 5 votes vote down vote up
def CreateTargetInfoMisc(self, targets):
    """Return a NestedMap corresponding to the 'misc' field in TargetInfo."""
    if 'fst_bias_probs' in targets:
      return py_utils.NestedMap({
          'fst_bias_probs': targets.fst_bias_probs,
      })
    else:
      return py_utils.NestedMap() 
Example 30
Source File: custom.py    From azure-cli-extensions with MIT License 5 votes vote down vote up
def create_hpc_cache_blob_storage_target(cmd, client,
                                         resource_group_name,
                                         cache_name,
                                         name,
                                         virtual_namespace_path,
                                         clfs_target):
    body = {}
    body['junctions'] = [{'namespacePath': virtual_namespace_path, 'targetPath': '/'}]
    body['target_type'] = 'clfs'  # str
    body.setdefault('clfs', {})['target'] = clfs_target  # str
    return client.create_or_update(resource_group_name=resource_group_name, cache_name=cache_name,
                                   storage_target_name=name, storagetarget=body) 
Example 31
Source File: custom.py    From azure-cli-extensions with MIT License 5 votes vote down vote up
def create_hpc_cache_nfs_storage_target(cmd, client,
                                        resource_group_name,
                                        cache_name,
                                        name,
                                        junctions,
                                        nfs3_target,
                                        nfs3_usage_model):
    body = {}
    body['junctions'] = junctions
    body['target_type'] = 'nfs3'  # str
    body.setdefault('nfs3', {})['target'] = nfs3_target  # str
    body.setdefault('nfs3', {})['usage_model'] = nfs3_usage_model  # str
    return client.create_or_update(resource_group_name=resource_group_name, cache_name=cache_name,
                                   storage_target_name=name, storagetarget=body) 
Example 32
Source File: rpn_helpers.py    From cntk-python-web-service-on-azure with MIT License 5 votes vote down vote up
def create_proposal_target_layer(rpn_rois, scaled_gt_boxes, num_classes):
    '''
    Creates a proposal target layer that is used for training an object detection network as proposed in the "Faster R-CNN" paper:
        Shaoqing Ren and Kaiming He and Ross Girshick and Jian Sun:
        "Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks"

    Assigns object detection proposals to ground-truth targets.
    Produces proposal classification labels and bounding-box regression targets.
    It also adds gt_boxes to candidates and samples fg and bg rois for training.

    Args:
        rpn_rois:        The proposed ROIs, e.g. from a region proposal network
        scaled_gt_boxes: The ground truth boxes as (x1, y1, x2, y2, label). Coordinates are absolute pixels wrt. the input image.
        num_classes:     The number of classes in the data set

    Returns:
        rpn_target_rois - a set of rois containing the ground truth and a number of sampled fg and bg ROIs
        label_targets - the target labels for the rois
        bbox_targets - the regression coefficient targets for the rois
        bbox_inside_weights - the weights for the regression loss
    '''

    ptl_param_string = "'num_classes': {}".format(num_classes)
    ptl = user_function(ProposalTargetLayer(rpn_rois, scaled_gt_boxes, param_str=ptl_param_string))

    # use an alias if you need to access the outputs, e.g., when cloning a trained network
    rois = alias(ptl.outputs[0], name='rpn_target_rois')
    label_targets = ptl.outputs[1]
    bbox_targets = ptl.outputs[2]
    bbox_inside_weights = ptl.outputs[3]

    return rois, label_targets, bbox_targets, bbox_inside_weights 
Example 33
Source File: __init__.py    From designate with Apache License 2.0 5 votes vote down vote up
def create_pool_target_option(self, context, pool_target_id,
                                  pool_target_option):
        pool_target_option.pool_target_id = pool_target_id

        return self._create(tables.pool_target_options, pool_target_option,
                            exceptions.DuplicatePoolTargetOption) 
Example 34
Source File: __init__.py    From designate with Apache License 2.0 5 votes vote down vote up
def create_pool_target_master(self, context, pool_target_id,
                                  pool_target_master):
        pool_target_master.pool_target_id = pool_target_id

        return self._create(tables.pool_target_masters, pool_target_master,
                            exceptions.DuplicatePoolTargetMaster) 
Example 35
Source File: generator.py    From fake-bpy-module with MIT License 5 votes vote down vote up
def get_or_create_target(self, target: str):
        info = self.get_target(target)
        if info is None:
            info = self.create_target(target)
        return info 
Example 36
Source File: efs_instance.py    From Particle-Cloud-Framework with Apache License 2.0 5 votes vote down vote up
def create_mount_target(self, subnet_id, **kwargs):
        """
        Creates a mount target for a file system

        Args:
            subnet_id (string): ID of the subnet to add the mount target in
            **kwargs: options for boto3 create_mount target

        Returns:
            response of boto3 create_mount_target
        """
        return self.client.create_mount_target(FileSystemId=self.current_state_definition['FileSystemId'], SubnetId=subnet_id, **kwargs) 
Example 37
Source File: 1389-按既定顺序创建目标数组.py    From LeetCode-Python with GNU General Public License v3.0 5 votes vote down vote up
def createTargetArray(self, nums, index):
        """
        :type nums: List[int]
        :type index: List[int]
        :rtype: List[int]
        """
        res = []
        for i in range(len(nums)):
            res.insert(index[i], nums[i])
        return res 
Example 38
Source File: crate-exporter.py    From ngsi-timeseries-api with MIT License 5 votes vote down vote up
def create_target_table(self):
        table_fqn = self._table.identifier().fqn()
        cs = [f"{n} {t}" for (n, t) in self._column_specs()]
        cols = ', '.join(cs)
        return f"CREATE TABLE IF NOT EXISTS {table_fqn} ({cols});" 
Example 39
Source File: utils.py    From face-alignment with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_target_heatmap(target_landmarks, centers, scales):
    heatmaps = np.zeros((target_landmarks.shape[0], 68, 64, 64), dtype=np.float32)
    for i in range(heatmaps.shape[0]):
        for p in range(68):
            landmark_cropped_coor = transform(target_landmarks[i, p] + 1, centers[i], scales[i], 64, invert=False)
            heatmaps[i, p] = draw_gaussian(heatmaps[i, p], landmark_cropped_coor + 1, 1)
    return torch.tensor(heatmaps) 
Example 40
Source File: update-task-target.gmp.py    From gvm-tools with GNU General Public License v3.0 5 votes vote down vote up
def create_target_hosts(gmp, host_file, task_id, old_target_id):
    new_target_id = copy_send_target(gmp, host_file, old_target_id)

    gmp.modify_task(task_id=task_id, target_id=new_target_id)

    print('  Task successfully modified!\n') 
Example 41
Source File: nvt-scan.gmp.py    From gvm-tools with GNU General Public License v3.0 5 votes vote down vote up
def create_target(gmp, name):
    try:
        res = gmp.create_target(name, hosts=[name])
        target_id = res.xpath('@id')[0]
    except GvmError:
        res = gmp.get_targets(filter='name=%s hosts=%s' % (name, name))
        target_id = res.xpath('target/@id')[0]

    return target_id 
Example 42
Source File: utils.py    From openstreetmap-heatmap with Apache License 2.0 5 votes vote down vote up
def create_target(origin=(0,0,0)):
    tar = bpy.data.objects.new('Target', None)
    bpy.context.scene.objects.link(tar)
    tar.location = origin

    return tar 
Example 43
Source File: convert_stix.py    From cti-stix-slider with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_victim_target_for_threat_actor(source, target_ref, target_obj_ref_1x):
    global _VICTIM_TARGET_TTPS
    target, identity1x_tuple = choose_full_object_or_idref(target_ref, target_obj_ref_1x)
    ttp = TTP()
    ttp.victim_targeting = VictimTargeting()
    ttp.victim_targeting.identity = target
    _VICTIM_TARGET_TTPS.append(ttp)
    source.observed_ttps.append(ttp)
    identity1x_tuple[1] = True 
Example 44
Source File: convert_stix.py    From cti-stix-slider with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_exploit_target_to_ttps(ttp, target_ref, target_obj_ref_1x):
    target, vul1x_tuple = choose_full_object_or_idref(target_ref, target_obj_ref_1x)
    ttp.add_exploit_target(target)
    vul1x_tuple[1] = True


# most of the TODOs in this map represent relationships not explicitly called out in STIX 1.x 
Example 45
Source File: convert_stix.py    From cti-stix-slider with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_victim_target_for_attack_pattern(ttp, target_ref, target_obj_ref_1x):
    global _VICTIM_TARGET_TTPS
    target, identity1x_tuple = choose_full_object_or_idref(target_ref, target_obj_ref_1x)
    ttp.victim_targeting = VictimTargeting()
    ttp.victim_targeting.identity = target
    _VICTIM_TARGET_TTPS.append(ttp)
    identity1x_tuple[1] = True 
Example 46
Source File: region_loss.py    From models with MIT License 5 votes vote down vote up
def create_target(pred_corners, gt_points, noobject_scale=0.1,
                  object_scale=5, sil_thresh=0.6):
    xp = chainer.cuda.get_array_module(pred_corners)
    B, _, _, H, W = pred_corners.shape
    B = len(gt_points)

    conf_mask = noobject_scale * xp.ones((B, H, W), dtype=np.bool)
    coord_mask = xp.zeros((B, H, W), dtype=np.bool)
    gt_confs = xp.zeros((B, H, W), dtype=np.float32)
    gt_rpoints = xp.zeros((B, 9, 2, H, W), dtype=np.float32)

    for b, (pred_corner, gt_point) in enumerate(
            zip(pred_corners, gt_points)):
        conf = xp.zeros((H, W), dtype=np.float32)
        for gt_pt in gt_point:
            conf = xp.maximum(
                conf, corner_confidences9(gt_pt, pred_corner))
        conf_mask[b][conf > sil_thresh] = 0

    for b, (pred_corner, gt_point) in enumerate(
            zip(pred_corners, gt_points)):
        for gt_pt in gt_point:
            # NOTE: 0 <= gt_pt[0, 1] - gi0 < 1
            gi0 = int(xp.floor(gt_pt[0, 1] * W))
            gj0 = int(xp.floor(gt_pt[0, 0] * H))
            conf = corner_confidences9(
                gt_pt, pred_corner[:, :, gi0, gj0])

            conf_mask[b, gi0, gj0] = object_scale
            coord_mask[b, gi0, gj0] = 1
            gt_confs[b, gi0, gj0] = conf
            gt_rpoints[b, :, 0, gi0, gj0] = gt_pt[:, 0] * W - gj0
            gt_rpoints[b, :, 1, gi0, gj0] = gt_pt[:, 1] * H - gi0
    return gt_rpoints, gt_confs, coord_mask, conf_mask 
Example 47
Source File: handlers.py    From aws-syndicate with Apache License 2.0 5 votes vote down vote up
def create_deploy_target_bucket():
    """
    Creates a bucket in AWS account where all bundles will be uploaded
    :return:
    """
    from syndicate.core import CONFIG
    click.echo('Create deploy target sdk: %s' % CONFIG.deploy_target_bucket)
    create_bundles_bucket()
    click.echo('Deploy target bucket was created successfully') 
Example 48
Source File: diagrams_common.py    From sphinxcontrib-needs with MIT License 5 votes vote down vote up
def create_target(self, target_name):
        env = self.state.document.settings.env
        id = env.new_serialno(target_name)
        targetid = "{targetname}-{docname}-{id}".format(
            targetname=target_name,
            docname=env.docname,
            id=id)
        targetnode = nodes.target('', '', ids=[targetid])

        return id, targetid, targetnode 
Example 49
Source File: import_data.py    From urbanfootprint with GNU General Public License v3.0 5 votes vote down vote up
def create_target_db_string(self):
        self.target_database_connection = "-h {0} -p {1} --user {2} {3}".format(
            self.target_database.get('HOST', 'localhost'),
            self.target_database.get('PORT', 5432),
            self.target_database['USER'],
            self.target_database['NAME'])
        logger.info("Using target database connection: {0}".format(self.target_database_connection)) 
Example 50
Source File: deploy-malmirror.py    From Cloud-Security-Research with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_mirror_target_sg(session, region, target_vpc_id):
    ec2_client = session.client('ec2', region_name=region)

    sg_id = ec2_client.create_security_group(
        GroupName=random_string(),
        Description=random_string(),
        VpcId=target_vpc_id
    )['GroupId']

    ec2_client.authorize_security_group_ingress(
        GroupId=sg_id,
        IpPermissions=[
            {
                'FromPort': 4789,
                'ToPort': 4789,
                'IpProtocol': 'udp',
                'IpRanges': [
                    {
                        'CidrIp': '10.0.0.0/8'
                    },
                    {
                        'CidrIp': '172.16.0.0/12'
                    },
                    {
                        'CidrIp': '192.168.0.0/16'
                    }
                ]
            }
        ]
    )

    return sg_id 
Example 51
Source File: deploy-malmirror.py    From Cloud-Security-Research with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_mirror_target(session, region, target_eni_id):
    ec2_client = session.client('ec2', region_name=region)

    return ec2_client.create_traffic_mirror_target(
        NetworkInterfaceId=target_eni_id
    )['TrafficMirrorTarget']['TrafficMirrorTargetId'] 
Example 52
Source File: rpn_helpers.py    From raster-deep-learning with Apache License 2.0 5 votes vote down vote up
def create_proposal_target_layer(rpn_rois, scaled_gt_boxes, cfg):
    '''
    Creates a proposal target layer that is used for training an object detection network as proposed in the "Faster R-CNN" paper:
        Shaoqing Ren and Kaiming He and Ross Girshick and Jian Sun:
        "Faster R-CNN: Towards Real-Time Object Detection with Region Proposal Networks"

    Assigns object detection proposals to ground-truth targets.
    Produces proposal classification labels and bounding-box regression targets.
    It also adds gt_boxes to candidates and samples fg and bg rois for training.

    Args:
        rpn_rois:        The proposed ROIs, e.g. from a region proposal network
        scaled_gt_boxes: The ground truth boxes as (x1, y1, x2, y2, label). Coordinates are absolute pixels wrt. the input image.
        num_classes:     The number of classes in the data set

    Returns:
        rpn_target_rois - a set of rois containing the ground truth and a number of sampled fg and bg ROIs
        label_targets - the target labels for the rois
        bbox_targets - the regression coefficient targets for the rois
        bbox_inside_weights - the weights for the regression loss
    '''

    ptl_param_string = "'num_classes': {}".format(cfg["DATA"].NUM_CLASSES)
    ptl = user_function(ProposalTargetLayer(rpn_rois, scaled_gt_boxes,
                                            batch_size=cfg.NUM_ROI_PROPOSALS,
                                            fg_fraction=cfg["TRAIN"].FG_FRACTION,
                                            normalize_targets=cfg.BBOX_NORMALIZE_TARGETS,
                                            normalize_means=cfg.BBOX_NORMALIZE_MEANS,
                                            normalize_stds=cfg.BBOX_NORMALIZE_STDS,
                                            fg_thresh=cfg["TRAIN"].FG_THRESH,
                                            bg_thresh_hi=cfg["TRAIN"].BG_THRESH_HI,
                                            bg_thresh_lo=cfg["TRAIN"].BG_THRESH_LO,
                                            param_str=ptl_param_string))

    # use an alias if you need to access the outputs, e.g., when cloning a trained network
    rois = alias(ptl.outputs[0], name='rpn_target_rois')
    label_targets = ptl.outputs[1]
    bbox_targets = ptl.outputs[2]
    bbox_inside_weights = ptl.outputs[3]

    return rois, label_targets, bbox_targets, bbox_inside_weights 
Example 53
Source File: cherry_sac.py    From cherry with Apache License 2.0 5 votes vote down vote up
def create_target_network(network):
    target_network = copy.deepcopy(network)
    for param in target_network.parameters():
        param.requires_grad = False
    return target_network 
Example 54
Source File: data_io.py    From sockeye with Apache License 2.0 5 votes vote down vote up
def create_target_and_shifted_label_sequences(target_and_label: mx.nd.NDArray) -> Tuple[mx.nd.NDArray, mx.nd.NDArray]:
    """
    Returns the target and label sequence from a joint array of varying-length sequences including both <bos> and <eos>.
    Both ndarrays returned have input size of second dimension - 1.
    """
    target = target_and_label[:, :-1]  # skip last column (for longest-possible sequence, this already removes <eos>)
    target = mx.nd.where(target == C.EOS_ID, mx.nd.zeros_like(target), target)  # replace other <eos>'s with <pad>
    label = target_and_label[:, 1:]  # label skips <bos>
    return target, label 
Example 55
Source File: db_manager.py    From recon-pipeline with MIT License 5 votes vote down vote up
def get_or_create_target_by_ip_or_hostname(self, ip_or_host):
        """ Simple helper to query a Target record by either hostname or ip address, whichever works """
        # get existing instance
        instance = (
            self.session.query(Target)
            .filter(
                or_(
                    Target.ip_addresses.any(
                        or_(IPAddress.ipv4_address.in_([ip_or_host]), IPAddress.ipv6_address.in_([ip_or_host]))
                    ),
                    Target.hostname == ip_or_host,
                )
            )
            .first()
        )
        if instance:
            return instance
        else:
            # create new entry
            tgt = self.get_or_create(Target)

            if get_ip_address_version(ip_or_host) == "4":
                tgt.ip_addresses.append(IPAddress(ipv4_address=ip_or_host))
            elif get_ip_address_version(ip_or_host) == "6":
                tgt.ip_addresses.append(IPAddress(ipv6_address=ip_or_host))
            else:
                # we've already determined it's not an IP, only other possibility is a hostname
                tgt.hostname = ip_or_host

            return tgt 
Example 56
Source File: clb_client.py    From tencentcloud-cli with Apache License 2.0 5 votes vote down vote up
def doCreateTargetGroup(argv, arglist):
    g_param = parse_global_arg(argv)
    if "help" in argv:
        show_help("CreateTargetGroup", g_param[OptionsDefine.Version])
        return

    param = {
        "TargetGroupName": argv.get("--TargetGroupName"),
        "VpcId": argv.get("--VpcId"),
        "Port": Utils.try_to_json(argv, "--Port"),
        "TargetGroupInstances": Utils.try_to_json(argv, "--TargetGroupInstances"),

    }
    cred = credential.Credential(g_param[OptionsDefine.SecretId], g_param[OptionsDefine.SecretKey])
    http_profile = HttpProfile(
        reqTimeout=60 if g_param[OptionsDefine.Timeout] is None else int(g_param[OptionsDefine.Timeout]),
        reqMethod="POST",
        endpoint=g_param[OptionsDefine.Endpoint]
    )
    profile = ClientProfile(httpProfile=http_profile, signMethod="HmacSHA256")
    mod = CLIENT_MAP[g_param[OptionsDefine.Version]]
    client = mod.ClbClient(cred, g_param[OptionsDefine.Region], profile)
    client._sdkVersion += ("_CLI_" + __version__)
    models = MODELS_MAP[g_param[OptionsDefine.Version]]
    model = models.CreateTargetGroupRequest()
    model.from_json_string(json.dumps(param))
    rsp = client.CreateTargetGroup(model)
    result = rsp.to_json_string()
    jsonobj = None
    try:
        jsonobj = json.loads(result)
    except TypeError as e:
        jsonobj = json.loads(result.decode('utf-8')) # python3.3
    FormatOutput.output("action", jsonobj, g_param[OptionsDefine.Output], g_param[OptionsDefine.Filter]) 
Example 57
Source File: net_plotter.py    From loss-landscape with MIT License 5 votes vote down vote up
def create_target_direction(net, net2, dir_type='states'):
    """
        Setup a target direction from one model to the other

        Args:
          net: the source model
          net2: the target model with the same architecture as net.
          dir_type: 'weights' or 'states', type of directions.

        Returns:
          direction: the target direction from net to net2 with the same dimension
                     as weights or states.
    """

    assert (net2 is not None)
    # direction between net2 and net
    if dir_type == 'weights':
        w = get_weights(net)
        w2 = get_weights(net2)
        direction = get_diff_weights(w, w2)
    elif dir_type == 'states':
        s = net.state_dict()
        s2 = net2.state_dict()
        direction = get_diff_states(s, s2)

    return direction 
Example 58
Source File: repo2gospec.py    From gofed with GNU General Public License v2.0 5 votes vote down vote up
def createTargetDirectories(name, target = ""):
	if target == "":
		target = "%s/%s" % (os.getcwd(), name)
	else:
		target = os.path.abspath("%s/%s" % (target, name) )

	make_sure_path_exists(target)
	os.chdir(target)