Question:
Boot class Inicializa el plugin
@return void

public function boot() {
		$this->emitter = new Emitter;
		$this->query = new QueryRepository();
		//Busca las acciones definidas en el plugin y las agrega como acciones de Wordpress
		$this->add_actions();
		add_action('cmb2_admin_init', array($this, 'add_metaboxes'), 1000);
	}

public function initialize($name = "Unknown", $icon = null){
        if($this->em->getRepository(PageType::class)->findOneByTitle($name) === null){
            $type = new PageType();
            $type->setTitle($name);
            $type->setIcon($icon);
            $this->em->persist($type);
            $this->em->flush();
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // GET /monitoring_center/{server_id}

func (api *API) GetMonitoringServerUsage(ser_id string, period string, dates ...time.Time) (*MonServerUsageDetails, error) {
	if period == "" {
		return nil, errors.New("Time period must be provided.")
	}

	params := make(map[string]interface{}, len(dates)+1)
	params["period"] = period

	if len(dates) == 2 {
		if dates[0].After(dates[1]) {
			return nil, errors.New("Start date cannot be after end date.")
		}

		params["start_date"] = dates[0].Format(time.RFC3339)
		params["end_date"] = dates[1].Format(time.RFC3339)

	} else if len(dates) > 0 {
		return nil, errors.New("Start and end dates must be provided.")
	}
	url := createUrl(api, monitorCenterPathSegment, ser_id)
	url = appendQueryParams(url, params)
	result := new(MonServerUsageDetails)
	err := api.Client.Get(url, &result, http.StatusOK)
	if err != nil {
		return nil, err
	}
	result.api = api
	return result, nil
}

func (s *UsageService) DeleteTrafficMonitor(p *DeleteTrafficMonitorParams) (*DeleteTrafficMonitorResponse, error) {
	resp, err := s.cs.newRequest("deleteTrafficMonitor", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r DeleteTrafficMonitorResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
/*
Return the index of the median of three elements in the specified array range -- the
first, the last, and the one in the middle.

public static int median(final Object[] a, int start, int end, Comparator<Object> cmp)
    {
        final int m = start + ((end - start) / 2);
        int smallest = start;

        if (cmp.compare(a[smallest], a[m]) > 0) {
            smallest = m;
        }
        if (cmp.compare(a[smallest], a[end]) > 0) {
            smallest = end;
        }

        if (smallest == start) {
            return (cmp.compare(a[m], a[end]) < 0) ? m : end;
        }
        if (smallest == m) {
            return (cmp.compare(a[start], a[end]) < 0) ? start : end;
        }
        return (cmp.compare(a[start], a[m]) < 0) ? start : m;
    }

@SuppressWarnings("unchecked")
	private void siftDown (int k, E x) {
		int half = size >>> 1; // loop while a non-leaf
		while (k < half) {
			int child = (k << 1) + 1; // assume left child is least
			E c = (E)queue[child];
			int right = child + 1;
			if (right < size && c.compareTo((E)queue[right]) > 0) c = (E)queue[child = right];
			if (x.compareTo(c) <= 0) break;
			queue[k] = c;
			k = child;
		}
		queue[k] = x;
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Gets the rendered STEAM_X:Y:Z format.
@param bool $newerFormat If the universe is public, should X be 1 instead of 0?
@return string
@throws Exception If this isn't an individual account SteamID

public function getSteam2RenderedID($newerFormat = false) {
		if ($this->type != self::TYPE_INDIVIDUAL) {
			throw new Exception("Can't get Steam2 rendered ID for non-individual ID");
		} else {
			$universe = $this->universe;
			if ($universe == 1 && !$newerFormat) {
				$universe = 0;
			}

			return 'STEAM_' . $universe . ':' . ($this->accountid & 1) . ':' . floor($this->accountid / 2);
		}
	}

func ParseStellarSecretKey(secStr string) (stellar1.SecretKey, stellar1.AccountID, *keypair.Full, error) {
	secStr = strings.ToUpper(secStr)
	if len(secStr) != 56 {
		return "", "", nil, fmt.Errorf("Stellar secret key must be 56 chars long: was %v", len(secStr))
	}
	_, err := base32.StdEncoding.DecodeString(secStr)
	if err != nil {
		return "", "", nil, fmt.Errorf("invalid characters in Stellar secret key")
	}
	kp, err := keypair.Parse(secStr)
	if err != nil {
		return "", "", nil, fmt.Errorf("invalid Stellar secret key: %v", err)
	}
	switch kp := kp.(type) {
	case *keypair.FromAddress:
		return "", "", nil, errors.New("unexpected Stellar account ID, expected secret key")
	case *keypair.Full:
		return stellar1.SecretKey(kp.Seed()), stellar1.AccountID(kp.Address()), kp, nil
	default:
		return "", "", nil, fmt.Errorf("invalid Stellar secret key")
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question: Return a random point inside the box

def generate(self):
        """"""
        x, y, z = self.point1
        return (x + self.size_x * random(),
                y + self.size_y * random(),
                z + self.size_z * random())

def draw(self, ar, can, x_tick, x_label, y):
        """"""

        rect_size = self.get_rect_size()
        line_len = self.get_line_len()

        nr_lines = len(self.label.split("\n"))
        text_height = font.text_height(self.label)[0]
        line_height = text_height / float(nr_lines)
        y_center = y + text_height - line_height / 1.5

        if self.fill_style != None:
            can.rectangle(self.line_style, self.fill_style,
                          x_tick, y_center - rect_size / 2.0,
                          x_tick + rect_size,
                          y_center + rect_size / 2.0)
        elif self.line_style != None:
            can.line(self.line_style, x_tick, y_center,
                     x_tick + line_len, y_center)
            if self.tick_mark != None:
                self.tick_mark.draw(can, x_tick + line_len / 2.0, y_center)
        elif self.tick_mark != None:
            self.tick_mark.draw(can, x_tick, y_center)

        can.show(x_label, y, self.label)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns the ready condition of the node.

@param node The target node.
@return The {@link NodeCondition} or null if not found.

private static NodeCondition getNodeReadyCondition(Node node) {
    Utils.checkNotNull(node, "Node can't be null.");

    if (node.getStatus() == null || node.getStatus().getConditions() == null) {
      return null;
    }

    for (NodeCondition condition : node.getStatus().getConditions()) {
      if (NODE_READY.equals(condition.getType())) {
        return condition;
      }
    }
    return null;
  }

def get_nodes_with_role(role_name, environment=None):

    prefix_search = role_name.endswith("*")
    if prefix_search:
        role_name = role_name.rstrip("*")
    for n in get_nodes(environment):
        roles = get_roles_in_node(n, recursive=True)
        if prefix_search:
            if any(role.startswith(role_name) for role in roles):
                yield n
        else:
            if role_name in roles:
                yield n

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetDetectionStatus sets the DetectionStatus field's value.

func (s *DescribeStackDriftDetectionStatusOutput) SetDetectionStatus(v string) *DescribeStackDriftDetectionStatusOutput {
	s.DetectionStatus = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

    if (isLog(4)) {
      log("change getfield " + owner + " name:" + name);
    }
    typeQueryUser = true;
  }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Exit admin mode
@param ctx       Internal parameter. Not user-accessible.
@return          Standard STATUS table.

public VoltTable[] run(SystemProcedureExecutionContext ctx) {
        // Choose the lowest site ID on this host to actually flip the bit
        VoltDBInterface voltdb = VoltDB.instance();
        OperationMode opMode = voltdb.getMode();

        if (ctx.isLowestSiteId()) {
            ZooKeeper zk = voltdb.getHostMessenger().getZK();
            try {
                Stat stat;
                OperationMode zkMode = null;
                Code code;
                do {
                    stat = new Stat();
                    code = Code.BADVERSION;
                    try {
                        byte [] data = zk.getData(VoltZK.operationMode, false, stat);
                        zkMode = data == null ? opMode : OperationMode.valueOf(data);
                        if (zkMode == RUNNING) {
                            break;
                        }
                        stat = zk.setData(VoltZK.operationMode, RUNNING.getBytes(), stat.getVersion());
                        code = Code.OK;
                        zkMode = RUNNING;
                        break;
                    } catch (BadVersionException ex) {
                        code = ex.code();
                    }
                } while (zkMode != RUNNING && code == Code.BADVERSION);

                m_stat = stat;
                voltdb.getHostMessenger().unpause();
                voltdb.setMode(RUNNING);
                // for snmp
                SnmpTrapSender snmp = voltdb.getSnmpTrapSender();
                if (snmp != null) {
                    snmp.resume("Cluster resumed.");
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        VoltTable t = new VoltTable(VoltSystemProcedure.STATUS_SCHEMA);
        t.addRow(VoltSystemProcedure.STATUS_OK);
        return new VoltTable[] {t};
    }

public function collStats(Query $query)
    {
        $options = $query->getOptions();

        $cmd     = ['collStats' => $options['table']];
        $command = new Command($cmd);

        $this->log('cmd', 'collStats', $cmd);

        return $command;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Set counter of ``name`` to ``num``.

def set_to(cls, name, num):
        """"""
        if num < 0:
            raise CounterValueError('Counter[%s] can not be set to %s' % (
                                    name, num))
        else:
            counter = cls.collection.find_and_modify(
                {'name': name},
                {'$set': {'seq': num}},
                new=True,
                upsert=True
            )
            return counter['seq']

def update_blocknumbers(blk)
      loop do
        if blk.number > 0
          @db.put_temporarily block_by_number_key(blk.number), blk.full_hash
        else
          @db.put block_by_number_key(blk.number), blk.full_hash
        end
        @db.commit_refcount_changes blk.number

        break if blk.number == 0

        blk = blk.get_parent()
        break if has_block_by_number(blk.number) && get_block_by_number(blk.number) == blk.full_hash
      end
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param string|RoleInterface $role

@return RouteInterface

public function addRole($role): RouteInterface
    {
        if (is_string($role)) {
            $this->roles[] = new GenericRole($role);
        } elseif (!$role instanceof RoleInterface) {
            throw new InvalidArgumentException(
                'addRole() expects $role to be of type Zend\Permissions\Acl\Role\RoleInterface'
            );
        }

        return $this;
    }

func (t *Template) GetAllAWSElastiCacheParameterGroupResources() map[string]*resources.AWSElastiCacheParameterGroup {
	results := map[string]*resources.AWSElastiCacheParameterGroup{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSElastiCacheParameterGroup:
			results[name] = resource
		}
	}
	return results
}

Instruction: Given a code description, retrieve the corresponding code.


Question: [str] 国民经济行业分类名称（股票专用）

def industry_name(self):

        try:
            return self.__dict__["industry_name"]
        except (KeyError, ValueError):
            raise AttributeError(
                "Instrument(order_book_id={}) has no attribute 'industry_name' ".format(self.order_book_id)
            )

function renderSimpleRuby( $ruby ) {
  var frag = $.create( '!' )
  var clazz = $ruby.classList
  var $rb, $ru

  frag.appendChild( $.clone( $ruby ))

  $
  .tag( 'rt', frag.firstChild )
  .forEach(function( $rt ) {
    var $rb = $.create( '!' )
    var airb = []
    var irb

    // Consider the previous nodes the implied
    // ruby base
    do {
      irb = ( irb || $rt ).previousSibling
      if ( !irb || irb.nodeName.match( /((?:h\-)?r[ubt])/i ))  break

      $rb.insertBefore( $.clone( irb ), $rb.firstChild )
      airb.push( irb )
    } while ( !irb.nodeName.match( /((?:h\-)?r[ubt])/i ))

    // Create a real `<h-ru>` to append.
    $ru = clazz.contains( 'zhuyin' ) ? createZhuyinRu( $rb, $rt ) : createNormalRu( $rb, $rt )

    // Replace the ruby text with the new `<h-ru>`,
    // and remove the original implied ruby base(s)
    try {
      $rt.parentNode.replaceChild( $ru, $rt )
      airb.map( $.remove )
    } catch ( e ) {}
  })
  return createCustomRuby( frag )
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
// Attempt to parse the given string as a configuration
// It may return a error if the parsing fails

func (c *ConfigParser) ReadString(s string) (err error) {
	r := strings.NewReader(s)
	return c.Read(r)
}

protected function validateConfig()
    {
        $message = null;
        if (empty($this->config['api_key'])) {
            $message = 'Geocoder Config: Api Key is mandatory for using Google API.';
        }
        elseif (empty($this->config['request_url'])) {
            $message = 'Geocoder Config: Request URL is mandatory for using Google API.';
        }
        elseif (empty($this->config['output_format'])) {
            $message = 'Geocoder Config: Output Format is mandatory for using Google API.';
        }
        elseif ( ! in_array($this->config['output_format'], self::SUPPORTED_FORMATS)) {
            $message = 'Geocoder Config: Given Format is not supported.';
        }

        if ($message) {
            throw  new \InvalidArgumentException($message);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // MakeTagsKey converts a tag set to bytes for use as a lookup key.

func MakeTagsKey(keys []string, tags models.Tags) []byte {
	// precondition: keys is sorted
	// precondition: models.Tags is sorted

	// Empty maps marshal to empty bytes.
	if len(keys) == 0 || len(tags) == 0 {
		return nil
	}

	sel := make([]int, 0, len(keys))

	sz := 0
	i, j := 0, 0
	for i < len(keys) && j < len(tags) {
		if keys[i] < string(tags[j].Key) {
			i++
		} else if keys[i] > string(tags[j].Key) {
			j++
		} else {
			sel = append(sel, j)
			sz += len(keys[i]) + len(tags[j].Value)
			i++
			j++
		}
	}

	if len(sel) == 0 {
		// no tags matched the requested keys
		return nil
	}

	sz += (len(sel) * 2) - 1 // selected tags, add separators

	// Generate marshaled bytes.
	b := make([]byte, sz)
	buf := b
	for _, k := range sel {
		copy(buf, tags[k].Key)
		buf[len(tags[k].Key)] = '|'
		buf = buf[len(tags[k].Key)+1:]
	}

	for i, k := range sel {
		copy(buf, tags[k].Value)
		if i < len(sel)-1 {
			buf[len(tags[k].Value)] = '|'
			buf = buf[len(tags[k].Value)+1:]
		}
	}

	return b
}

public function set(string $uri, string $query, EsiResponse $data)
    {

        if ($this->is_memcached)
            $this->memcached->set($this->buildCacheKey($uri, $query), serialize($data), 0);
        else
            $this->memcached->set($this->buildCacheKey($uri, $query), serialize($data), $this->flags, 0);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get a block setting.

Originally, this was just used for the home-page blocks.  Now, it is used by any
module that has repeated blocks of content on the same page.

@param int    $block_id
@param string $setting_name
@param string $default

@return string

final protected function getBlockSetting(int $block_id, string $setting_name, string $default = ''): string
    {
        $settings = app('cache.array')->rememberForever('block_setting' . $block_id, static function () use ($block_id): array {
            return DB::table('block_setting')
                ->where('block_id', '=', $block_id)
                ->pluck('setting_value', 'setting_name')
                ->all();
        });

        return $settings[$setting_name] ?? $default;
    }

protected function build($template)
    {
        $this->body['flash'] = array();
        if(isset($_SESSION['flash']['message'])) {
            $this->body['flash']['message'] = $_SESSION['flash']['message'];
            $this->body['flash']['type'] = $_SESSION['flash']['type'];
            unset($_SESSION['flash']);
        }

        $body = $this->parse($template, $this->body);

        $page = array(
            'flash' => $this->body['flash'],
            'meta' => $this->meta,
            'links' => $this->links,
            'styles' => $this->styles,
            'scripts' => $this->scripts,
            'title' => $this->title,
            'class' => $this->id,
            'head' => $this->head,
            'body' => $body,
            'foot' => $this->foot);

        $page = $this->parse($this->layout, $page);

        $this->response
            ->set('headers', 'Content-Type', 'text/html; charset=utf-8')
            ->set('body', $page);

        return $page;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Remove a selector from the page.
@param {Object} selector CSS selector as returned by
@param {Boolean} incremental If true all selectors except "selector" are removed, otherwise only "selector" is
removed
@see extractSelectors

function (selector, incremental) {
        if (!selector) {
            // This is a baseline
            if (incremental) {
                // Everything should be removed
                refreshCSS(true);
            } else {
                // Nothing should be removed
                return;
            }
        } else {
            var textLoaded = aria.templates.CSSMgr.__textLoaded[selector.location];
            // remember the original text
            selector.original = textLoaded.text;
            if (incremental) {
                // Keep only the selector
                refreshCSS(true, selector.descriptor);
            } else {
                // Remove the selector
                textLoaded.text = textLoaded.text.replace(selector.descriptor, "");
                refreshCSS();
            }
        }
    }

private function copy(array $sources, $dest, $minify)
    {
        // create destination path if not exists

        $ext = pathinfo($dest, PATHINFO_EXTENSION);
        $dir = !empty($ext) ? dirname($dest) : $dest;
        if (!file_exists($dir)) {
            if (!make_dir($dir, 0775)) {
                throw new RuntimeException('Unable to create directory ' . $dir); // @codeCoverageIgnore
            }
        }

        // list all source files into a flat array

        $files = [];
        foreach ($sources as $source) {
            if (is_dir($source)) {
                if ($ext == 'js') {
                    $filter = ['js'];
                }
                else if ($ext == 'css') {
                    $filter = ['css', 'less', 'scss'];
                }
                else {
                    $filter = null;
                }
                list_files($files, $source, $filter);
            }
            else {
                $files[] = $source;
            }
        }

        // copy all files to the destination

        if (file_exists($dest) && !is_dir($dest)) {
            unlink($dest);
        } // @codeCoverageIgnore

        foreach ($files as $file) {
            // get content
            $content = file_get_contents($file);

            // compile
            $srcExt = pathinfo($file, PATHINFO_EXTENSION);
            switch ($srcExt) {
                case 'less':
//                    $content = (new LessCompiler)->compile($content);
                    $content = (new LessCompiler)->parse($content)->getCss();
                    break;
                case 'scss':
                    $content = (new SCSSCompiler)->compile($content);
                    break;
            }

            // minimize
            if ($minify) {
                switch ($srcExt) {
                    case 'js':
                        $content = JSMin::minify($content);
                        break;
                    case 'css':
                    case 'less':
                    case 'scss':
                        $content = CssMin::minify($content);
                        break;
                }
            }

            // save content
            if (is_dir($dest)) {
                $success = file_put_contents($dest . DIRECTORY_SEPARATOR . basename($file), $content, LOCK_EX);
                //@chmod($dest . DIRECTORY_SEPARATOR . basename($file), 0664);
            }
            else {
                // concatenate the files to a single file
                if (file_exists($dest)) {
                    $success = file_put_contents($dest, PHP_EOL . $content, FILE_APPEND | LOCK_EX);
                }
                else {
                    $success = file_put_contents($dest, $content, LOCK_EX);
                    //@chmod($dest, 0664);
                }
            }
            if ($success === false) {
                throw new RuntimeException(sprintf('Asset Manager was not able to copy "%s" to "%s"', $file, $dest)); // @codeCoverageIgnore
            }
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Recursively copies all items in the source directory or file to the target directory.

@param string $source Source dir/file to copy
@param string $target Place to copy the source
@param int    $mode   What to chmod the file to

public function copyAll($source, $target, $mode = null)
    {
        if (is_dir($source)) {
            if ($mode == null) {
                @mkdir($target, Config::get('concrete.filesystem.permissions.directory'));
                @chmod($target, Config::get('concrete.filesystem.permissions.directory'));
            } else {
                @mkdir($target, $mode);
                @chmod($target, $mode);
            }

            $d = dir($source);
            while (false !== ($entry = $d->read())) {
                if (substr($entry, 0, 1) === '.') {
                    continue;
                }

                $Entry = $source . '/' . $entry;
                if (is_dir($Entry)) {
                    $this->copyAll($Entry, $target . '/' . $entry, $mode);
                    continue;
                }

                copy($Entry, $target . '/' . $entry);
                if ($mode == null) {
                    @chmod($target . '/' . $entry, $this->getCreateFilePermissions($target)->file);
                } else {
                    @chmod($target . '/' . $entry, $mode);
                }
            }

            $d->close();
        } else {
            if ($mode == null) {
                $mode = $this->getCreateFilePermissions(dirname($target))->file;
            }
            copy($source, $target);
            chmod($target, $mode);
        }
    }

func MakeFileExistsFunc(baseDir string) function.Function {
	return function.New(&function.Spec{
		Params: []function.Parameter{
			{
				Name: "path",
				Type: cty.String,
			},
		},
		Type: function.StaticReturnType(cty.Bool),
		Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
			path := args[0].AsString()
			path, err := homedir.Expand(path)
			if err != nil {
				return cty.UnknownVal(cty.Bool), fmt.Errorf("failed to expand ~: %s", err)
			}

			if !filepath.IsAbs(path) {
				path = filepath.Join(baseDir, path)
			}

			// Ensure that the path is canonical for the host OS
			path = filepath.Clean(path)

			fi, err := os.Stat(path)
			if err != nil {
				if os.IsNotExist(err) {
					return cty.False, nil
				}
				return cty.UnknownVal(cty.Bool), fmt.Errorf("failed to stat %s", path)
			}

			if fi.Mode().IsRegular() {
				return cty.True, nil
			}

			return cty.False, fmt.Errorf("%s is not a regular file, but %q",
				path, fi.Mode().String())
		},
	})
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns the value mapped by {@code key} if it exists and is a List of {@code T}. Returns null
otherwise.

public <T extends ValueMap> List<T> getList(Object key, Class<T> clazz) {
    Object value = get(key);
    if (value instanceof List) {
      List list = (List) value;
      try {
        ArrayList<T> real = new ArrayList<>();
        for (Object item : list) {
          T typedValue = coerceToValueMap(item, clazz);
          if (typedValue != null) {
            real.add(typedValue);
          }
        }
        return real;
      } catch (Exception ignored) {
      }
    }
    return null;
  }

public boolean isMapped(Class<?> classToCheck){
		return    !isNull(loadGlobals().get(classToCheck.getName()))
			   || !isEmpty(loadAttributes().get(classToCheck.getName()));
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Adds controller prefix to all collection routes.

@param string $prefix

public function prependRouteControllersWithPrefix($prefix)
    {
        foreach (parent::all() as $route) {
            $route->setDefault('_controller', $prefix.$route->getDefault('_controller'));
        }
    }

public static List<String> parseConnectionPrefixes(Config config, SharedRestClientKey key) throws URISyntaxException, NotConfiguredException {
    if (key instanceof UriRestClientKey) {
      return Lists.newArrayList(((UriRestClientKey) key).getUri());
    }

    if (!config.hasPath(SERVER_URI_KEY)) {
      throw new NotConfiguredException("Missing key " + SERVER_URI_KEY);
    }

    List<String> uris = Lists.newArrayList();
    for (String uri : Splitter.on(",").omitEmptyStrings().trimResults().splitToList(config.getString(SERVER_URI_KEY))) {
      uris.add(resolveUriPrefix(new URI(uri)));
    }
    return uris;
  }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Encode an integer

@param  integer $data The integer to be encoded.
@return string  Returns the bencode encoded integer.

private function encodeInteger($data = null)
    {
        $data = is_null($data) ? $this->data : $data;
        return sprintf("i%.0fe", $data);
    }

def bytes_to_int(byte_array, big_endian=True, signed=False):

    if six.PY3:
        order = 'little'
        if big_endian:
            order = 'big'
        return int.from_bytes(byte_array, byteorder=order, signed=signed)
    else:
        length = len(byte_array)
        if length == 1:
            code = 'B'
        elif length == 2:
            code = 'H'
        elif length == 4:
            code = 'L'
        elif length == 8:
            code = 'Q'
        else:
            raise Exception("bytes_to_int : length of byte_array should be 1, 2, 4, or 8")
        if big_endian:
            code = '>'+code
        else:
            code = '<'+code

        if signed:
            code = code.lower()
        return struct.unpack(code, byte_array)[0]

Instruction: Given a code description, retrieve the corresponding code.


Question:
Sends off a request to Simbad to check whether a target is recognised.
    Returns with a list of results, or raises an exception if it times out

def checkSimbad(g, target, maxobj=5, timeout=5):

    url = 'http://simbad.u-strasbg.fr/simbad/sim-script'
    q = 'set limit ' + str(maxobj) + \
        '\nformat object form1 "Target: %IDLIST(1) | %COO(A D;ICRS)"\nquery ' \
        + target
    query = urllib.parse.urlencode({'submit': 'submit script', 'script': q})
    resp = urllib.request.urlopen(url, query.encode(), timeout)
    data = False
    error = False
    results = []
    for line in resp:
        line = line.decode()
        if line.startswith('::data::'):
            data = True
        if line.startswith('::error::'):
            error = True
        if data and line.startswith('Target:'):
            name, coords = line[7:].split(' | ')
            results.append(
                {'Name': name.strip(), 'Position': coords.strip(),
                 'Frame': 'ICRS'})
    resp.close()

    if error and len(results):
        g.clog.warn('drivers.check: Simbad: there appear to be some ' +
                    'results but an error was unexpectedly raised.')
    return results

def is_correct(self):

        state = True

        # Internal checks before executing inherited function...
        cls = self.__class__
        if hasattr(self, 'host_name'):
            for char in cls.illegal_object_name_chars:
                if char in self.host_name:
                    self.add_error("[%s::%s] host_name contains an illegal character: %s"
                                   % (self.my_type, self.get_name(), char))
                    state = False

        # Fred: do not alert about missing check_command for an host... this because 1/ it is
        # very verbose if hosts are not checked and 2/ because it is the Nagios default behavior
        # if not self.check_command:
        #     self.add_warning("[%s::%s] has no defined check command"
        #                      % (self.my_type, self.get_name()))

        if self.notifications_enabled and not self.contacts:
            self.add_warning("[%s::%s] notifications are enabled but no contacts nor "
                             "contact_groups property is defined for this host"
                             % (self.my_type, self.get_name()))

        return super(Host, self).is_correct() and state

Instruction: Given a code description, retrieve the corresponding code.


Question: Attempt to create a rule given the list of prerequisites.

def attempt_rule(task_name, task_pattern, args, extensions, block, level)
      sources = make_sources(task_name, task_pattern, extensions)
      prereqs = sources.map { |source|
        trace_rule level, "Attempting Rule #{task_name} => #{source}"
        if File.exist?(source) || Rake::Task.task_defined?(source)
          trace_rule level, "(#{task_name} => #{source} ... EXIST)"
          source
        elsif parent = enhance_with_matching_rule(source, level + 1)
          trace_rule level, "(#{task_name} => #{source} ... ENHANCE)"
          parent.name
        else
          trace_rule level, "(#{task_name} => #{source} ... FAIL)"
          return nil
        end
      }
      task = FileTask.define_task(task_name, { args => prereqs }, &block)
      task.sources = prereqs
      task
    end

def validate_protoquil(program: Program) -> None:

    valid_instruction_types = tuple([Pragma, Declare, Halt, Gate, Reset, ResetQubit, Measurement])
    for instr in program.instructions:
        if not isinstance(instr, valid_instruction_types):
            # Instructions like MOVE, NOT, JUMP, JUMP-UNLESS will fail here
            raise ValueError(f"ProtoQuil validation failed: {instr} is not allowed.")

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get the number of retries left for the given key.

@param  string  $key
@param  int  $maxAttempts
@return int

public function retriesLeft($key, $maxAttempts)
    {
        $attempts = $this->attempts($key);

        return ($attempts === 0) ? $maxAttempts : $maxAttempts - $attempts + 1;
    }

func (b *Batch) Attempts() int {
	b.metrics.l.Lock()
	defer b.metrics.l.Unlock()

	var attempts int
	for _, metric := range b.metrics.m {
		attempts += metric.Attempts
	}
	return attempts
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Use this API to fetch filtered set of lbroute6 resources.
filter string should be in JSON format.eg: "port:80,servicetype:HTTP".

public static lbroute6[] get_filtered(nitro_service service, String filter) throws Exception{
		lbroute6 obj = new lbroute6();
		options option = new options();
		option.set_filter(filter);
		lbroute6[] response = (lbroute6[]) obj.getfiltered(service, option);
		return response;
	}

func (p *Ports) AllPortRanges() map[network.PortRange]string {
	result := make(map[network.PortRange]string)
	for _, portRange := range p.doc.Ports {
		rawRange := network.PortRange{
			FromPort: portRange.FromPort,
			ToPort:   portRange.ToPort,
			Protocol: portRange.Protocol,
		}
		result[rawRange] = portRange.UnitName
	}
	return result
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get content type by its id

@param int $id

@return null|ContentTypeInterface

public function getContentTypeById($id)
    {
        return $this->om->getRepository($this->configurationManager->getEntityClass('content_type'))->find($id);
    }

func (c *ContainerServer) GetContainerFromShortID(cid string) (*oci.Container, error) {
	if cid == "" {
		return nil, fmt.Errorf("container ID should not be empty")
	}

	containerID, err := c.ctrIDIndex.Get(cid)
	if err != nil {
		return nil, fmt.Errorf("container with ID starting with %s not found: %v", cid, err)
	}

	ctr := c.GetContainer(containerID)
	if ctr == nil {
		return nil, fmt.Errorf("specified container not found: %s", containerID)
	}
	return ctr, nil
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Parse ChartStyle
 @param [Nokogiri::XML:Node] node with Relationships
 @return [ChartStyle] result of parsing

def parse(node)
      node.xpath('*').each do |node_child|
        case node_child.name
        when 'style'
          @style_number = node_child.attribute('val').value.to_i
        when 'oleObject'
          @ole_object = OleObject.new(parent: self).parse(node_child)
        end
      end
      self
    end

protected function create_navigation(\stdClass $tree) {
        if ($this->firstelement) {
            $html = \html_writer::start_tag('ul', ['class' => 'treeview parent block_tree list', 'id' => 'my-tree']);
            $this->firstelement = false;
        } else {
            $html = \html_writer::start_tag('ul', ['class' => 'parent', 'role' => 'group']);
        }
        foreach ($tree->children as $child) {
            if (isset($child->children)) {
                $html .= \html_writer::start_tag('li', ['class' => 'menu-item', 'role' => 'treeitem', 'aria-expanded' => 'false']);
                $html .= $child->name;
                $html .= $this->create_navigation($child);
            } else {
                $html .= \html_writer::start_tag('li', ['class' => 'item', 'role' => 'treeitem', 'aria-expanded' => 'false']);
                // Normal display.
                if (isset($child->datavar)) {
                    $html .= \html_writer::link('#', $child->name, ['data-var' => $child->datavar]);
                } else {
                    $html .= \html_writer::link($child->url, $child->name, ['target' => '_blank']);
                }
            }
            $html .= \html_writer::end_tag('li');
        }
        $html .= \html_writer::end_tag('ul');
        return $html;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Get all the scenarios in a given network.

def get_scenarios(network_id,**kwargs):

    user_id = kwargs.get('user_id')
    try:
        net_i = db.DBSession.query(Network).filter(Network.id == network_id).one()
        net_i.check_read_permission(user_id=user_id)
    except NoResultFound:
        raise ResourceNotFoundError("Network %s not found"%(network_id))

    return net_i.scenarios

public void genStat(JCTree tree, Env<GenContext> env) {
        if (code.isAlive()) {
            code.statBegin(tree.pos);
            genDef(tree, env);
        } else if (env.info.isSwitch && tree.hasTag(VARDEF)) {
            // variables whose declarations are in a switch
            // can be used even if the decl is unreachable.
            code.newLocal(((JCVariableDecl) tree).sym);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Find a route in the router based on the specified view name.

        :param view_name: string of view name to search by
        :return: tuple containing (uri, Route)

def find_route_by_view_name(self, view_name):

        if not view_name:
            return (None, None)

        for uri, route in self.routes_all.items():
            if route.name == view_name:
                return uri, route

        return (None, None)

def build_absolute_uri(request, url):

    if app_settings.get('CAPTURE_ROOT_URL'):
        return urljoin(app_settings.get('CAPTURE_ROOT_URL'), url)
    return request.build_absolute_uri(url)

Instruction: Given a code description, retrieve the corresponding code.


Question: // WithHTTPClient adds the HTTPClient to the get o auth2 client params

func (o *GetOAuth2ClientParams) WithHTTPClient(client *http.Client) *GetOAuth2ClientParams {
	o.SetHTTPClient(client)
	return o
}

public synchronized void refreshWithPassword(String username, String password, CharacterSelector characterSelector) throws AuthenticationException {
		refreshWithPassword(createPasswordProvider(username, password, characterSelector));
	}

Instruction: Given a code description, retrieve the corresponding code.


Question: Auto Generated Code

def ipv6_ipv6route_route_next_ipv6_hop_next_hop(self, **kwargs):

        config = ET.Element("config")
        ipv6 = ET.SubElement(config, "ipv6", xmlns="urn:brocade.com:mgmt:brocade-common-def")
        ipv6route = ET.SubElement(ipv6, "ipv6route", xmlns="urn:brocade.com:mgmt:brocade-ip-forward")
        route = ET.SubElement(ipv6route, "route")
        dest_key = ET.SubElement(route, "dest")
        dest_key.text = kwargs.pop('dest')
        next = ET.SubElement(route, "next")
        ipv6_hop = ET.SubElement(next, "ipv6-hop")
        next_hop = ET.SubElement(ipv6_hop, "next-hop")
        next_hop.text = kwargs.pop('next_hop')

        callback = kwargs.pop('callback', self._callback)
        return callback(config)

private function populateAvailableTypes($onlyAutowiringTypes = false)
    {
        $this->types = array();
        if (!$onlyAutowiringTypes) {
            $this->ambiguousServiceTypes = array();
        }

        foreach ($this->container->getDefinitions() as $id => $definition) {
            $this->populateAvailableType($id, $definition, $onlyAutowiringTypes);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// Error can be either of the following types:
//
//   - InvalidObjectFault
//   - RuntimeFault

func (service *VboxPortType) IHostUSBDeviceFiltersetAction(request *IHostUSBDeviceFiltersetAction) (*IHostUSBDeviceFiltersetActionResponse, error) {
	response := new(IHostUSBDeviceFiltersetActionResponse)
	err := service.client.Call("", request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

public function get($tag)
    {
        if (!isset($this->styles[$tag])) {
            throw new OutOfBoundsException(sprintf(
                'The style tag "%s" does not exist.',
                $tag
            ));
        }

        return $this->styles[$tag];
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Get the relations to the base table and related table

@param baseTable
base table name
@param relatedTable
related table name
@return extended relations
@throws SQLException
upon failure
@since 3.2.0

public List<ExtendedRelation> getRelations(String baseTable,
			String relatedTable) throws SQLException {
		return getRelations(baseTable, null, relatedTable, null, null, null);
	}

public static String resolveDataSourceTypeFromDialect(String dialect)
    {
        if (StringUtils.contains(dialect, "Oracle"))
        {
            return "Oracle";
        }
        else if (StringUtils.contains(dialect, "MySQL"))
        {
            return "MySQL";
        }
        else if (StringUtils.contains(dialect, "DB2390Dialect"))
        {
            return "DB2/390";
        }
        else if (StringUtils.contains(dialect, "DB2400Dialect"))
        {
            return "DB2/400";
        }
        else if (StringUtils.contains(dialect, "DB2"))
        {
            return "DB2";
        }
        else if (StringUtils.contains(dialect, "Ingres"))
        {
            return "Ingres";
        }
        else if (StringUtils.contains(dialect, "Derby"))
        {
            return "Derby";
        }
        else if (StringUtils.contains(dialect, "Pointbase"))
        {
            return "Pointbase";
        }
        else if (StringUtils.contains(dialect, "Postgres"))
        {
            return "Postgres";
        }
        else if (StringUtils.contains(dialect, "SQLServer"))
        {
            return "SQLServer";
        }
        else if (StringUtils.contains(dialect, "Sybase"))
        {
            return "Sybase";
        }
        else if (StringUtils.contains(dialect, "HSQLDialect"))
        {
            return "HyperSQL";
        }
        else if (StringUtils.contains(dialect, "H2Dialect"))
        {
            return "H2";
        }

        return dialect;

    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// PrivateKeyToCurve25519 converts an ed25519 private key into a corresponding
// curve25519 private key such that the resulting curve25519 public key will
// equal the result from PublicKeyToCurve25519.

func PrivateKeyToCurve25519(curve25519Private *[32]byte, privateKey *[64]byte) {
	h := sha512.New()
	h.Write(privateKey[:32])
	digest := h.Sum(nil)

	digest[0] &= 248
	digest[31] &= 127
	digest[31] |= 64

	copy(curve25519Private[:], digest)
}

func (klv *KeyLevelValidator) Validate(cc string, blockNum, txNum uint64, rwsetBytes, prp, ccEP []byte, endorsements []*peer.Endorsement) commonerrors.TxValidationError {
	// construct signature set
	signatureSet := []*common.SignedData{}
	for _, endorsement := range endorsements {
		data := make([]byte, len(prp)+len(endorsement.Endorser))
		copy(data, prp)
		copy(data[len(prp):], endorsement.Endorser)

		signatureSet = append(signatureSet, &common.SignedData{
			// set the data that is signed; concatenation of proposal response bytes and endorser ID
			Data: data,
			// set the identity that signs the message: it's the endorser
			Identity: endorsement.Endorser,
			// set the signature
			Signature: endorsement.Signature})
	}

	// construct the policy checker object
	policyChecker := policyChecker{
		ccEP:          ccEP,
		policySupport: klv.policySupport,
		signatureSet:  signatureSet,
		vpmgr:         klv.vpmgr,
	}

	// unpack the rwset
	rwset := &rwsetutil.TxRwSet{}
	if err := rwset.FromProtoBytes(rwsetBytes); err != nil {
		return policyErr(errors.WithMessage(err, fmt.Sprintf("txRWSet.FromProtoBytes failed on tx (%d,%d)", blockNum, txNum)))
	}

	// iterate over all writes in the rwset
	for _, nsRWSet := range rwset.NsRwSets {
		// skip other namespaces
		if nsRWSet.NameSpace != cc {
			continue
		}

		// public writes
		// we validate writes against key-level validation parameters
		// if any are present or the chaincode-wide endorsement policy
		for _, pubWrite := range nsRWSet.KvRwSet.Writes {
			err := policyChecker.checkSBAndCCEP(cc, "", pubWrite.Key, blockNum, txNum)
			if err != nil {
				return err
			}
		}
		// public metadata writes
		// we validate writes against key-level validation parameters
		// if any are present or the chaincode-wide endorsement policy
		for _, pubMdWrite := range nsRWSet.KvRwSet.MetadataWrites {
			err := policyChecker.checkSBAndCCEP(cc, "", pubMdWrite.Key, blockNum, txNum)
			if err != nil {
				return err
			}
		}
		// writes in collections
		// we validate writes against key-level validation parameters
		// if any are present or the chaincode-wide endorsement policy
		for _, collRWSet := range nsRWSet.CollHashedRwSets {
			coll := collRWSet.CollectionName
			for _, hashedWrite := range collRWSet.HashedRwSet.HashedWrites {
				key := string(hashedWrite.KeyHash)
				err := policyChecker.checkSBAndCCEP(cc, coll, key, blockNum, txNum)
				if err != nil {
					return err
				}
			}
		}
		// metadata writes in collections
		// we validate writes against key-level validation parameters
		// if any are present or the chaincode-wide endorsement policy
		for _, collRWSet := range nsRWSet.CollHashedRwSets {
			coll := collRWSet.CollectionName
			for _, hashedMdWrite := range collRWSet.HashedRwSet.MetadataWrites {
				key := string(hashedMdWrite.KeyHash)
				err := policyChecker.checkSBAndCCEP(cc, coll, key, blockNum, txNum)
				if err != nil {
					return err
				}
			}
		}
	}

	// we make sure that we check at least the CCEP to honour FAB-9473
	return policyChecker.checkCCEPIfNoEPChecked(cc, blockNum, txNum)
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // SetYarnEndpointAddress sets the YarnEndpointAddress field's value.

func (s *DevEndpoint) SetYarnEndpointAddress(v string) *DevEndpoint {
	s.YarnEndpointAddress = &v
	return s
}

def set_name(self, name):
        """"""
        if not name:
            name = ''
        self._client['config']['name'] = name
        yield from self._server.client_name(self.identifier, name)

Instruction: Given a code description, retrieve the corresponding code.


Question: Wait and raise KeyboardInterrupt after.

def run_checked (self):
        """"""
        self.start_time = time.time()
        self.setName("Interrupt")
        while not self.stopped(self.WaitSeconds):
            duration = time.time() - self.start_time
            if duration > self.duration:
                log.warn(LOG_CHECK, "Interrupt after %s" % strformat.strduration_long(duration))
                raise KeyboardInterrupt()

def gui_repaint(self, drawDC=None):

        DEBUG_MSG("gui_repaint()", 1, self)
        if self.IsShownOnScreen():
            if drawDC is None:
                drawDC=wx.ClientDC(self)

            #drawDC.BeginDrawing()
            drawDC.DrawBitmap(self.bitmap, 0, 0)
            #drawDC.EndDrawing()
            #wx.GetApp().Yield()
        else:
            pass

Instruction: Given a code description, retrieve the corresponding code.


Question:
Sets a proper EncType on the given \Zend\Http\Client object (for UrlEncoded Request, used value is Client::ENC_URLENCODED)

@param \Zend\Http\Client $client the Zend http client object

@return mixed|\Zend\Http\Client

public function setClientEncType(\Zend\Http\Client $client)
    {
        // Setting EncType to UrlEncoded
        $client->setEncType(\Zend\Http\Client::ENC_URLENCODED);

        return $client;
    }

public function generateHeaders()
    {
        $this->setHeader( "Content-Type", "text/" . $this->subType . "; charset=" . $this->charset );
        $this->setHeader( "Content-Transfer-Encoding", $this->encoding );
        return parent::generateHeaders();
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
/*
Adds a channel with identification.
@requesterID and @conversationID are optional.

public void addChannel(
            T channel,
            String functionalityName,
            String requesterID,
            String conversationID)
    {
        T oldCh = null;
        synchronized (this.channelsWithId)
        {
            oldCh = this.channelsWithId.get(calculateId(functionalityName, requesterID, conversationID));
            this.channelsWithId.put(calculateId(functionalityName, requesterID, conversationID), channel);
        }
        synchronized (this.channelsWithFunctionalityName)
        {
            Collection<T> channelsForFunctionalityName = this.channelsWithFunctionalityName.get(functionalityName);
            if (null == channelsForFunctionalityName)
            {
                channelsForFunctionalityName = new ArrayList<T>();
            }
            // channels are stored in
            if (null != oldCh)
            {
                channelsForFunctionalityName.remove(oldCh);
            }
            channelsForFunctionalityName = this.removeInternalChannels(channelsForFunctionalityName);
            channelsForFunctionalityName.add(channel);
            this.channelsWithFunctionalityName.put(functionalityName, channelsForFunctionalityName);
        }
    }

public TCConversationRequest createConversation(Dialog d, boolean dialogTermitationPermission) {
        if (d == null) {
            throw new NullPointerException("Dialog is null");
        }
        TCConversationRequestImpl tccr = new TCConversationRequestImpl(dialogTermitationPermission);
        tccr.setDialog(d);
        tccr.setOriginatingAddress(d.getLocalAddress());

        return tccr;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
@param resource $res

@throws \Exception

public static function loadKeyFromX509Resource($res): array
    {
        $key = \openssl_get_publickey($res);

        $details = \openssl_pkey_get_details($key);
        if (isset($details['key'])) {
            $values = self::loadKeyFromPEM($details['key']);
            \openssl_x509_export($res, $out);
            $x5c = \preg_replace('#-.*-#', '', $out);
            $x5c = \preg_replace('~\R~', PHP_EOL, $x5c);
            $x5c = \trim($x5c);
            $values['x5c'] = [$x5c];

            $values['x5t'] = Base64Url::encode(\openssl_x509_fingerprint($res, 'sha1', true));
            $values['x5t#256'] = Base64Url::encode(\openssl_x509_fingerprint($res, 'sha256', true));

            return $values;
        }

        throw new \InvalidArgumentException('Unable to load the certificate');
    }

func InterpretCreateError(err error, qualifiedResource unversioned.GroupResource, name string) error {
	switch {
	case storage.IsNodeExist(err):
		return errors.NewAlreadyExists(qualifiedResource, name)
	case storage.IsUnreachable(err):
		return errors.NewServerTimeout(qualifiedResource, "create", 2) // TODO: make configurable or handled at a higher level
	default:
		return err
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question: Updates class attribute of the element.

protected function updateClassAttribute()
    {
        $this->classesString = implode(' ', $this->classes);

        $this->element->setAttribute('class', $this->classesString);
    }

public function setAttr(string $name, $value): self {
        $this->collection()->each(function($node) use($name, $value) {
            if ($node instanceof \DOMElement) {
                $node->setAttribute($name, (string)$value);
            }
        });

        return $this;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // StructuredGenerate outputs a horizontal pod autoscaler object using the configured fields.

func (s *HorizontalPodAutoscalerGeneratorV1) StructuredGenerate() (runtime.Object, error) {
	if err := s.validate(); err != nil {
		return nil, err
	}

	scaler := autoscalingv1.HorizontalPodAutoscaler{
		ObjectMeta: metav1.ObjectMeta{
			Name: s.Name,
		},
		Spec: autoscalingv1.HorizontalPodAutoscalerSpec{
			ScaleTargetRef: autoscalingv1.CrossVersionObjectReference{
				Kind:       s.ScaleRefKind,
				Name:       s.ScaleRefName,
				APIVersion: s.ScaleRefAPIVersion,
			},
			MaxReplicas: s.MaxReplicas,
		},
	}

	if s.MinReplicas > 0 {
		v := int32(s.MinReplicas)
		scaler.Spec.MinReplicas = &v
	}
	if s.CPUPercent >= 0 {
		c := int32(s.CPUPercent)
		scaler.Spec.TargetCPUUtilizationPercentage = &c
	}

	return &scaler, nil
}

public function scaffold(Manager $manager)
    {
        return [
            'name' => $this->getName(),
            'description' => $this->getDescription(),
            'args' => $this->createArgs($manager),
            'type' => $this->getType($manager),
            'resolve' => $this->createResolverFunction(),
        ];
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
// DeleteLivePullStreamInfoConfig 删除拉流信息
//
// https://help.aliyun.com/document_detail/57735.html?spm=5176.doc57734.6.657.wRW6P7

func (l *Live) DeleteLivePullStreamInfoConfig(streamName string, resp interface{}) (err error) {
	req := l.cloneRequest(DeleteLivePullStreamInfoConfigAction)
	req.SetArgs("StreamName", streamName)
	err = l.rpc.Query(req, resp)
	return
}

function(l) {
			if (l.type === gui.LIFE_ENTER) {
				if (!this.spirit.life.rendered) { // spirit did a manual run?
					this.run.apply(this, this._arguments || []);
				}
				this.spirit.life.remove(l.type, this);
				this._arguments = null;
			}
		}

Instruction: Given a code description, retrieve the corresponding code.


Question: Preprocess the given data, ready for parsing.

def Preprocess(self, data):
    """"""
    # Add whitespace to line continuations.
    data = data.replace(":\\", ": \\")

    # Strip comments manually because sudoers has multiple meanings for '#'.
    data = SudoersFieldParser.COMMENTS_RE.sub("", data)
    return data

func ImportTar(ctx context.Context, r io.Reader, ds ipld.DAGService) (*dag.ProtoNode, error) {
	tr := tar.NewReader(r)

	root := new(dag.ProtoNode)
	root.SetData([]byte("ipfs/tar"))

	e := dagutils.NewDagEditor(root, ds)

	for {
		h, err := tr.Next()
		if err != nil {
			if err == io.EOF {
				break
			}
			return nil, err
		}

		header := new(dag.ProtoNode)

		headerBytes, err := marshalHeader(h)
		if err != nil {
			return nil, err
		}

		header.SetData(headerBytes)

		if h.Size > 0 {
			spl := chunker.NewRabin(tr, uint64(chunker.DefaultBlockSize))
			nd, err := importer.BuildDagFromReader(ds, spl)
			if err != nil {
				return nil, err
			}

			err = header.AddNodeLink("data", nd)
			if err != nil {
				return nil, err
			}
		}

		err = ds.Add(ctx, header)
		if err != nil {
			return nil, err
		}

		path := escapePath(h.Name)
		err = e.InsertNodeAtPath(context.Background(), path, header, func() *dag.ProtoNode { return new(dag.ProtoNode) })
		if err != nil {
			return nil, err
		}
	}

	return e.Finalize(ctx, ds)
}

Instruction: Given a code description, retrieve the corresponding code.


Question: Returns a `tf.Example` parsing spec as dict.

def _parse_example_spec(self):
    """"""
    height, width = image_util.get_expected_image_size(self.module_spec)
    input_shape = [height, width, 3]
    return {self.key: tf_v1.FixedLenFeature(input_shape, tf.float32)}

def _tokens_from_patsy(node):

    for n in node.args:
        for t in _tokens_from_patsy(n):
            yield t

    if node.token:
        yield node.token

Instruction: Given a code description, retrieve the corresponding code.


Question:
Works out what the provided attr evaluates to.

 @param attr [Symbol] attribute to evaluate

 @return [String] value of attribute

def provide_attr(attr)
      list_item_attr_value = list_item.public_send(attr)

      # Provide user supplied attr
      return list_item_attr_value if list_item_attr_value.present?

      # Provide object supplied attr
      return object_data[attr] if object_available?

      # Provide error - Object is linked but has been deleted
      return 'Object Unavailable' if list_item.object? && !object_available?

      # Provide empty string - no attr supplied and no object linked
      ''
    end

public Object getDefaultValue(Parameter parameter) {
    Class<?> type = parameter.getType();

    if (TypeUtils.isaString(type)) {
      return getStringDefaultValue(parameter);
    }

    if (TypeUtils.isaByte(type)) {
      return getByteDefaultValue(parameter);
    }

    if (TypeUtils.isaShort(type)) {
      return getShortDefaultValue(parameter);
    }

    if (TypeUtils.isaInteger(type)) {
      return getIntegerDefaultValue(parameter);
    }

    if (TypeUtils.isaLong(type)) {
      return getLongDefaultValue(parameter);
    }

    if (TypeUtils.isaFloat(type)) {
      return getFloatDefaultValue(parameter);
    }

    if (TypeUtils.isaDouble(type)) {
      return getDoubleDefaultValue(parameter);
    }

    if (TypeUtils.isaCharacter(type)) {
      return getCharacterDefaultValue(parameter);
    }

    if (TypeUtils.isaBoolean(type)) {
      return getBooleanDefaultValue(parameter);
    }

    return null;
  }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Action when button was clicked.

        Parameters
        ----------
        button : instance of QPushButton
            which button was pressed

def button_clicked(self, button):

        if button is self.idx_ok:

            # File location
            if not self.filename:
                msg = 'Select location for data export file.'
                error_dialog = QErrorMessage(self)
                error_dialog.setWindowTitle('File path error')
                error_dialog.showMessage(msg)
                return

            # Check for signal
            self.update_nseg
            if self.nseg <= 0:
                msg = 'No valid signal found.'
                error_dialog = QErrorMessage(self)
                error_dialog.setWindowTitle('Error fetching data')
                error_dialog.showMessage(msg)
                return

            # Which analyses?
            freq = self.frequency
            freq_full = freq['export_full'].get_value()
            freq_band = freq['export_band'].get_value()
            freq_plot = freq['plot_on'].get_value()
            freq_fooof = freq['fooof_on'].get_value()
            freq_prep = freq['prep'].get_value()
            freq_on = freq_full or freq_band or freq_plot or freq_fooof

            if Pac is not None:
                pac_on = self.pac['pac_on'].get_value()
                pac_prep = self.pac['prep'].get_value()
            else:
                pac_on = False
                pac_prep = False

            ev = self.event
            glob = asarray(
                    [v.get_value() for v in ev['global'].values()]).any()
            loc = asarray(
                    [v[0].get_value() for v in ev['local'].values()]).any()
            avg_sl = ev['sw']['avg_slope'].get_value()
            max_sl = ev['sw']['max_slope'].get_value()
            loc_prep = asarray(
                    [v[1].get_value() for v in ev['local'].values()]).any()
            slope_prep = ev['sw']['prep'].get_value()

            if not (freq_on or pac_on or glob or loc or avg_sl or max_sl):
                return

            if freq['export_band'].get_value():
                bands = freq_from_str(freq['band'].get_value())
                if bands is None:
                    msg = ('Invalid input for Define bands. Click the '
                    "'i' button for instructions.")
                    error_dialog = QErrorMessage(self)
                    error_dialog.setWindowTitle('Error reading bands')
                    error_dialog.showMessage(msg)
                    return

            if (freq['norm'].get_value() == 'by mean of event type(s)' and
                not freq['norm_evt_type'].selectedItems()):
                msg = 'Select event type(s) for normalization.'
                error_dialog = QErrorMessage(self)
                error_dialog.setWindowTitle('Error fetching data')
                error_dialog.showMessage(msg)
                return

            if (freq['norm'].get_value() == 'by mean of stage(s)' and
                not freq['norm_stage'].selectedItems()):
                msg = 'Select stage(s) for normalization.'
                error_dialog = QErrorMessage(self)
                error_dialog.setWindowTitle('Error fetching data')
                error_dialog.showMessage(msg)
                return

            # Fetch signal
            eco = self.evt_chan_only
            chan = [] if (eco.get_value() and eco.isEnabled()) else self.chan
            concat_chan = self.cat['chan'].get_value()

            self.data = self.get_segments()

            if not self.data.segments:
                msg = 'No valid signal found.'
                error_dialog = QErrorMessage(self)
                error_dialog.setWindowTitle('Error fetching data')
                error_dialog.showMessage(msg)
                return

            ding = self.data.read_data(chan,
                               ref_chan=self.one_grp['ref_chan'],
                               grp_name=self.one_grp['name'],
                               concat_chan=concat_chan,
                               max_s_freq=self.parent.value('max_s_freq'),
                               parent=self)

            if not ding:
                self.parent.statusBar().showMessage('Process interrupted.')
                return

            # Transform signal
            if freq_prep or pac_prep or loc_prep or slope_prep:
                lg.info('Pre-processing data')
                self.data = self.transform_data(self.data)

            """ ------ FREQUENCY ------ """

            if freq_on:

                csd_on = freq['csd'].get_value()
                gainphase_on = freq['gainphase'].get_value()
                coh_on = freq['coh'].get_value()

                # don't need autospectrum if all we want is CSD
                if not (csd_on and not (gainphase_on or coh_on)):
                    asd = self.compute_freq() # autospectral density
                    if not asd:
                        return

                if csd_on or gainphase_on or coh_on:
                    csd = self.compute_freq(csd=True) # cross-spectral density
                    chancombo = str(csd[0]['data'].axis['chan'][0][0])
                    freq_out = []

                    if csd_on:
                        freq_out.append((csd, 'csd',
                                         ('Cross-spectral density, '
                                          + chancombo + ', '),
                                          None, 'semilogy'))

                    if gainphase_on:
                        xg, yg, ph = self.compute_freq_cross(csd, asd,
                                                            output='gainphase')
                        xchancombo = str(xg[0]['data'].axis['chan'][0][0])
                        ychancombo = str(yg[0]['data'].axis['chan'][0][0])
                        freq_out.append((xg, 'xgain',
                                         ('Gain, ' + xchancombo + ', '),
                                         'Gain', 'linear'))
                        freq_out.append((yg, 'ygain',
                                         ('Gain, ' + ychancombo + ', '),
                                         'Gain', 'linear'))
                        freq_out.append((ph, 'phase',
                                         ('Phase shift, ' + xchancombo + ', '),
                                         'Phase shift (degrees)', 'linear'))

                    if coh_on:
                        coh, = self.compute_freq_cross(csd, asd,
                                                       output='coherence')
                        freq_out.append((coh, 'coh',
                                         ('Coherence, ' + chancombo + ', '),
                                         'Coherence', 'linear'))

                else:
                    freq_out = [(asd, 'freq', '', None, 'semilogy')]

                for one_xf, suffix, prefix, ylabel, scale in freq_out:

                    if freq_band:
                        filename = (splitext(self.filename)[0] + '_' + suffix +
                                    '_band.csv')
                        export_freq_band(one_xf, bands, filename)

                    if freq_full or freq_plot or freq_fooof:
                        n_freq_bins = [x['data']()[0].shape for x in one_xf]

                        if all(x == n_freq_bins[0] for x in n_freq_bins):
                            x = list(one_xf[0]['data'].axis['freq'][0])

                            if len(one_xf) == 1:
                                desc = None
                                y = abs(one_xf[0]['data'].data[0][0])
                            else:
                                as_matrix = asarray(
                                   [y for x in one_xf for y in x['data']()[0]])
                                desc = get_descriptives(as_matrix)
                                y = desc['mean']

                            if freq_full:
                                filename = (splitext(self.filename)[0] + '_' +
                                            suffix + '_full.csv')
                                export_freq(one_xf, filename, desc=desc)

                            if freq_plot:
                                self.plot_freq(x, y,
                                               title=(prefix + self.title),
                                               ylabel=ylabel, scale=scale)

                            if freq_fooof:
                                self.report_fooof(asarray(x), y, suffix)

            """ ------ PAC ------ """

            if pac_on:
                pac_output = self.compute_pac()

                if pac_output is not None:
                    xpac, fpha, famp = pac_output
                else:
                    return

                as_matrix = asarray(
                        [ravel(chan['data'][x,:,:]) for chan in xpac.values() \
                         for x in range(chan['data'].shape[0])])
                desc = get_descriptives(as_matrix)
                self.export_pac(xpac, fpha, famp, desc)

            """ ------ EVENTS ------ """

            evt_dat, count, density = self.compute_evt_params()

            if (evt_dat or count or density):
                fn = splitext(self.filename)[0] + '_params.csv'
                export_event_params(fn, evt_dat, count=count, density=density)

            self.parent.overview.mark_poi() # remove poi
            self.accept()

        if button is self.idx_cancel:
            self.parent.overview.mark_poi() # remove poi
            self.reject()

function createPublisher(broker, configurator) {
    var params = getParams(PublisherConfiguration, configurator);
    return Publisher(broker, params.envelope, params.pipeline, params.routeName, params.routePattern, params.logger);
  }

Instruction: Given a code description, retrieve the corresponding code.


Question: InternalXbaseWithAnnotations.g:833:1: entryRuleXCollectionLiteral : ruleXCollectionLiteral EOF ;

public final void entryRuleXCollectionLiteral() throws RecognitionException {
        try {
            // InternalXbaseWithAnnotations.g:834:1: ( ruleXCollectionLiteral EOF )
            // InternalXbaseWithAnnotations.g:835:1: ruleXCollectionLiteral EOF
            {
            if ( state.backtracking==0 ) {
               before(grammarAccess.getXCollectionLiteralRule());
            }
            pushFollow(FOLLOW_1);
            ruleXCollectionLiteral();

            state._fsp--;
            if (state.failed) return ;
            if ( state.backtracking==0 ) {
               after(grammarAccess.getXCollectionLiteralRule());
            }
            match(input,EOF,FOLLOW_2); if (state.failed) return ;

            }

        }
        catch (RecognitionException re) {
            reportError(re);
            recover(input,re);
        }
        finally {
        }
        return ;
    }

public function GetComment($key) {
        $resources = $this->GetList();
        $keyExist = array_key_exists($key, $resources);
        if ($keyExist) {
            return $resources[$key][\Puzzlout\Framework\BO\F_common_resource::F_COMMON_RESOURCE_COMMENT];
        } else {
//      throw new \Puzzlout\Framework\Exceptions\ResourceNotFoundException(
//      "The resource comment doesn't exist for Group => " . $this->GroupValue . " and Key => " . $key, 0, null);
            return "???";
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Performs additional filtering on the list of projects for the project selector.<p>

@param projects the original project list

@return the filtered project list

public List<CmsProject> filterProjectsForSelector(List<CmsProject> projects) {

        List<CmsProject> result = new ArrayList<CmsProject>();
        for (CmsProject project : projects) {
            if (!project.isHiddenFromSelector()) {
                result.add(project);
            }
        }
        return result;
    }

public function initializeArguments()
    {
        parent::initializeArguments();
        $this->registerArgument('results', '\Solarium\QueryType\Select\Result\Result', 'Query results', true);
        $this->registerArgument('document', '\Solarium\QueryType\Select\Result\Document', 'Result document to work on',
            true);
        $this->registerArgument('field', 'string', 'name of field in document to highlight', true);
        $this->registerArgument('alternateField', 'string',
            'name of alternate field in document to use for highlighting', false, null);
        $this->registerArgument('index', 'int', 'if the field is an array: index of the single element to highlight',
            false);
        $this->registerArgument('idKey', 'string', 'name of the field in document that is its ID', false, 'id');
        $this->registerArgument('highlightTagOpen', 'string', 'opening tag to insert to begin highlighting', false,
            '');
        $this->registerArgument('highlightTagClose', 'string', 'closing tag to insert to end highlighting', false,
            '');
        $this->registerArgument('raw', 'boolean', 'whether to not HTML escape the output', false, false);
    }

Instruction: Given a code description, retrieve the corresponding code.


private void migrate() throws SQLException {
		QueryVO pk = helper.selectAll("pkList",
			ObjectBuilder.<String, Object>map().put("tables", tables).get());
		List<TablePkFkVO> tablePkFkVOs = pk.toBeans(TablePkFkVO.class);

		logger.info("TablePkFkVO size = {}", tablePkFkVOs.size());

		for (TablePkFkVO table : tablePkFkVOs) {
			QueryVO fk = helper.selectAll("fkList",
				ObjectBuilder.<String, Object>map().put("table", table.getName()).get());
			table.setReferencedBy(fk.toBeans(RefConsVO.class));
		}

		logger.info("TablePkFkVO size = {}", tablePkFkVOs.size());

		for (TablePkFkVO tablePkFkVO : tablePkFkVOs) {
			migrateTable(tablePkFkVO);
		}
	}

function (input, stateMachine) {
      if (!input) { return []; }
      if (stateMachine === undefined) { stateMachine = 'ce'; }
      var state = '0';

      //
      // String buffers for parsing:
      //
      // buffer.a == amount
      // buffer.o == element
      // buffer.b == left-side superscript
      // buffer.p == left-side subscript
      // buffer.q == right-side subscript
      // buffer.d == right-side superscript
      //
      // buffer.r == arrow
      // buffer.rdt == arrow, script above, type
      // buffer.rd == arrow, script above, content
      // buffer.rqt == arrow, script below, type
      // buffer.rq == arrow, script below, content
      //
      // buffer.text_
      // buffer.rm
      // etc.
      //
      // buffer.parenthesisLevel == int, starting at 0
      // buffer.sb == bool, space before
      // buffer.beginsWithBond == bool
      //
      // These letters are also used as state names.
      //
      // Other states:
      // 0 == begin of main part (arrow/operator unlikely)
      // 1 == next entity
      // 2 == next entity (arrow/operator unlikely)
      // 3 == next atom
      // c == macro
      //
      /** @type {Buffer} */
      var buffer = {};
      buffer['parenthesisLevel'] = 0;

      input = input.replace(/\n/g, " ");
      input = input.replace(/[\u2212\u2013\u2014\u2010]/g, "-");
      input = input.replace(/[\u2026]/g, "...");

      //
      // Looks through mhchemParser.transitions, to execute a matching action
      // (recursive)
      //
      var lastInput;
      var watchdog = 10;
      /** @type {ParserOutput[]} */
      var output = [];
      while (true) {
        if (lastInput !== input) {
          watchdog = 10;
          lastInput = input;
        } else {
          watchdog--;
        }
        //
        // Find actions in transition table
        //
        var machine = mhchemParser.stateMachines[stateMachine];
        var t = machine.transitions[state] || machine.transitions['*'];
        iterateTransitions:
        for (var i=0; i<t.length; i++) {
          var matches = mhchemParser.patterns.match_(t[i].pattern, input);
          if (matches) {
            //
            // Execute actions
            //
            var task = t[i].task;
            for (var iA=0; iA<task.action_.length; iA++) {
              var o;
              //
              // Find and execute action
              //
              if (machine.actions[task.action_[iA].type_]) {
                o = machine.actions[task.action_[iA].type_](buffer, matches.match_, task.action_[iA].option);
              } else if (mhchemParser.actions[task.action_[iA].type_]) {
                o = mhchemParser.actions[task.action_[iA].type_](buffer, matches.match_, task.action_[iA].option);
              } else {
                throw ["MhchemBugA", "mhchem bug A. Please report. (" + task.action_[iA].type_ + ")"];  // Trying to use non-existing action
              }
              //
              // Add output
              //
              mhchemParser.concatArray(output, o);
            }
            //
            // Set next state,
            // Shorten input,
            // Continue with next character
            //   (= apply only one transition per position)
            //
            state = task.nextState || state;
            if (input.length > 0) {
              if (!task.revisit) {
                input = matches.remainder;
              }
              if (!task.toContinue) {
                break iterateTransitions;
              }
            } else {
              return output;
            }
          }
        }
        //
        // Prevent infinite loop
        //
        if (watchdog <= 0) {
          throw ["MhchemBugU", "mhchem bug U. Please report."];  // Unexpected character
        }
      }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: // new random bin generator based on benchmark specs

func getBin(xr *XorRand) *as.Bin {
	var bin *as.Bin
	switch binDataType {
	case "B":
		bin = &as.Bin{Name: "B", Value: getRandValue(xr)}
	case "S":
		bin = &as.Bin{Name: "S", Value: getRandValue(xr)}
	default:
		bin = &as.Bin{Name: "I", Value: getRandValue(xr)}
	}

	return bin
}

public static function compare(string $a, string $b): string
    {
        return static::makeBin($a, 16) === static::makeBin($b, 16);
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Translates the log priority to the log levels of Monolog.

@param integer $priority Log level from \Aimeos\MW\Logger\Base
@return integer Log level from Monolog\Logger
@throws \Aimeos\MW\Logger\Exception If log level is unknown

protected function translatePriority( $priority )
	{
		switch( $priority )
		{
			case \Aimeos\MW\Logger\Base::EMERG:
				return \Monolog\Logger::EMERGENCY;
			case \Aimeos\MW\Logger\Base::ALERT:
				return \Monolog\Logger::ALERT;
			case \Aimeos\MW\Logger\Base::CRIT:
				return \Monolog\Logger::CRITICAL;
			case \Aimeos\MW\Logger\Base::ERR:
				return \Monolog\Logger::ERROR;
			case \Aimeos\MW\Logger\Base::WARN:
				return \Monolog\Logger::WARNING;
			case \Aimeos\MW\Logger\Base::NOTICE:
				return \Monolog\Logger::NOTICE;
			case \Aimeos\MW\Logger\Base::INFO:
				return \Monolog\Logger::INFO;
			case \Aimeos\MW\Logger\Base::DEBUG:
				return \Monolog\Logger::DEBUG;
			default:
				throw new \Aimeos\MW\Logger\Exception( 'Invalid log level' );
		}
	}

public void marshall(DescribeMLModelsRequest describeMLModelsRequest, ProtocolMarshaller protocolMarshaller) {

        if (describeMLModelsRequest == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(describeMLModelsRequest.getFilterVariable(), FILTERVARIABLE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getEQ(), EQ_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGT(), GT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLT(), LT_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getGE(), GE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLE(), LE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNE(), NE_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getPrefix(), PREFIX_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getSortOrder(), SORTORDER_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(describeMLModelsRequest.getLimit(), LIMIT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
predict the conditional mean (BLUP)

        Returns:
            predictions (BLUP)

def predictMean(self):

        assert self.noisPos!=None,      'No noise element'
        assert self.init,               'GP not initialised'

        KiY = self.gp.agetKEffInvYCache()

        if self.fast==False:
            KiY = KiY.reshape(self.P,self.N).T

        Ymean = None
        for term_i in range(self.n_terms):
            if term_i!=self.noisPos:
                Kstar = self.vd.getTerm(term_i).getKcf().Kcross(SP.zeros(1))
                term  = SP.dot(Kstar.T,KiY)
                if self.P>1:
                    C    = self.getEstTraitCovar(term_i)
                    term = SP.dot(term,C)
                if Ymean==None:     Ymean  = term
                else:               Ymean += term

        # to generalise
        Ymean+=self.getFixed()[:,0]

        return Ymean

func (l *linuxDatapath) writeStaticData(fw io.Writer, e datapath.EndpointConfiguration) {
	fmt.Fprint(fw, defineIPv6("LXC_IP", e.IPv6Address()))
	fmt.Fprint(fw, defineIPv4("LXC_IPV4", e.IPv4Address()))

	fmt.Fprint(fw, defineMAC("NODE_MAC", e.GetNodeMAC()))
	fmt.Fprint(fw, defineUint32("LXC_ID", uint32(e.GetID())))

	secID := e.GetIdentity().Uint32()
	fmt.Fprintf(fw, defineUint32("SECLABEL", secID))
	fmt.Fprintf(fw, defineUint32("SECLABEL_NB", byteorder.HostToNetwork(secID).(uint32)))

	epID := uint16(e.GetID())
	fmt.Fprintf(fw, "#define POLICY_MAP %s\n", bpf.LocalMapName(policymap.MapName, epID))
	fmt.Fprintf(fw, "#define CALLS_MAP %s\n", bpf.LocalMapName("cilium_calls_", epID))
	fmt.Fprintf(fw, "#define CONFIG_MAP %s\n", bpf.LocalMapName(bpfconfig.MapNamePrefix, epID))
}

Instruction: Given a code description, retrieve the corresponding code.


Question: // Serialize writes the ResolvedFile to an io.Writer in canonical order.

func (f *ResolvedFile) Serialize(w io.Writer) error {
	// piggyback on top of File.Serialize.
	packagesBySubdir := make(map[string]PackageSlice, len(f.PackagesBySubdir))
	for k, v := range f.PackagesBySubdir {
		slc := make(PackageSlice, len(v))
		for i, pkg := range v {
			slc[i] = PackageDef{
				PackageTemplate:   pkg.PackageName,
				UnresolvedVersion: pkg.InstanceID,
			}
		}
		packagesBySubdir[k] = slc
	}
	return (&File{
		ServiceURL:       f.ServiceURL,
		ParanoidMode:     f.ParanoidMode,
		PackagesBySubdir: packagesBySubdir,
	}).Serialize(w)
}

def save(self, save_json=True, save_xml=True):

        if self.layer_is_file_based:
            if save_json:
                self.write_to_file(self.json_uri)
            if save_xml:
                self.write_to_file(self.xml_uri)
        else:
            self.write_to_db(save_json, save_xml)

Instruction: Given a code description, retrieve the corresponding code.


Question:
Google Plus
Registers Google Plus meta tags declared
@return void

Register an Google Plus property.
@param string $property
@param string $data

public function renderGooglePlusMetaTags() {
		if (!isset($this->googlePlusTags['name']))
			$this->googlePlusTags['name'] = Yii::app()->name; // default to App name
		if (!isset($this->googlePlusTags['url']))
			$this->googlePlusTags['url'] = $this->getProtocol()."://".Yii::app()->request->serverName.Yii::app()->request->requestUri; // defaults to current URL
		foreach ($this->googlePlusTags as $type => $value) { // loop through any other OG tags declared
			$this->registerGooglePlus($type, $value);
		}
	}

function(metadata) {
        var types = ['name', 'desc', 'author'],
            node = this.createElementNS(this.namespaces.gpx, 'metadata');
        for (var i=0; i < types.length; i++) {
            var type = types[i];
            if (metadata[type]) {
                var n = this.createElementNS(this.namespaces.gpx, type);
                n.appendChild(this.createTextNode(metadata[type]));
                node.appendChild(n);
            }
        }
        return node;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: Urls for chunk: dict<str wiki_url, list<str> ref_urls>.

def _wiki_urls_for_shard(shard_id, urls_dir=None):
  """"""
  urls_dir = urls_dir or WIKI_URLS_DIR
  urls_filepath = os.path.join(urls_dir, WIKI_URLS_FILE % shard_id)
  with tf.gfile.GFile(urls_filepath) as f:
    return json.loads(f.read())

def get_item_api(self, resource):

        parameters = self.get_item_parameters(resource)

        get_item_api = {
            'path': '/%s/{id}' % resource.get_api_name(),
            'description': 'Operations on %s' % resource.model.__name__,
            'operations': [
                {
                    'httpMethod': 'GET',
                    'nickname': 'get%s' % resource.model.__name__,
                    'summary': 'Get %s by its unique ID' %
                               resource.model.__name__,
                    'parameters': parameters,
                }
            ]
        }

        return get_item_api

Instruction: Given a code description, retrieve the corresponding code.


Question:
Returns a random integer between two positive integers (inclusive).
@param int $min Minimum limit
@param int $max Maximum limit
@return int Random integer between minimum and maximum limit
@throws \InvalidArgumentException If the limits are invalid

public function getInteger($min, $max)
    {
        $min = (int) $min;
        $max = (int) $max;

        if ($this->isOutOfBounds($min, 0, $max)) {
            throw new \InvalidArgumentException('Invalid minimum or maximum value');
        }

        return $this->generator->getNumber($min, $max);
    }

public function generateKey(array $options = [])
	{
		// Generate the encryption key.
		try
		{
			$public = DefuseKey::createNewRandomKey();
		}
		catch (EnvironmentIsBrokenException $ex)
		{
			throw new \RuntimeException('Cannot safely create a key', $ex->getCode(), $ex);
		}

		// Create the new encryption key object.
		return new Key('crypto', $public->saveToAsciiSafeString(), $public->getRawBytes());
	}

Instruction: Given a code description, retrieve the corresponding code.


Question:
// MustCurryWith works as CurryWith but panics where CurryWith would have
// returned an error.

func (v *HistogramVec) MustCurryWith(labels Labels) ObserverVec {
	vec, err := v.CurryWith(labels)
	if err != nil {
		panic(err)
	}
	return vec
}

def _init_humidity(self):

        if not self._humidity_init:
            self._humidity_init = self._humidity.humidityInit()
            if not self._humidity_init:
                raise OSError('Humidity Init Failed')

Instruction: Given a code description, retrieve the corresponding code.


Question:
Remove a connection listener
@param cm The connection manager
@param cl The connection listener

void removeConnectionListener(ConnectionManager cm, ConnectionListener cl)
   {
      if (cmToCl != null && cmToCl.get(cm) != null)
      {
         cmToCl.get(cm).remove(cl);
         clToC.remove(cl);
      }
   }

public void putListener(CallbackType callbackType, Method method) {
    if (callbacks == null) {
      callbacks = new EnumMap<>(CallbackType.class);
    }
    Method oldMethod = callbacks.put(callbackType, method);
    if (oldMethod != null) {
      String format = "Class %s has at least two methods, %s and %s, with annotation of %s. "
          + "At most one method is allowed for a given callback type. ";
      String message = String.format(format, listenerClass.getName(), oldMethod.getName(),
          method.getName(), callbackType.getAnnotationClass().getName());
      throw new EntityManagerException(message);
    }
  }

Instruction: Given a code description, retrieve the corresponding code.


Question: Any error that occurs during a doPost is caught and reported here.

@Override
	final protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setBufferSize(BUFFER_SIZE);
		postCount.incrementAndGet();
		try {
			reportingDoPost(req, resp);
		} catch (ThreadDeath t) {
			throw t;
		} catch (RuntimeException | ServletException | IOException e) {
			getLogger().log(Level.SEVERE, null, e);
			throw e;
		} catch (SQLException t) {
			getLogger().log(Level.SEVERE, null, t);
			throw new ServletException(t);
		}
	}

protected function itemTypeError(string $method, $item): string
    {
        $itemType = is_object($item) ? get_class($item) : gettype($item);

        return sprintf(
            '%s::%s expects item type (%s); received (%s) %s',
            static::class,
            $method,
            $this->itemType(),
            $itemType,
            VarPrinter::toString($item)
        );
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Exports the whole query as a {@link JsonObject}.

@see #injectParams(JsonObject) for the part that deals with global parameters
@see AbstractFtsQuery#injectParamsAndBoost(JsonObject) for the part that deals with the "query" entry

public JsonObject export() {
        JsonObject result = JsonObject.create();
        injectParams(result);

        JsonObject queryJson = JsonObject.create();
        queryPart.injectParamsAndBoost(queryJson);
        return result.put("query", queryJson);
    }

def queue_jobs(main_task_path, params_list, queue=None, batch_size=1000):

    if len(params_list) == 0:
        return []
    if queue is None:
        task_def = context.get_current_config().get("tasks", {}).get(main_task_path) or {}
        queue = task_def.get("queue", "default")

    from .queue import Queue
    queue_obj = Queue(queue)

    if queue_obj.is_raw:
        raise Exception("Can't queue regular jobs on a raw queue")

    all_ids = []

    for params_group in group_iter(params_list, n=batch_size):

        context.metric("jobs.status.queued", len(params_group))

        # Insert the job in MongoDB
        job_ids = Job.insert([{
            "path": main_task_path,
            "params": params,
            "queue": queue,
            "datequeued": datetime.datetime.utcnow(),
            "status": "queued"
        } for params in params_group], w=1, return_jobs=False)

        all_ids += job_ids

    queue_obj.notify(len(all_ids))
    set_queues_size({queue: len(all_ids)})

    return all_ids

Instruction: Given a code description, retrieve the corresponding code.


Question:
Merges all parameters and invokes the lazy ones.

@param Blueprint $mergeBlueprint The overrides during merging

@return Blueprint The merged blueprint

public function merge(Blueprint $mergeBlueprint): Blueprint
    {
        return new Blueprint(
            $this->className,
            $this->mergeParams($mergeBlueprint),
            $this->mergeSetters($mergeBlueprint),
            $this->mergeMutations($mergeBlueprint)
        );
    }

public function middleware($middleware)
    {
        $middleware = (array) $middleware;

        if (! is_array($this->cb)) {
            $this->cb = [
                'controller' => $this->cb,
                'middleware' => $middleware
            ];

            return $this;
        }

        if (!isset($this->cb['middleware'])) {
            $this->cb['middleware'] = $middleware;
        } else {
            $this->cb['middleware'] = array_merge($middleware, (array) $this->cb['middleware']);
        }

        return $this;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Keep the order of contents by the list of uids

@param array $uids
@param Paginator $contents

@return null|Paginator

protected function sortByUids($uids, $contents)
    {
        $uids = (array) $uids;

        $orderedUids = [];
        foreach ($uids as $key => $uid) {
            $orderedUids[$uid] = $key;
        }

        $formattedResult = [];
        foreach ($contents as $content) {
            if (isset($orderedUids[$content->getUid()])) {
                $formattedResult[$orderedUids[$content->getUid()]] = $content;
            }
        }

        ksort($formattedResult);

        return $formattedResult;
    }

@Override
  public int setPageID(P page) {
    int pageID = page.getPageID();
    if(pageID == -1) {
      pageID = getNextEmptyPageID();
      if(pageID == -1) {
        pageID = nextPageID++;
      }
      page.setPageID(pageID);
    }
    return pageID;
  }

Instruction: Given a code description, retrieve the corresponding code.


Question: // Fail reports a failure through

func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool {
	return Fail(a.t, failureMessage, msgAndArgs...)
}

public function check($code, string $email = null)
    {
        try {
            $this->prep($code, $email);
            return true;
        } catch (DoormanException $e) {
            $this->error = $e->getMessage();
            return false;
        }
    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
Update the model

@param Model $model

@return Model[]

public function update(Model $model)
    {
        $data['models'] = [];
        $data['models'][] = $this->createModelData($model);
        $data['action'] = 'merge';

        $modelResult = $this->getRequest()->request(
            'PATCH',
            $this->getRequestUrl('models'),
            $data
        );

        return $this->getModelsFromResult($modelResult);
    }

public function Comment2($CommentID, $Inserted = FALSE) {
      $this->CommentModel->Save2($CommentID, $Inserted);
      $this->Render('Blank', 'Utility', 'Dashboard');
   }

Instruction: Given a code description, retrieve the corresponding code.


Question:
setProgram(string, string) -> None

        Sets the id of the current program.

def setProgram(self, tlsID, programID):

        self._connection._sendStringCmd(
            tc.CMD_SET_TL_VARIABLE, tc.TL_PROGRAM, tlsID, programID)

func (p *Process) GetPid() int {
	if p.command != nil && p.command.Process != nil {
		return p.command.Process.Pid
	}
	return p.status.Pid
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
Helper to normalize the given locale (in BCP-47 syntax) to the java.util.Locale format.
@param {string} sLocale locale to normalize
@returns {string} Normalized locale or undefined if the locale can't be normalized

function normalize(sLocale) {
		var m;
		if ( typeof sLocale === 'string' && (m = rLocale.exec(sLocale.replace(/_/g, '-'))) ) {
			var sLanguage = m[1].toLowerCase();
			sLanguage = M_ISO639_NEW_TO_OLD[sLanguage] || sLanguage;
			var sScript = m[2] ? m[2].toLowerCase() : undefined;
			var sRegion = m[3] ? m[3].toUpperCase() : undefined;
			var sVariants = m[4] ? m[4].slice(1) : undefined;
			var sPrivate = m[6];
			// recognize and convert special SAP supportability locales (overwrites m[]!)
			if ( (sPrivate && (m = rSAPSupportabilityLocales.exec(sPrivate)))
				|| (sVariants && (m = rSAPSupportabilityLocales.exec(sVariants))) ) {
				return "en_US_" + m[1].toLowerCase(); // for now enforce en_US (agreed with SAP SLS)
			}
			// Chinese: when no region but a script is specified, use default region for each script
			if ( sLanguage === "zh" && !sRegion ) {
				if ( sScript === "hans" ) {
					sRegion = "CN";
				} else if ( sScript === "hant" ) {
					sRegion = "TW";
				}
			}
			return sLanguage + (sRegion ? "_" + sRegion + (sVariants ? "_" + sVariants.replace("-","_") : "") : "");
		}
	}

public static String resolveDataSourceTypeFromDialect(String dialect)
    {
        if (StringUtils.contains(dialect, "Oracle"))
        {
            return "Oracle";
        }
        else if (StringUtils.contains(dialect, "MySQL"))
        {
            return "MySQL";
        }
        else if (StringUtils.contains(dialect, "DB2390Dialect"))
        {
            return "DB2/390";
        }
        else if (StringUtils.contains(dialect, "DB2400Dialect"))
        {
            return "DB2/400";
        }
        else if (StringUtils.contains(dialect, "DB2"))
        {
            return "DB2";
        }
        else if (StringUtils.contains(dialect, "Ingres"))
        {
            return "Ingres";
        }
        else if (StringUtils.contains(dialect, "Derby"))
        {
            return "Derby";
        }
        else if (StringUtils.contains(dialect, "Pointbase"))
        {
            return "Pointbase";
        }
        else if (StringUtils.contains(dialect, "Postgres"))
        {
            return "Postgres";
        }
        else if (StringUtils.contains(dialect, "SQLServer"))
        {
            return "SQLServer";
        }
        else if (StringUtils.contains(dialect, "Sybase"))
        {
            return "Sybase";
        }
        else if (StringUtils.contains(dialect, "HSQLDialect"))
        {
            return "HyperSQL";
        }
        else if (StringUtils.contains(dialect, "H2Dialect"))
        {
            return "H2";
        }

        return dialect;

    }

Instruction: Given a code description, retrieve the corresponding code.


Question:
prepare the group by

@access private
@return string

private function _prepareGroupBy()
	{
		$sQuery = '';

		if (is_array($this->_aGroupBy) && count($this->_aGroupBy) > 0) {

			$sQuery .= ' GROUP BY '.implode(',', $this->_aGroupBy).' ';
		}

		return $sQuery;
	}

func (conn *FakeVTGateConn) AddQuery(
	sql string,
	bindVariables map[string]*querypb.BindVariable,
	session *vtgatepb.Session,
	expectedResult *sqltypes.Result) {
	conn.execMap[sql] = &queryResponse{
		execQuery: &queryExecute{
			SQL:           sql,
			BindVariables: bindVariables,
			Session:       session,
		},
		reply: expectedResult,
	}
}

Instruction: Given a code description, retrieve the corresponding code.


Question:
// String returns a strongly random string of characters (taken from
// randomCharset) of the specified length. The returned string contains ~5.8
// bits of entropy per character, due to the character set used.

func String(l int) string {
	bs := make([]byte, l)
	for i := range bs {
		bs[i] = randomCharset[defaultSecureRand.Intn(len(randomCharset))]
	}
	return string(bs)
}

public function setSeed($seed)
    {
        if (is_int($seed) !== true) {
            throw new Exception(
                sprintf('The type of the seed value "%s" need to be int. You passed a(n) "%s".', $seed, gettype($seed))
            );
        }

        // We need to call different methods depending on chosen source
        switch ($this->getMode()) {

            case self::MODE_PHP_MERSENNE_TWISTER:
                mt_srand($seed);
                break;

            case self::MODE_PHP_DEFAULT:
                srand($seed);
                break;

            case self::MODE_OPEN_SSL:
            default:
                // Intentionally left blank
                break;
        }

        $this->seed = $seed;
    }

Instruction: Given a code description, retrieve the corresponding code.


Question: all rolled into one. This is okay since the grammar is so simple.

Filter<S> parseRoot() {
        Filter<S> filter = parseFilter();
        int c = nextCharIgnoreWhitespace();
        if (c >= 0) {
            mPos--;
            throw error("Unexpected trailing characters");
        }
        return filter;
    }

def inspect_theme_data
      print_clear_line
      Jekyll.logger.debug "Reading:", "Theme Data Files..."
      @theme_data_files.each { |file| Jekyll.logger.debug "", file }
      print_clear_line
      Jekyll.logger.debug "Merging:", "Theme Data Hash..."

      unless site.config["show-data"] && site.config["verbose"]
        Jekyll.logger.debug "", "use --show-data with --verbose to output " \
                                "merged Data Hash.".cyan
        print_clear_line
      end
    end

Instruction: Given a code description, retrieve the corresponding code.


Question:
*
@param $date
@param $days
@return bool|string

public static function subDays($date, $days)
    {
        $d = self::formatDate($date);
        $d = date_parse($d);
        $d = mktime($d['hour'], $d['minute'], $d['second'], $d['month'], $d['day'] - $days, $d['year']);
        return self::formatDate($d);
    }

private function processData(array $data): void
    {
        foreach ($data['formatters'] as $locale => $f) {
            if (!isset($this->formatters[$locale])) {
                $this->formatters[$locale] = array();
            }

            foreach ($f as $formatter => $d) {
                $calendar = \IntlDateFormatter::GREGORIAN;
                if (isset($d['calendar']) && $d['calendar'] === 'traditional') {
                    $calendar = \IntlDateFormatter::TRADITIONAL;
                }

                $this->formatters[$locale][$formatter] = new \IntlDateFormatter($locale, null, null, null, $calendar, $d['pattern']);
            }
        }
    }

Instruction: Given a code description, retrieve the corresponding code.