Question:
Returns holidays by year.
@param {number} year
@param {boolean} [includeWeekends] include holidays falling on a weekend (default: false)
@return {Array}

function(year, includeWeekends) {
    initialize(year);

    includeWeekends = includeWeekends || false;

    var self = this;
    var holidays = [];

    if (!includeWeekends) {
      self.year.discardWeekends();
    }

    Object.keys(self.year.holidays).forEach(function(month) {
      self.year.holidays[month].forEach(function(holiday) {
        holidays.push(holiday);
      });
    });

    return holidays;
  }

public static function url($identifier, $data = null, $domain = null) {

		if(false === is_string($identifier)) {
			return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($identifier)), E_USER_ERROR);
		}

		if(false === static :: routeExists($identifier)) {
			return trigger_error(sprintf('Route identifier "%s" not found in routes.php', $identifier), E_USER_ERROR);
		}

		if(null !== $data && false === is_string($data) && false === is_array($data)) {
			return trigger_error(sprintf('Argument 2 passed to %s() must be of the type array or string, "%s" given', __METHOD__, gettype($data)), E_USER_ERROR);
		}

		if(null !== $domain && false === is_string($domain)) {
			return trigger_error(sprintf('Argument 3 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($domain)), E_USER_ERROR);
		}

		if(true === is_string($data)) {
			$data = [$data];
		}

		if(null === $data) {
			$data = [];
		}

		$route 		= static :: getRoute($identifier);
		$url 		= $route -> getUrl();
		$parameters = 0;
		$optionals  = 0;

		if(preg_match_all('#\{(.*?)(\?)?\}#i', $url, $matches)) {

			foreach($matches[2] as $optional) {

				if('?' === $optional) {

					$optionals++;
					continue;
				}

				$parameters++;
			}

			if(count($data) < $parameters) {
				return trigger_error(sprintf('Incorrect number of parameters given for Router url with identifier "%s". Expecting %s, got %s with %s optional', $route -> getIdentifier(), count($matches[2]), count($data), $optionals), E_USER_ERROR);
			}

			foreach($matches[0] as $index => $match) {

				$match 		= $matches[0][$index];
				$type 		= $matches[1][$index];
				$optional 	= $matches[2][$index];
				$where 		= $route -> getWhere();
				$replace 	= static :: $types['string'];

				if(true === isset(static :: $types[$type])) {
					$replace = static :: $types[$type];
				}

				if(true === is_array($where)) {

					foreach($where as $key => $regex) {

						if($key === $type) {

							$replace =$regex;
							break;
						}
					}
				}

				if(true === isset($data[$index])) {

					if(false === is_string($data[$index]) && false === is_numeric($data[$index])) {
						return trigger_error(sprintf('Router url width id "%s" expects parameters to be a String', $route -> getIdentifier()));
					}

					if(preg_match('#' . $replace . '#i', $data[$index])) {
						$url = preg_replace('#'. preg_quote($match) .'#i', $data[$index], $url, 1);
					}
					else {
						return trigger_error(sprintf('Parameters given to router url width id "%s" do not match. Trying to match regular expression pattern "%s" with "%s" as subject', $route -> getIdentifier(), $replace, $data[$index]));
					}
				}
				elseif('' !== $optional) {
					$url = preg_replace('#'. '/?' . preg_quote($match) .'#i', '', $url, 1);
				}
			}
		}

		if(null !== $domain && false === static :: domainExists($domain)) {
			return trigger_error(sprintf('Domain "%s" does not exists in routes.php', $domain), E_USER_ERROR);
		}

		//Check if routes has a prefix and add it if it does
		$prefix = $route -> getPrefix();

		if(true === isset($prefix['url'])) {
			$url = $prefix['url'] . $url;
		}

		return (null !== $domain ? rtrim($domain, '/') . '/' : '') . $url;
	}

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


Question:
// CombinedOutput runs the command  in a bash shell and returns its
// combined standard output and standard error.

func (e *ExecRunner) CombinedOutput(cmd string) (string, error) {
	var b bytes.Buffer
	err := e.CombinedOutputTo(cmd, &b)
	if err != nil {
		return "", errors.Wrapf(err, "running command: %s\n output: %s", cmd, b.Bytes())
	}
	return b.String(), nil

}

def html(self):

        failure = ""
        skipped = None
        stdout = tag.text(self.stdout)
        stderr = tag.text(self.stderr)

        if self.skipped:
            skipped = """

Skipped: {msg}

{skip}

            """.format(msg=tag.text(self.skipped_msg),
                       skip=tag.text(self.skipped))

        if self.failed():
            failure = """

Failed: {msg}

{fail}

            """.format(msg=tag.text(self.failure_msg),
                       fail=tag.text(self.failure))

        properties = [x.html() for x in self.properties]

        return """

                {testname}

                {testclassname}

                Time Taken: {duration}s

            {skipped}
            {failure}

            {properties}

Stdout

{stdout}

Stderr

{stderr}

        """.format(anchor=self.anchor(),
                   testname=self.name,
                   testclassname=self.testclass.name,
                   duration=self.duration,
                   failure=failure,
                   skipped=skipped,
                   properties="".join(properties),
                   stdout=stdout,
                   stderr=stderr)

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


Question:
Select All

@return mixed
@throws \GapOrm\Exceptions\QueryFailedException

public function selectAll()
    {
        if (is_null($this->sth)) {
            throw new QueryFailedException();
        }

        return $this->sth->fetchAll(\PDO::FETCH_OBJ);
    }

func (c *client) ScanEverything(ctx context.Context, sop *ScanOp) ([]DomainObject, string, error) {
	if !c.initialized {
		return nil, "", &ErrNotInitialized{}
	}
	// look up the entity in the registry
	re, err := c.registrar.Find(sop.object)
	if err != nil {
		return nil, "", errors.Wrap(err, "failed to ScanEverything")
	}
	// convert the fieldsToRead to the server side equivalent
	fieldsToRead, err := re.ColumnNames(sop.fieldsToRead)
	if err != nil {
		return nil, "", errors.Wrap(err, "failed to ScanEverything")
	}

	// call the server side method
	values, token, err := c.connector.Scan(ctx, re.EntityInfo(), fieldsToRead, sop.token, sop.limit)
	if err != nil {
		return nil, "", err
	}
	objectArray := objectsFromValueArray(sop.object, values, re, nil)
	return objectArray, token, nil
}

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


Question:
Scope: Coditionally apply orderBy() to the query based on the current request.

@param  \Illuminate\Database\Query\Builder  $query
@param  Request  $request
@return Model

public function scopeRequestOrder($query, Request $request)
    {
        if ($request->has('orderBy')) {
            $direction = ($request->has('orderDir')) ? $request->input('orderDir') : 'desc';
            $query->orderBy($request->input('orderBy'), $direction);
        }

        return $query;
    }

private function getJobs()
    {
        if ($this->hasParameter('profile')) {
            $this->fetchJobs($this->getParameter('profile'));

            return;
        }

        $this->buildJobs([$this->getParameter('job')]);
    }

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


Question:
Generates the pagination links (minus "next" and "previous"), depending on whether the pagination links are shown
in natural or reversed order.

private function _show_pages() {

        $output = '';

        // if the total number of pages is lesser than the number of selectable pages
        if ($this->_properties['total_pages'] <= $this->_properties['selectable_pages'])

            // iterate ascendingly or descendingly, depending on whether we're showing links in reverse order or not
            for (

                $i = ($this->_properties['reverse'] ? $this->_properties['total_pages'] : 1);
                ($this->_properties['reverse'] ? $i >= 1 : $i <= $this->_properties['total_pages']);
                ($this->_properties['reverse'] ? $i-- : $i++)

            ) {

                // CSS classes to be applied to the list item, if any
                $css_classes = isset($this->_properties['css_classes']['list_item']) && $this->_properties['css_classes']['list_item'] != '' ? array(trim($this->_properties['css_classes']['list_item'])) : array();

                // if this the currently selected page, highlight it
                if ($this->_properties['page'] == $i) $css_classes[] = 'active';

                // generate markup
                $output .= '
_build_uri($i) . '"' .

                    // add CSS classes to the anchor, if necessary
                    (isset($this->_properties['css_classes']['anchor']) && $this->_properties['css_classes']['anchor'] != '' ? ' class="' . trim($this->_properties['css_classes']['anchor']) . '"' : '') . '>' .

                    // apply padding if required
                    ($this->_properties['padding'] ? str_pad($i, strlen($this->_properties['total_pages']), '0', STR_PAD_LEFT) : $i) .

                    '
';

            }

        // if the total number of pages is greater than the number of selectable pages
        else {

            // CSS classes to be applied to the list item, if any
            $css_classes = isset($this->_properties['css_classes']['list_item']) && $this->_properties['css_classes']['list_item'] != '' ? array(trim($this->_properties['css_classes']['list_item'])) : array();

            // highlight if the page is currently selected
            if ($this->_properties['page'] == ($this->_properties['reverse'] ? $this->_properties['total_pages'] : 1)) $css_classes[] = 'active';

            // start with a link to the first or last page, depending if we're displaying links in reverse order or not

            // generate markup
            $output .= '
_build_uri($this->_properties['reverse'] ? $this->_properties['total_pages'] : 1) . '"' .

                // add CSS classes to the anchor, if necessary
                (isset($this->_properties['css_classes']['anchor']) && $this->_properties['css_classes']['anchor'] != '' ? ' class="' . trim($this->_properties['css_classes']['anchor']) . '"' : '') . '>' .

                // if padding is required
                ($this->_properties['padding'] ?

                    // apply padding
                    str_pad(($this->_properties['reverse'] ? $this->_properties['total_pages'] : 1), strlen($this->_properties['total_pages']), '0', STR_PAD_LEFT) :

                    // show the page number
                    ($this->_properties['reverse'] ? $this->_properties['total_pages'] : 1)) .

                '
';

            // compute the number of adjacent pages to display to the left and right of the currently selected page so
            // that the currently selected page is always centered
            $adjacent = floor(($this->_properties['selectable_pages'] - 3) / 2);

            // this number must be at least 1
            if ($adjacent == 0) $adjacent = 1;

            // find the page number after we need to show the first "..."
            // (depending on whether we're showing links in reverse order or not)
            $scroll_from = ($this->_properties['reverse'] ?

                $this->_properties['total_pages'] - ($this->_properties['selectable_pages'] - $adjacent) + 1 :

                $this->_properties['selectable_pages'] - $adjacent);

            // get the page number from where we should start rendering
            // if displaying links in natural order, then it's "2" because we have already rendered the first page
            // if we're displaying links in reverse order, then it's total_pages - 1 because we have already rendered the last page
            $starting_page = ($this->_properties['reverse'] ? $this->_properties['total_pages'] - 1 : 2);

            // if the currently selected page is past the point from where we need to scroll,
            if (

                ($this->_properties['reverse'] && $this->_properties['page'] <= $scroll_from) ||
                (!$this->_properties['reverse'] && $this->_properties['page'] >= $scroll_from)

            ) {

                // by default, the starting_page should be whatever the current page plus/minus $adjacent
                // depending on whether we're showing links in reverse order or not
                $starting_page = $this->_properties['page'] + ($this->_properties['reverse'] ? $adjacent : -$adjacent);

                // but if that would mean displaying less navigation links than specified in $this->_properties['selectable_pages']
                if (

                    ($this->_properties['reverse'] && $starting_page < ($this->_properties['selectable_pages'] - 1)) ||
                    (!$this->_properties['reverse'] && $this->_properties['total_pages'] - $starting_page < ($this->_properties['selectable_pages'] - 2))

                )

                    // adjust the value of $starting_page again
                    if ($this->_properties['reverse']) $starting_page = $this->_properties['selectable_pages'] - 1;
                    else $starting_page -= ($this->_properties['selectable_pages'] - 2) - ($this->_properties['total_pages'] - $starting_page);

                // put the "..." after the link to the first/last page, depending on whether we're showing links in reverse order or not
                $output .= '
_properties['css_classes']['list_item']) && $this->_properties['css_classes']['list_item'] != '' ? ' class="' . $this->_properties['css_classes']['list_item'] . '"' : '') . '>' .

                    // add CSS classes to the span element, if necessary
                    '_properties['css_classes']['anchor']) && $this->_properties['css_classes']['anchor'] != '' ? ' class="' . trim($this->_properties['css_classes']['anchor']) . '"' : '') . '>' .

                    '…
';

            }

            // get the page number where we should stop rendering
            // by default, this value is the sum of the starting page plus/minus (depending on whether we're showing links
            // in reverse order or not) whatever the number of $this->_properties['selectable_pages'] minus 3 (first page,
            // last page and current page)
            $ending_page = $starting_page + (($this->_properties['reverse'] ? -1 : 1) * ($this->_properties['selectable_pages'] - 3));

            // if we're showing links in natural order and ending page would be greater than the total number of pages minus 1
            // (minus one because we don't take into account the very last page which we output automatically)
            // adjust the ending page
            if ($this->_properties['reverse'] && $ending_page < 2) $ending_page = 2;

            // or, if we're showing links in reverse order, and ending page would be smaller than 2
            // (2 because we don't take into account the very first page which we output automatically)
            // adjust the ending page
            elseif (!$this->_properties['reverse'] && $ending_page > $this->_properties['total_pages'] - 1) $ending_page = $this->_properties['total_pages'] - 1;

            // render pagination links
            for ($i = $starting_page; $this->_properties['reverse'] ? $i >= $ending_page : $i <= $ending_page; $this->_properties['reverse'] ? $i-- : $i++) {

                // CSS classes to be applied to the list item, if any
                $css_classes = isset($this->_properties['css_classes']['list_item']) && $this->_properties['css_classes']['list_item'] != '' ? array(trim($this->_properties['css_classes']['list_item'])) : array();

                // highlight the currently selected page
                if ($this->_properties['page'] == $i) $css_classes[] = 'active';

                // generate markup
                $output .= '
_build_uri($i) . '"' .

                    // add CSS classes to the anchor, if necessary
                    (isset($this->_properties['css_classes']['anchor']) && $this->_properties['css_classes']['anchor'] != '' ? ' class="' . trim($this->_properties['css_classes']['anchor']) . '"' : '') . '>' .

                    // apply padding if required
                    ($this->_properties['padding'] ? str_pad($i, strlen($this->_properties['total_pages']), '0', STR_PAD_LEFT) : $i) .

                    '
';

            }

            // if we have to, place another "..." at the end, before the link to the last/first page (depending on whether we're showing links in reverse order or not)
            if (

                ($this->_properties['reverse'] && $ending_page > 2) ||
                (!$this->_properties['reverse'] && $this->_properties['total_pages'] - $ending_page > 1)

            )

                // generate markup
                $output .= '
_properties['css_classes']['list_item']) && $this->_properties['css_classes']['list_item'] != '' ? ' class="' . $this->_properties['css_classes']['list_item'] . '"' : '') . '>' .

                    // add CSS classes to the span element, if necessary
                    '_properties['css_classes']['anchor']) && $this->_properties['css_classes']['anchor'] != '' ? ' class="' . trim($this->_properties['css_classes']['anchor']) . '"' : '') . '>' .

                    '…
';

            // now we put a link to the last/first page (depending on whether we're showing links in reverse order or not)

            // CSS classes to be applied to the list item, if any
            $css_classes = isset($this->_properties['css_classes']['list_item']) && $this->_properties['css_classes']['list_item'] != '' ? array(trim($this->_properties['css_classes']['list_item'])) : array();

            // highlight if the page is currently selected
            if ($this->_properties['page'] == $i) $css_classes[] = 'active';

            // generate markup
            $output .= '
_build_uri($this->_properties['reverse'] ? 1 : $this->_properties['total_pages']) . '"' .

                // add CSS classes to the anchor, if necessary
                (isset($this->_properties['css_classes']['anchor']) && $this->_properties['css_classes']['anchor'] != '' ? ' class="' . trim($this->_properties['css_classes']['anchor']) . '"' : '') . '>' .

                // also, apply padding if necessary
                ($this->_properties['padding'] ? str_pad(($this->_properties['reverse'] ? 1 : $this->_properties['total_pages']), strlen($this->_properties['total_pages']), '0', STR_PAD_LEFT) : ($this->_properties['reverse'] ? 1 : $this->_properties['total_pages'])) .

                '
';

        }

        // return the resulting string
        return $output;

    }

def search_cat(self, catid, keyword, p_index=1):
        '''

        '''
        catid = 'sid' + catid
        logger.info('-' * 20)
        logger.info('search cat')
        logger.info('catid: {0}'.format(catid))
        logger.info('keyword: {0}'.format(keyword))

        # catid = ''
        if p_index == '' or p_index == '-1':
            current_page_number = 1
        else:
            current_page_number = int(p_index)
        res_all = self.ysearch.get_all_num(keyword, catid=catid)

        results = self.ysearch.search_pager(
            keyword,
            catid=catid,
            page_index=current_page_number,
            doc_per_page=CMS_CFG['list_num']
        )
        page_num = int(res_all / CMS_CFG['list_num'])

        kwd = {'title': '查找结果',
               'pager': '',
               'count': res_all,
               'current_page': current_page_number,
               'catid': catid,
               'keyword': keyword}

        self.render('misc/search/search_list.html',
                    kwd=kwd,
                    srecs=results,
                    pager=gen_pager_bootstrap_url(
                        '/search/{0}/{1}'.format(catid, keyword),
                        page_num,
                        current_page_number
                    ),
                    userinfo=self.userinfo,
                    cfg=CMS_CFG)

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


Question:
Service a GET request as described below.
Request:
{@code
GET http://<nn>:<port>/data[/<path>] HTTP/1.1
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException {
    NameNode.getNameNodeMetrics().numFileDataServletDoGet.inc();
    final UnixUserGroupInformation ugi = getUGI(request);
    final ClientProtocol nnproxy = createNameNodeProxy(ugi);

    try {
      final String path = request.getPathInfo() != null
        ? request.getPathInfo() : "/";
      FileStatus info = nnproxy.getFileInfo(path);
      if ((info != null) && !info.isDir()) {
        response.sendRedirect(createUri(info, ugi, nnproxy,
              request).toURL().toString());
      } else if (info == null){
        response.sendError(400, "cat: File not found " + path);
      } else {
        response.sendError(400, "cat: " + path + ": is a directory");
      }
    } catch (URISyntaxException e) {
      response.getWriter().println(e.toString());
    } catch (IOException e) {
      response.sendError(400, e.getMessage());
    }
  }

public void doGet(HttpServletRequest req, HttpServletResponse res)
		throws ServletException, IOException
	{
		this.doProcess(req, res);
	}

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


Question: Stop children that are working on overdue jobs.

def check_spinning_children(self):
        ''''''
        child_jobs = self.task_master.get_child_work_units(self.worker_id)
        # We will kill off any jobs that are due before "now".  This
        # isn't really now now, but now plus a grace period to make
        # sure spinning jobs don't get retried.
        now = time.time() + self.stop_jobs_early
        for child, wul in child_jobs.iteritems():
            if not isinstance(wul, (list, tuple)):
                # Support old style get_child_work_units which returns
                # single WorkUnit objects instead of list of them.
                wul = [wul]
            if not wul:
                # This worker is idle, but oddly, still present; it should
                # clean up after itself
                continue
            # filter on those actually assigned to the child worker
            wul = filter(lambda wu: wu.worker_id == child, wul)
            # check for any still active not-overdue job
            if any(filter(lambda wu: wu.expires > now, wul)):
                continue
            # So either someone else is doing its work or it's just overdue
            environment = self.task_master.get_heartbeat(child)
            if not environment:
                continue  # derp
            if 'pid' not in environment:
                continue  # derp
            if environment['pid'] not in self.children:
                continue  # derp
            os.kill(environment['pid'], signal.SIGTERM)
            # This will cause the child to die, and do_some_work will
            # reap it; but we'd also like the job to fail if possible
            for wu in wul:
                if wu.data is None:
                    logger.critical('how did wu.data become: %r' % wu.data)
                else:
                    wu.data['traceback'] = 'job expired'
                wu.fail(exc=Exception('job expired'))

public static Problem readFromFile(File file, double bias) throws IOException, InvalidInputDataException {
        return Train.readProblem(file, bias);
    }

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


Question: Starts the work loop.

def work(self):

        self.work_init()

        self.work_loop(max_jobs=self.max_jobs, max_time=self.max_time)

        self.work_stop()

function mappableLoop(n) {
            return n.type === 'AwaitExpression' && !n.$hidden || inAsyncLoop && (n.type === 'BreakStatement' || n.type === 'ContinueStatement') && n.label;
        }

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


Question:
Returns the value for the given key.

@param  string $key

@return mixed

protected function data(string $key)
	{
		if (empty($this->data[$key])) {
			throw new NotificationLabelsException("The [{$key}] has to be provided within the notification data.");
		}

		return $this->data[$key];
	}

def hash_to_rets_query_string(hash)
      [].tap do |str|
        hash.each_pair do |k,v|
          val = value_map(v)
          str << "(#{k.to_s.camelize}=#{val})"
        end
      end.join(',')
    end

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


Question: __________________________________________________________________

function processSort(feed,sort,sortName) {
	if (warnReleaseStatus(sort.release_status)) {
		console.log('Warning: sort '+sortName+' is '+sort.release_status+deprecationInfo(feed,sort.name,'sort',sort.deprecated_since));
	}
	swagSort(sort);
	if (sort.sort_direction) {
		sort.sort_direction = toArray(sort.sort_direction);
		for (var i in sort.sort_direction) {
			var sortDirection = sort.sort_direction[i];
			var sortDirectionName = ('s-'+feed.name+'-'+sort.name+'-'+sortDirection.value).toCamelCase();
			if (seen.indexOf(sortDirectionName)<0) {
				processSortDirection(feed,sort,sortDirection,sortDirectionName);
				seen.push(sortDirectionName);
			}
			else {
				console.log('* Skipping sort '+sortDirectionName+' as duplicate name');
			}
		}
	}
	else {
		if (seen.indexOf(sortName)<0) {
			exportSort(feed,sort,sortName);
			seen.push(sortName);
		}
		else {
			console.log('* Skipping sort '+sortName+' as duplicate name');
		}
	}
}

@Override
    protected void paintComponent(java.awt.Graphics g) {
        if (!isInitialized()) {
            return;
        }

        final java.awt.Graphics2D G2 = (java.awt.Graphics2D) g.create();

        CENTER.setLocation(getGaugeBounds().getCenterX(), getGaugeBounds().getCenterX());

        G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Translate the coordinate system related to the insets
        G2.translate(getFramelessOffset().getX(), getFramelessOffset().getY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        final java.awt.Shape OLD_CLIP = G2.getClip();

        // Draw the horizon
        G2.setClip(CLIP);

        // Rotate around roll
        G2.rotate(-Math.toRadians(roll), CENTER.getX(), CENTER.getY());

        // Translate about dive
        G2.translate(0, -(pitch * pitchPixel) - getFramelessOffset().getY());

        // Draw horizon
        G2.drawImage(horizonImage, 0, (int) ((getHeight() - horizonImage.getHeight()) / 2.0), null);

        // Draw the scale and angle indicator
        G2.translate(-getFramelessOffset().getX(), (pitch * pitchPixel) + getFramelessOffset().getY());
        G2.drawImage(horizonForegroundImage, (int) (getWidth() * 0.5 - horizonForegroundImage.getWidth() / 2.0), (int) (getWidth() * 0.10747663551401869), null);

        G2.setTransform(OLD_TRANSFORM);
        G2.setClip(OLD_CLIP);

        // Draw combined background image
        G2.drawImage(bImage, 0, 0, null);

        // Draw combined foreground image
        G2.drawImage(fImage, 0, 0, null);

        if (!isEnabled()) {
            G2.drawImage(disabledImage, 0, 0, null);
        }

        G2.dispose();
    }

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


Question:
@param string $address

@return \Geocoder\Model\Address|null

protected function _execute($address) {
		$this->_Geocoder = new Geocoder();
		try {
			$addresses = $this->_Geocoder->geocode($address);
		} catch (InconclusiveException $e) {
			return null;
		} catch (NotAccurateEnoughException $e) {
			return null;
		}

		if (!$addresses || $addresses->count() < 1) {
			return null;
		}
		$address = $addresses->first();
		return $address;
	}

public function match($pathinfo)
    {
        $routes = array();
        $this->debug(sprintf('match: Matching %s', $pathinfo));

        foreach ($this->matchers as $matcher) {
            try {
                $routes = $matcher->match($pathinfo);
                break;
            } catch (ResourceNotFoundException $e) {
            } catch (MethodNotAllowedException $e) {
            }
        }

        if (!isset($routes['_route']) || !isset($routes['_controller'])) {
            $mesg = 'match: No Routes Found.';
            $this->alert($mesg);
            throw new RoutingException($mesg);
        }

        $this->debug(sprintf('match: Route matched %s', $routes['_route']));

        return($routes);
    }

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


Question: Interactively change the color map by scrolling.

def sc_cmap(self, viewer, event, msg=True):

        direction = self.get_direction(event.direction)
        self._cycle_cmap(viewer, msg, direction=direction)
        return True

@Override
  public void updateAdaptiveData(final String[] tokens,
      final String[] outcomes) {

    for (int i = 0; i < tokens.length; i++) {
      this.previousMap.put(tokens[i], outcomes[i]);
    }
  }

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


Question:
Search the parameters that were overridden during the parameters-merge phase.

@return array Names of the overridden parameters.

private function searchOverridenParameters(array $parametersList): array
    {
        $parametersUsageCount = [];

        foreach ($parametersList as $list) {
            foreach ($list as $parameter => $_value) {
                if (!isset($parametersUsageCount[$parameter])) {
                    $parametersUsageCount[$parameter] = 0;
                }

                $parametersUsageCount[$parameter] += 1;
            }
        }

        $overriddenParameters = array_filter($parametersUsageCount, function ($count) {
            return $count > 1;
        });

        return array_keys($overriddenParameters);
    }

private function load_command_config_file($file, $prefix) {

    $yaml = $this->sm->get('pegase.component.yaml.spyc');
    $data = $yaml->parse($file);
    $mm = $this->sm->get('pegase.core.module_manager');

    foreach($data as $command_name => $command) {

      if(key_exists('prefix', $command)) {
        $prefix_to_add = $command['prefix'];
      }
      else
        $prefix_to_add = $command_name;

      if(key_exists('class', $command) && key_exists('method', $command)) {

        if(!key_exists('parameters', $command))
          $command['parameters'] = null;

        if(!key_exists('options', $command))
          $command['options'] = null;

        $this->add_command(array(
          'name' => $prefix . $prefix_to_add,
          'class' => $command['class'],
          'method' => $command['method'],
          'parameters' => $command['parameters'],
          'options' => $command['options']
        ));
      }
      else if(key_exists('import', $command)) {
        $this->load_command_config_file(
          $mm->get_file($command['import']['module'], $command['import']['file']),
          $prefix . $prefix_to_add);
      }
    }
  }

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


Question:
// SetDeltaY sets the DeltaY optional argument. Y delta in CSS pixels
// for mouse wheel event (default: 0).

func (a *DispatchMouseEventArgs) SetDeltaY(deltaY float64) *DispatchMouseEventArgs {
	a.DeltaY = &deltaY
	return a
}

def require_option(current_ctx: click.Context, param_name: str) -> None:
    """"""

    ctx = current_ctx
    param_definition = None
    while ctx is not None:
        # ctx.command.params has the actual definition of the param. We use
        # this when raising the exception.
        param_definition = next(
            (p for p in ctx.command.params if p.name == param_name), None
        )

        # ctx.params has the current value of the parameter, as set by the user.
        if ctx.params.get(param_name):
            return
        ctx = ctx.parent

    assert param_definition, f"unknown parameter {param_name}"
    raise click.MissingParameter(ctx=current_ctx, param=param_definition)

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


Question:
// Update updates an existing archive, if found.
// It returns whether it was found, and - if so - the (updated) existing archive and its old partition

func (b *BigtableIdx) Update(point schema.MetricPoint, partition int32) (idx.Archive, int32, bool) {
	pre := time.Now()

	archive, oldPartition, inMemory := b.MemoryIndex.Update(point, partition)

	if !b.cfg.UpdateBigtableIdx {
		statUpdateDuration.Value(time.Since(pre))
		return archive, oldPartition, inMemory
	}

	if inMemory {
		// bigtable uses partition ID in the key prefix, so an "update" that changes the partition for
		// an existing metricDef will just create a new row in the table and won't remove the old row.
		// So we need to explicitly delete the old entry.
		if oldPartition != partition {
			go func() {
				err := b.deleteRow(FormatRowKey(archive.Id, oldPartition))
				if err != nil {
					log.Errorf("bigtable-idx: Failed to delete row %s: %s", archive.Id, err)
				}
			}()
		}
		// check if we need to save to bigtable.
		now := uint32(time.Now().Unix())
		if archive.LastSave < (now - b.cfg.updateInterval32) {
			archive = b.updateBigtable(now, inMemory, archive, partition)
		}
	}

	statUpdateDuration.Value(time.Since(pre))
	return archive, oldPartition, inMemory
}

def check_url(url_data, logger):
    """"""
    if url_data.has_result:
        logger.log_url(url_data.to_wire())
    else:
        cache = url_data.aggregate.result_cache
        key = url_data.cache_url
        result = cache.get_result(key)
        if result is None:
            # check
            check_start = time.time()
            try:
                url_data.check()
                do_parse = url_data.check_content()
                url_data.checktime = time.time() - check_start
                # Add result to cache
                result = url_data.to_wire()
                cache.add_result(key, result)
                for alias in url_data.aliases:
                    # redirect aliases
                    cache.add_result(alias, result)
                # parse content recursively
                # XXX this could add new warnings which should be cached.
                if do_parse:
                    parser.parse_url(url_data)
            finally:
                # close/release possible open connection
                url_data.close_connection()
        else:
            # copy data from cache and adjust it
            result = copy.copy(result)
            result.parent_url = url_data.parent_url
            result.base_ref = url_data.base_ref or u""
            result.base_url = url_data.base_url or u""
            result.line = url_data.line
            result.column = url_data.column
            result.level = url_data.recursion_level
            result.name = url_data.name
        logger.log_url(result)

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


Question:
Connect to the remote server.

@see __construct()

@throws Horde\Socket\Client\Exception

protected function _connect(
        $host, $port, $timeout, $secure, $context, $retries = 0
    )
    {
        $conn = '';
        if (!strpos($host, '://')) {
            switch (strval($secure)) {
            case 'ssl':
            case 'sslv2':
            case 'sslv3':
                $conn = $secure . '://';
                $this->_secure = true;
                break;

            case 'tlsv1':
                $conn = 'tls://';
                $this->_secure = true;
                break;

            case 'tls':
            default:
                $conn = 'tcp://';
                break;
            }
        }
        $conn .= $host;
        if ($port) {
            $conn .= ':' . $port;
        }

        $this->_stream = @stream_socket_client(
            $conn,
            $error_number,
            $error_string,
            $timeout,
            STREAM_CLIENT_CONNECT,
            stream_context_create($context)
        );

        if ($this->_stream === false) {
            /* From stream_socket_client() page: a function return of false,
             * with an error code of 0, indicates a "problem initializing the
             * socket". These kind of issues are seen on the same server
             * (and even the same user account) as sucessful connections, so
             * these are likely transient issues. Retry up to 3 times in these
             * instances. */
            if (!$error_number && ($retries < 3)) {
                return $this->_connect($host, $port, $timeout, $secure, ++$retries, $context);
            }

            $e = new Client\Exception(
                'Error connecting to server.'
            );
            $e->details = sprintf("[%u] %s", $error_number, $error_string);
            throw $e;
        }

        stream_set_timeout($this->_stream, $timeout);

        if (function_exists('stream_set_read_buffer')) {
            stream_set_read_buffer($this->_stream, 0);
        }
        stream_set_write_buffer($this->_stream, 0);

        $this->_connected = true;
    }

public function execute(Input $input, Output $output)
    {
        $connector = $input->getArgument('connector') ?: $this->app->config->get('queue.connector', 'sync');

        $queue = $input->getOption('queue') ?: $this->app->config->get("queue.{$connector}", 'default');
        $delay = $input->getOption('delay');
        $sleep = $input->getOption('sleep');
        $tries = $input->getOption('tries');

        $this->listenForEvents();

        if ($input->getOption('once')) {
            $this->worker->runNextJob($connector, $queue, $delay, $sleep, $tries);
        } else {
            $memory  = $input->getOption('memory');
            $timeout = $input->getOption('timeout');
            $this->worker->daemon($connector, $queue, $delay, $sleep, $tries, $memory, $timeout);
        }
    }

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


Question: // Validate inspects the fields of the type to determine if they are valid.

func (s *DeleteApiKeyInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "DeleteApiKeyInput"}
	if s.ApiKey == nil {
		invalidParams.Add(request.NewErrParamRequired("ApiKey"))
	}
	if s.ApiKey != nil && len(*s.ApiKey) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("ApiKey", 1))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

func (s *messageStoreImpl) CheckValid(message interface{}) bool {
	s.lock.RLock()
	defer s.lock.RUnlock()

	for _, m := range s.messages {
		if s.pol(message, m.data) == common.MessageInvalidated {
			return false
		}
	}
	return true
}

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


Question: // NewFakeClusterLister returns a new FakeClusterLister

func NewFakeClusterLister(resp *containerservice.ListResult, err error) *FakeClusterLister {
	return &FakeClusterLister{
		Resp: resp,
		Err:  err,
	}
}

func (c *Cluster) Query(ctx context.Context, q Query) (cursor *Cursor, err error) {
	for i := 0; i < c.numRetries(); i++ {
		var node *Node
		var hpr hostpool.HostPoolResponse

		node, hpr, err = c.GetNextNode()
		if err != nil {
			return nil, err
		}

		cursor, err = node.Query(ctx, q)
		hpr.Mark(err)

		if !shouldRetryQuery(q, err) {
			break
		}
	}

	return cursor, err
}

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


Question: Sponsor(s) of the conference the abstract belongs to.

def confsponsor(self):
        """"""
        sponsors = chained_get(self._confevent, ['confsponsors', 'confsponsor'], [])
        if len(sponsors) == 0:
            return None
        if isinstance(sponsors, list):
            return [s['$'] for s in sponsors]
        return sponsors

def extract(text, default=UNKNOWN):
        """"""
        if not text:
            return default
        found = CALLING_CONVENTION_TYPES.pattern.match(text)
        if found:
            return found.group('cc')

        return default

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


Question:
Destroy the volume

    name
        Name of the volume

    profile
        Profile to build on

    CLI Example:

    .. code-block:: bash

        salt '*' nova.volume_delete myblock profile=openstack

def volume_delete(name, profile=None, **kwargs):
    '''

    '''
    conn = _auth(profile, **kwargs)
    return conn.volume_delete(name)

def cancel(context, jobs, analysis_id):
    """"""
    analysis_obj = context.obj['store'].analysis(analysis_id)
    if analysis_obj is None:
        click.echo('analysis not found')
        context.abort()
    elif analysis_obj.status != 'running':
        click.echo(f"analysis not running: {analysis_obj.status}")
        context.abort()

    config_path = Path(analysis_obj.config_path)
    with config_path.open() as config_stream:
        config_raw = ruamel.yaml.safe_load(config_stream)
    config_data = parse_config(config_raw)

    log_path = Path(f"{config_data['log_path']}")
    if not log_path.exists():
        click.echo(f"missing MIP log file: {log_path}")
        context.abort()

    with log_path.open() as log_stream:
        all_jobs = job_ids(log_stream)

    if jobs:
        for job_id in all_jobs:
            click.echo(job_id)
    else:
        for job_id in all_jobs:
            LOG.debug(f"cancelling job: {job_id}")
            process = subprocess.Popen(['scancel', job_id])
            process.wait()

        analysis_obj.status = 'canceled'
        context.obj['store'].commit()
        click.echo('cancelled analysis successfully!')

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


Question:
Populate id.

@param entityMetadata
the entity metadata
@param schemaTable
the schema table
@param entity
the entity
@param row
the row

private void populateId(EntityMetadata entityMetadata, Table schemaTable, Object entity, Row row)
    {
        FieldDef fieldMetadata;
        FieldValue value;
        String idColumnName = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();

        fieldMetadata = schemaTable.getField(idColumnName);

        value = row.get(idColumnName);

        NoSqlDBUtils.get(fieldMetadata, value, entity, (Field) entityMetadata.getIdAttribute().getJavaMember());
    }

protected function buildInsertQuery(SQLInsert $query, array &$parameters)
    {
        $nl = $this->getSeparator();
        $into = $query->getInto();

        // Column identifiers
        $columns = $query->getColumns();
        $sql = "INSERT INTO {$into}{$nl}(" . implode(', ', $columns) . ")";

        // Values
        $sql .= "{$nl}VALUES";

        // Build all rows
        $rowParts = array();
        foreach ($query->getRows() as $row) {
            // Build all columns in this row
            $assignments = $row->getAssignments();
            // Join SET components together, considering parameters
            $parts = array();
            foreach ($columns as $column) {
                // Check if this column has a value for this row
                if (isset($assignments[$column])) {
                    // Assigment is a single item array, expand with a loop here
                    foreach ($assignments[$column] as $assignmentSQL => $assignmentParameters) {
                        $parts[] = $assignmentSQL;
                        $parameters = array_merge($parameters, $assignmentParameters);
                        break;
                    }
                } else {
                    // This row is missing a value for a column used by another row
                    $parts[] = '?';
                    $parameters[] = null;
                }
            }
            $rowParts[] = '(' . implode(', ', $parts) . ')';
        }
        $sql .= $nl . implode(",$nl", $rowParts);

        return $sql;
    }

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


Question:
Defines the value of the receiver.

@param mixed $value
@param array|DataObject $data

@return $this

public function setValue($value, $data = null)
    {
        // Check Provided Value:

        if ($value && $this->isValidValue($value)) {
            return parent::setValue($value, $data);
        }

        // Default to Locale (if enabled):

        if ($this->config()->default_to_locale) {

            if (($code = $this->getCountryFromLocale()) && $this->isValidValue($code)) {
                return parent::setValue($code, $data);
            }

        }

        // Default to Country (if defined):

        if (($code = strtolower($this->config()->default_country)) && $this->isValidValue($code)) {
            return parent::setValue($code, $data);
        }

        // Answer Self:

        return $this;
    }

public void marshall(GetDataSourceRequest getDataSourceRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(getDataSourceRequest.getApiId(), APIID_BINDING);
            protocolMarshaller.marshall(getDataSourceRequest.getName(), NAME_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: to get value at specific path in a json

function(json, path) {
            var i = 0,

                ln = path.length;

            if (json === null) {
                return null;
            }
            while (i < ln) {
                if (json[path[i]] === null) {
                    json = null;
                    return;
                } else {
                    json = json[path[i]];
                }
                i = i + 1;
            }
            return json;
        }

function(depth, parts, strict) {
    if (!depth) {
      this.pushStackLiteral('data');
    } else {
      this.pushStackLiteral('container.data(data, ' + depth + ')');
    }

    this.resolvePath('data', parts, 0, true, strict);
  }

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


Question:
// The xxxInterface routines build up a value to be stored
// in an empty interface. They are not strictly necessary,
// but they avoid the weight of reflection in this common case.
// valueInterface is like value but returns interface{}

func (d *decodeState) valueInterface(data Slice) interface{} {
	switch data.Type() {
	case Array:
		return d.arrayInterface(data)
	case Object:
		return d.objectInterface(data)
	default:
		return d.literalInterface(data)
	}
}

private void storeEntityInformation(List<Chain> allChains, List<EntityInfo> entityInfos) {
		for (EntityInfo entityInfo : entityInfos) {
			String description = entityInfo.getDescription();
			String type;
			if (entityInfo.getType()==null){
				type = null;
			}
			else{
				type = entityInfo.getType().getEntityType();
			}
			List<Chain> entityChains = entityInfo.getChains();
			if (entityChains.isEmpty()){
				// Error mapping chain to entity
				System.err.println("ERROR MAPPING CHAIN TO ENTITY: "+description);
				mmtfDecoderInterface.setEntityInfo(new int[0], "", description, type);
				continue;
			}
			else{
				int[] chainIndices = new int[entityChains.size()];
				for (int i=0; i<entityChains.size(); i++) {
					chainIndices[i] = allChains.indexOf(entityChains.get(i));
				}
				Chain chain = entityChains.get(0);
				ChainImpl chainImpl;
				if (chain instanceof ChainImpl){
					chainImpl = (ChainImpl) entityChains.get(0);
				}
				else{
					throw new RuntimeException();
				}
				String sequence = chainImpl.getSeqResOneLetterSeq();
				mmtfDecoderInterface.setEntityInfo(chainIndices, sequence, description, type);
			}
		}
	}

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


Question:
Send query to identify if server is master.

@throws IOException in case of socket error.

private void sendPipelineCheckMaster() throws IOException {
    if (urlParser.getHaMode() == HaMode.AURORA) {
      writer.startPacket(0);
      writer.write(COM_QUERY);
      writer.write(IS_MASTER_QUERY);
      writer.flush();
    }
  }

public boolean canTryToConnect(int retryAfterSecend) {
        // 如果是有效连接
        if (this.available) {
            return true;
            // 如果连接无效，并且达到重试时间
        } else if ((System.currentTimeMillis() - lastUnavailableTime) > retryAfterSecend * 1000) {
            return true;
        }
        return false;
    }

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


Question:
Initialize the DR producer so that any binary log generated on recover
will be queued. This does NOT open the DR port. That will happen after
command log replay finishes.

private void initializeDRProducer() {
        try {
            if (m_producerDRGateway != null) {
                m_producerDRGateway.startAndWaitForGlobalAgreement();

                for (Initiator iv2init : m_iv2Initiators.values()) {
                    iv2init.initDRGateway(m_config.m_startAction,
                                          m_producerDRGateway,
                                          isLowestSiteId(iv2init));
                }

                m_producerDRGateway.completeInitialization();
            }
        } catch (Exception ex) {
            CoreUtils.printPortsInUse(hostLog);
            VoltDB.crashLocalVoltDB("Failed to initialize DR producer", false, ex);
        }
    }

def fromsra(args):

    p = OptionParser(fromsra.__doc__)
    p.add_option("--paired", default=False, action="store_true",
            help="Specify if library layout is paired-end " + \
                 "[default: %default]")
    p.add_option("--compress", default=None, choices=["gzip", "bzip2"],
            help="Compress output fastq files [default: %default]")
    p.set_outdir()
    p.set_grid()
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    srafile, = args
    paired = opts.paired
    compress = opts.compress
    outdir = opts.outdir

    script_path = which("fastq-dump")
    if not script_path:
        logging.error("Cannot find `fastq-dump` in the PATH")
        sys.exit()

    cmd = [script_path]
    if compress:
        cmd.append("--{0}".format(compress))
    if paired:
        cmd.append("--split-files")
    if outdir:
        cmd.append("--outdir {0}".format(outdir))
    cmd.append(srafile)

    outcmd = " ".join(cmd)
    sh(outcmd, grid=opts.grid)

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


Question:
Sprawdza posiadanie renderowanych atrybutów
@return boolean

private function _hasPrintableAttributes()
    {
        //iteracja po atrybutach
        foreach ($this->_cmsAttributes as $attribute) {
            //nie jest atrybutem odziedziczonym - czyli będzie wypisany przy renderingu
            if (!$attribute->getJoined('cms_attribute_relation')->isMaterializedInherited()) {
                return true;
            }
        }
        return false;
    }

async def prover_close_credentials_search(search_handle: int) -> None:

    logger = logging.getLogger(__name__)
    logger.debug("prover_close_credentials_search: >>> search_handle: %r",
                 search_handle)

    if not hasattr(prover_close_credentials_search, "cb"):
        logger.debug("prover_close_credentials_search: Creating callback")
        prover_close_credentials_search.cb = create_cb(CFUNCTYPE(None, c_int32, c_int32))

    c_search_handle = c_int32(search_handle)

    res = await do_call('indy_prover_close_credentials_search',
                        c_search_handle,
                        prover_close_credentials_search.cb)

    logger.debug("prover_close_credentials_search: <<< res: %r", res)
    return res

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


Question:
Unpack a binary message into this object's attributes.

        Pass the correct length for list unpacking.

        Args:
            buff (bytes): Binary data package to be unpacked.
            offset (int): Where to begin unpacking.

def unpack(self, buff, offset=0):

        unpack_length = UBInt16()
        unpack_length.unpack(buff, offset)
        super().unpack(buff[:offset+unpack_length], offset)

def _add_tag_files(
    zip_file, dir_name, payload_info_list, payload_byte_count, payload_file_count
):
    """"""
    tag_info_list = []
    _add_tag_file(zip_file, dir_name, tag_info_list, _gen_bagit_text_file_tup())
    _add_tag_file(
        zip_file,
        dir_name,
        tag_info_list,
        _gen_bag_info_file_tup(payload_byte_count, payload_file_count),
    )
    _add_tag_file(
        zip_file, dir_name, tag_info_list, _gen_pid_mapping_file_tup(payload_info_list)
    )
    return tag_info_list

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


Question:
Takes a PDF (e.g. A4) and makes a 2x1 booklet (e.g. 2xA5 per A4).
    The booklet can be folded like a book and the final pages will be in order.
    Returns the output filename.

def booklet_nup_pdf(input_filename: str, output_filename: str,
                    latex_paper_size: str = LATEX_PAPER_SIZE_A4) -> str:

    log.info("Creating booklet")
    log.debug("... {!r} -> {!r}", input_filename, output_filename)
    require(PDFJAM, HELP_MISSING_PDFJAM)
    n_pages = get_page_count(input_filename)
    n_sheets = calc_n_sheets(n_pages)
    log.debug("{} pages => {} sheets", n_pages, n_sheets)
    pagenums = page_sequence(n_sheets, one_based=True)
    pagespeclist = [str(p) if p <= n_pages else "{}"
                    for p in pagenums]
    # ... switches empty pages to "{}", which is pdfjam notation for
    # an empty page.
    pagespec = ",".join(pagespeclist)
    pdfjam_tidy = True  # clean up after yourself?
    args = [
        PDFJAM,
        "--paper", latex_paper_size,
        "--landscape",
        "--nup", "2x1",
        "--keepinfo",  # e.g. author information
        "--outfile", output_filename,
        "--tidy" if pdfjam_tidy else "--no-tidy",
        "--",  # "no more options"
        input_filename, pagespec
    ]
    run(args)
    return output_filename

def package_contents(self):
        ''

        if self.contents_cache:
            return self.contents_cache

        # Get a list of ZipInfo objects.
        files = self.zf.infolist()
        out_files = {}

        # Iterate through each file in the XPI.
        for file_ in files:

            file_doc = {'name': file_.filename,
                        'size': file_.file_size,
                        'name_lower': file_.filename.lower()}

            file_doc['extension'] = file_doc['name_lower'].split('.')[-1]

            out_files[file_.filename] = file_doc

        self.contents_cache = out_files
        return out_files

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


Question: // createRecord creates a record given an associated zone and a godo.DomainRecordEditRequest

func createRecord(c *godo.Client, zoneName string, createRequest *godo.DomainRecordEditRequest) error {
	_, _, err := c.Domains.CreateRecord(context.TODO(), zoneName, createRequest)
	if err != nil {
		return fmt.Errorf("error creating record: %v", err)
	}

	return nil
}

public function run() {
    $values = $this->formValues;

    try {
      $creative = $this->service->creatives->get($values['account_id'],
          $values['buyer_creative_id'], $values['ad_group_id']);
      print '
Found creative
';
      $this->printResult($creative);
    } catch (Google_Exception $ex) {
      if ($ex->getCode() == 404 || $ex->getCode() == 403) {
        print '
Creative not found or can\'t access creative
';
      } else {
        throw $ex;
      }
    }
  }

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


Question: Load shared celery tasks.

def celery_module_imports(sender, signal=None, **kwargs):
    """"""
    app = getattr(sender, 'flask_app', None)
    if app:
        app.extensions['invenio-celery'].load_entry_points()

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:
Remove a basepath from the URI path.

@return Psr7UriInterface|UriInterface

public static function removeBasepath($uri, $path)
    {
        $uri = self::normalizePath(self::filterUri($uri));
        $basepath = (new HierarchicalPath($path))->withLeadingSlash();
        if ('/' === (string) $basepath) {
            return $uri;
        }

        $currentpath = $uri->getPath();
        if (0 !== strpos($currentpath, (string) $basepath)) {
            return $uri;
        }

        return $uri->withPath(
            (string) (new HierarchicalPath($currentpath))->withoutSegment(...range(0, count($basepath) - 1))
        );
    }

func (c *Context) SetServiceBaseURL(domainOrURL string) {
	u, _ := getBaseURL(domainOrURL)

	if u != nil && u.Host != "" {
		c.ServiceBaseURL = *u
	} else if domainOrURL != "" {
		c.ServiceBaseURL = url.URL{Scheme: "https", Host: domainOrURL}
	} else {
		c.Log().Error("Can't use SetServiceHostFromURL with empty arg")
	}
}

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


Question: stream|string -> create data file

def retrieve_save(data)
      File.open(location, 'w') do |f|
        f << (data.respond_to?(:read) ? data.read : data)
      end
    end

def __write_noaas(dat, path):

    for filename, text in dat.items():
        try:
            with open(os.path.join(path, filename), "w+") as f:
                f.write(text)
        except Exception as e:
            print("write_noaas: There was a problem writing the NOAA text file: {}: {}".format(filename, e))
    return

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


Question:
Function mpsRedirect

@author: 713uk13m <dev@nguyenanhung.com>
@time  : 2018-12-05 10:30

@param array $data
@param bool  $resultIsUrl

@return array|null

public function mpsRedirect($data = [], $resultIsUrl = FALSE)
    {
        try {
            $this->debug->info(__FUNCTION__, 'Input Params: ' . json_encode($data));
            $movitelMps = new MovitelMps\MovitelMps($this->options);
            $movitelMps->setMovitelPublicKey($this->movitelPublicKey);
            $movitelMps->setMovitelPrivateKey($this->movitelPrivateKey);
            $movitelMps->setCpPublicKey($this->cpPublicKey);
            $movitelMps->setCpPrivateKey($this->cpPrivateKey);
            $dataToRequest = "SUB=" . $data['sub'] . "&REQ=" . $data['req'] . "&SOURCE=" . $data['source'] . "&SESS=" . $data['session_id'];
            $dataLink      = "PRO=" . $data['provider'] . "&CMD=" . $data['cmd_msisdn'] . "&SER=" . $data['service'] . "&SUB=" . $data['sub'] . "&DATA=";
            $this->debug->info(__FUNCTION__, '$dataToRequest: ' . json_encode($dataToRequest));
            $this->debug->info(__FUNCTION__, '$dataLink: ' . json_encode($dataLink));
            $dataRequest = $movitelMps->createDataRequestToMps($data, $dataToRequest);
            $this->debug->info(__FUNCTION__, '$dataRequest: ' . json_encode($dataRequest));
            if ($dataRequest !== NULL && is_array($dataRequest)) {
                $dataEncrypted = $dataRequest[0];
                $dataSignature = $dataRequest[1];
                // Link
                $movitelRedirectUrl = $data['link'] . self::MSISDN_METHOD . '?' . $dataLink . urlencode($dataEncrypted) . '&SIG=' . $dataSignature;
                $this->debug->info(__FUNCTION__, '$movitelRedirectUrl: ' . json_encode($movitelRedirectUrl));
                if ($resultIsUrl === TRUE) {
                    $this->debug->info(__FUNCTION__, 'Result is URL');

                    return [
                        'status' => 'url',
                        'link'   => $movitelRedirectUrl
                    ];
                } else {
                    $this->debug->info(__FUNCTION__, 'Result is Redirect');
                    // Redirect url
                    Utils::redirect($movitelRedirectUrl);
                }
            }
            $this->debug->info(__FUNCTION__, 'Invalid Redirect URL');
        }
        catch (\Exception $e) {
            $message = 'Error File: ' . $e->getFile() . ' - Line: ' . $e->getLine() . ' - Code: ' . $e->getCode() . ' - Message: ' . $e->getMessage();
            $this->debug->error(__FUNCTION__, $message);

            return NULL;
        }

        return NULL;
    }

protected function info($args) {
		$files = array();

		foreach ($args['targets'] as $hash) {
			if (($volume = $this->volume($hash)) != false
			&& ($info = $volume->file($hash)) != false) {
				$files[] = $info;
			}
		}

		return array('files' => $files);
	}

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


Question:
Export an entire dataset (effectively, one of the superglobals) from the request arguments list

@param int $ParamType Type of data to export. One of the self::INPUT_* constants
@return array

public function GetRequestArguments($ParamType = NULL) {
      if ($ParamType === NULL)
         return $this->_RequestArguments;
      elseif (!isset($this->_RequestArguments[$ParamType]))
         return array();
      else
         return $this->_RequestArguments[$ParamType];
   }

public static function createFromDataModel(VariableDeclaration $variableDeclaration)
    {
        $variable = parent::createFromDataModel($variableDeclaration);

        if ($variableDeclaration instanceof TemplateDeclaration) {

            $variable->setParamVariable($variableDeclaration->isParamVariable());
            $variable->setMathVariable($variableDeclaration->isMathVariable());

            return $variable;
        } else {
            $msg = "TemplateVariable::createFromDataModel only accept 'qtism\\data\\state\\TemplateVariable' objects, '" . get_class($variableDeclaration) . "' given.";
            throw new InvalidArgumentException($msg);
        }
    }

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


Question:
Returns short name of the received entity or class name.

@param string|object $entity Entity object or just entity name in the full or shot notation

@return string For example 'AcmeBundle:User'

public function getEntityClassShort($entity)
    {
        $cacheKey = 'short';
        $entity   = $this->getEntityClassFull($entity);
        $short    = $this->getFromCache($entity, $cacheKey);

        if (false !== $short) {
            return $short;
        }

        foreach ($this->entityManager->getConfiguration()->getEntityNamespaces() as $short => $full) {
            if (false === strpos($entity, $full)) {
                continue;
            }

            $short .= ':'.ltrim(str_replace($full, '', $entity), '\\');
            $this->cache[$full][$cacheKey] = $short;

            return $short;
        }

        return $entity;
    }

public function build(ResultSpec $result): string
    {
        $response = [];
        $units = $result->getResults();

        foreach ($units as $unit) {
            /** @var AbstractResult $unit */
            if ($unit instanceof Result) {
                /** @var Result $unit */
                $response[] = [
                    'jsonrpc' => '2.0',
                    'result' => $this->preBuild($unit->getResult()),
                    'id'     => $unit->getId()
                ];
            } elseif ($unit instanceof Error) {
                /** @var Error $unit */
                $baseException = $unit->getBaseException();
                $response[] = [
                    'jsonrpc' => '2.0',
                    'error' => [
                        'code'    => $baseException->getJsonRpcCode(),
                        'message' => $this->getErrorMessage($baseException->getJsonRpcCode()),
                        'data'    => $baseException->getJsonRpcData()
                    ],
                    'id' => $unit->getId()
                ];
            }
        }

        if (empty($response)) {
            return '';
        }

        if ($result->isSingleResult()) {
            return json_encode($response[0]);
        }

        return json_encode($response);
    }

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


Question:
Override $configuration parameters with $override.

Only first level keys in main configuration and separately under 'parameters' key are replaced.

@param array $configuration
@param array $override

@return array

private function overrideConfiguration(array $configuration, array $override)
    {
        $configuration['parameters'] = array_replace(
            $configuration['parameters'],
            $override['parameters']
        );

        unset($override['parameters']);

        return array_replace($configuration, $override);
    }

static public function config($config = array())
    {
        !empty($config) && self::$config = array_merge(self::$config, $config);
        if (!empty(self::$config['cachepath'])) {
            Cache::$cachepath = self::$config['cachepath'];
        }
        if (empty(self::$config['component_verify_ticket'])) {
            self::$config['component_verify_ticket'] = Cache::get('component_verify_ticket');
        }
        if (empty(self::$config['token']) && !empty(self::$config['component_token'])) {
            self::$config['token'] = self::$config['component_token'];
        }
        if (empty(self::$config['appsecret']) && !empty(self::$config['component_appsecret'])) {
            self::$config['appsecret'] = self::$config['component_appsecret'];
        }
        if (empty(self::$config['encodingaeskey']) && !empty(self::$config['component_encodingaeskey'])) {
            self::$config['encodingaeskey'] = self::$config['component_encodingaeskey'];
        }
        return self::$config;
    }

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


Question: Parse an iterator of str (one string per line) to the intermediary syntax

def line_iterator_to_intermediary(line_iterator):

    current_table = None
    tables = []
    relations = []
    errors = []
    for line_nb, line, raw_line in filter_lines_from_comments(line_iterator):
        try:
            new_obj = parse_line(line)
            current_table, tables, relations = update_models(new_obj, current_table, tables, relations)
        except ParsingException as e:
            e.line_nb = line_nb
            e.line = raw_line
            errors.append(e)
    if len(errors) != 0:
        msg = 'ERAlchemy couldn\'t complete the generation due the {} following errors'.format(len(errors))
        raise ParsingException(msg + '\n\n'.join(e.traceback for e in errors))
    return tables, relations

def links(self):
        """"""
        # <https://example.com/?page=2>; rel="next", <https://example.com/?page=34>; rel="last"'
        # becomes
        # {
        #     'last': {'rel': 'last', 'url': 'https://example.com/?page=34'},
        #     'next': {'rel': 'next', 'url': 'https://example.com/?page=2'},
        # },
        result = {}
        if 'Link' in self.headers:
            value = self.headers['Link']

            for part in re.split(r', *<', value):
                link = {}
                vs = part.split(';')

                # First section is always an url.
                link['url'] = vs.pop(0).strip('\'" <>')

                for v in vs:
                    if '=' in v:
                        key, v = v.split('=')
                        link[key.strip('\'" ')] = v.strip('\'" ')

                rkey = link.get('rel') or link['url']
                result[rkey] = link

        return result

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


Question: // Destroy the disaster recovery task, detaching and forgetting any SRs introduced which are no longer required

func (_class DRTaskClass) Destroy(sessionID SessionRef, self DRTaskRef) (_err error) {
	_method := "DR_task.destroy"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertDRTaskRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_, _err =  _class.client.APICall(_method, _sessionIDArg, _selfArg)
	return
}

def _disconnect(self):
        """"""
        for cluster in self._clusters:
            if 'connection' in cluster:
                connection = cluster.pop('connection')
                connection.close()
        # Remove all attributes that are database names so that next time
        # when they are accessed, __getattr__ will be called and will create
        # new Clients
        for dbname in self._mapped_databases:
            self.__delattr__(dbname)
        self._mapped_databases = []

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


Question: constructor cannot be arrow function

function (url, options) {
    // 首先建立连接
    options = options || {};
    options.autoReconnect = true;

    const { timestamp = true, updatedTime, createdTime } = options;

    const extendUpdate = timestamp ? extend.update(updatedTime) : extend.no();
    const extendCreate = timestamp ? extend.create(createdTime) : extend.no();

    const connect = mongo.connect(url, options);

    this.collections = () => {
      return connect.then((db) => {
        return db.collections();
      });
    };
    this.collection = (collectionName) => {
      return connect.then((db) => {
        return db.collection(collectionName);
      });
    };
    this.count = (collectionName, query, options) => {
      return this.collection(collectionName).then((collection) => {
        return collection.count(query, options);
      });
    };
    this.create = this.insert = (collectionName, data) => {
      return this.collection(collectionName).then((collection) => {
        return collection.insert(extendCreate(data));
      });
    };
    this.find = (collectionName, filter, condition, cursor) => {
      return this.collection(collectionName).then((collection) => {
        if (!cursor) {
          return collection.find(filter, condition).toArray();
        } else {
          return collection.find(filter, condition);
        }
      });
    };
    this.findOne = (collectionName, filter, condition) => {
      return this.collection(collectionName).then((collection) => {
        return collection.findOne(filter, condition);
      });
    };
    this.update = (collectionName, filter, data, options) => {
      return this.collection(collectionName).then((collection) => {
        return collection.update(filter, extendUpdate(data), Object.assign({}, { upsert: false }, options));
      });
    };
    this.updateOne = (collectionName, filter, data, options) => {
      return this.collection(collectionName).then((collection) => {
        return collection.updateOne(filter, extendUpdate(data), Object.assign({}, { upsert: true }, options));
      });
    };
    this.remove = (collectionName, filter, options) => {
      return this.collection(collectionName).then((collection) => {
        return collection.deleteMany(filter, options);
      });
    };
    this.aggregate = (collectionName, pipeline, options) => {
      return this.collection(collectionName).then((collection) => {
        return new Promise((rec, rej) => {
          collection.aggregate(pipeline, (err, res) => {
            if (err) {
              rej(err);
            } else {
              rec(res);
            }
          });
        });
      });
    };
    return this;
  }

func (kok *kok_IN) WeekdayNarrow(weekday time.Weekday) string {
	return kok.daysNarrow[weekday]
}

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


Question:
Send queries to default connection and all shards in this cluster
 @param [Boolean] continue_on_error when a shard raises error, ignore exception and continue

def with_default_and_all(continue_on_error = false)
      ([default_shard] + cluster.shards).map do |shard|
        begin
          with_shard(shard) {
            yield
          }
        rescue Exception => err
          unless continue_on_error
            raise err
          end
          err
        end
      end
    end

async def consume_events(self):
        ''' '''
        # begin by making sure the channel is created
        await self.create_channel()
        # get cursor method
        def create_cursor():
            now = datetime.datetime.utcnow()
            dummy_id = ObjectId.from_datetime(now)
            return self._collection.find({'_id': {'$gte': dummy_id}}, cursor_type=CursorType.TAILABLE_AWAIT)
        # get cursor and start the loop
        cursor = create_cursor()
        while self.active:
            if cursor.alive:
                if (await cursor.fetch_next):
                    message = cursor.next_object()
                    event = message['key']
                    data = message['data']
                    logger.debug('event: %s - %s', event, data)
                    for sub in self._subscribers[event]:
                        await sub.deliver({'type': 'event', 'payload': {'name': event, 'data': data}})
            else:
                await asyncio.sleep(0.1)
                cursor = create_cursor()

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


Question: // getEndpoints returns a list of <endpoint ip>:<port> for a given service/target port combination.

func (lbc *loadBalancerController) getEndpoints(
	s *api.Service, servicePort *api.ServicePort) (endpoints []string) {
	ep, err := lbc.epLister.GetServiceEndpoints(s)
	if err != nil {
		return
	}

	// The intent here is to create a union of all subsets that match a targetPort.
	// We know the endpoint already matches the service, so all pod ips that have
	// the target port are capable of service traffic for it.
	for _, ss := range ep.Subsets {
		for _, epPort := range ss.Ports {
			var targetPort int
			switch servicePort.TargetPort.Type {
			case intstr.Int:
				if epPort.Port == getTargetPort(servicePort) {
					targetPort = epPort.Port
				}
			case intstr.String:
				if epPort.Name == servicePort.TargetPort.StrVal {
					targetPort = epPort.Port
				}
			}
			if targetPort == 0 {
				continue
			}
			for _, epAddress := range ss.Addresses {
				endpoints = append(endpoints, fmt.Sprintf("%v:%v", epAddress.IP, targetPort))
			}
		}
	}
	return
}

public java.lang.String getServerIp() {
    java.lang.Object ref = serverIp_;
    if (ref instanceof java.lang.String) {
      return (java.lang.String) ref;
    } else {
      com.google.protobuf.ByteString bs =
          (com.google.protobuf.ByteString) ref;
      java.lang.String s = bs.toStringUtf8();
      serverIp_ = s;
      return s;
    }
  }

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


Question:
Unlock all messages which have been locked to this LCP but not consumed

@throws SIResourceException Thrown if there is a problem in the msgStore

@Override
    public void unlockAll() throws SISessionUnavailableException, SIResourceException
    {
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.entry(tc, "unlockAll", this);

        synchronized (_asynchConsumerBusyLock)
        {
            this.lock();
            try
            {
                // Only valid if the consumer session is still open
                checkNotClosed();

                try
                {
                    // Unlock the messages (take this lock to ensure we don't have a problem
                    // getting it if we need it to re-deliver the unlocked messages to ourselves)
                    _allLockedMessages.unlockAll();
                } catch (SIMPMessageNotLockedException e)
                {
                    // No FFDC code needed
                    // This exception has occurred beause someone has deleted the
                    // message(s). Ignore this exception as it is unlocked anyway
                }
            } finally
            {
                this.unlock();
            }
        }

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
            SibTr.exit(tc, "unlockAll");
    }

protected Locale ensureLocale(Locale locale) {

        // get the default locale for the resource
        List<Locale> locales = OpenCms.getLocaleManager().getDefaultLocales(getCms(), getParamResource());
        if (m_content != null) {
            if (!m_content.hasLocale(locale)) {
                try {

                    // to copy anything we need at least one locale
                    if ((m_content.getLocales().size() > 0)) {
                        // required locale not available, check if an existing default locale should be copied as "template"
                        try {
                            // a list of possible default locales has been set as property, try to find a match
                            m_content.copyLocale(locales, locale);

                        } catch (CmsException e) {
                            m_content.addLocale(getCms(), locale);
                        }

                    } else {
                        m_content.addLocale(getCms(), locale);
                    }

                    writeContent();
                } catch (CmsException e) {
                    LOG.error(e.getMessageContainer(), e);
                }
            }
            if (!m_content.hasLocale(locale)) {
                // value may have changed because of the copy operation
                locale = m_content.getLocales().get(0);
            }
        }
        return locale;
    }

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


Question: Key-value query url builder (of the form: "base/v0/k1=v1/k2=v2").

def kvpath(self, base, *pa, **kw):

        def fmt(vtuple):
            typ, val = vtuple
            if not val is None:
                return safeformat("{:%s}"%typ, val)
            return None
        parts = [base]
        for v in pa:
            fv = fmt(v)
            if not fv is None:
                parts.append(quote(fv))
        for k,v in kw.items():
            fv = fmt(v)
            if not fv is None:
                parts.append(quote(k+"="+fv))
        return "/".join(parts)

public String serviceName_quota_PUT(String serviceName, Long quota) throws IOException {
		String qPath = "/metrics/{serviceName}/quota";
		StringBuilder sb = path(qPath, serviceName);
		HashMap<String, Object>o = new HashMap<String, Object>();
		addBody(o, "quota", quota);
		String resp = exec(qPath, "PUT", sb.toString(), o);
		return convertTo(resp, String.class);
	}

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


Question:
Quick wrapper for using the Watcher.

    :param logger_name: name of logger to watch
    :param level: minimum log level to show (default INFO)
    :param out: where to send output (default stdout)
    :return: Watcher instance

def watch(logger_name, level=DEBUG, out=stdout):

    watcher = Watcher(logger_name)
    watcher.watch(level, out)
    return watcher

def show_raslog_output_show_all_raslog_raslog_entries_severity(self, **kwargs):

        config = ET.Element("config")
        show_raslog = ET.Element("show_raslog")
        config = show_raslog
        output = ET.SubElement(show_raslog, "output")
        show_all_raslog = ET.SubElement(output, "show-all-raslog")
        raslog_entries = ET.SubElement(show_all_raslog, "raslog-entries")
        severity = ET.SubElement(raslog_entries, "severity")
        severity.text = kwargs.pop('severity')

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

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


Question:
Find the filesystem path of the FindBugs plugin directory.

@return the filesystem path of the FindBugs plugin directory, or null if
the FindBugs plugin directory cannot be found

public static String getFindBugsEnginePluginLocation() {
        // findbugs.home should be set to the directory the plugin is
        // installed in.
        URL u = plugin.getBundle().getEntry("/");
        try {
            URL bundleRoot = FileLocator.resolve(u);
            String path = bundleRoot.getPath();
            if (FindBugsBuilder.DEBUG) {
                System.out.println("Pluginpath: " + path); //$NON-NLS-1$
            }
            if (path.endsWith("/eclipsePlugin/")) {
                File f = new File(path);
                f = f.getParentFile();
                f = new File(f, "findbugs");
                path = f.getPath() + "/";
            }

            return path;
        } catch (IOException e) {
            FindbugsPlugin.getDefault().logException(e, "IO Exception locating engine plugin");
        }
        return null;
    }

func playerProgramFilePaths() []string {
	path, err := playerVMwareRoot()
	if err != nil {
		log.Printf("Error finding VMware root: %s", err)
	}

	paths := make([]string, 0, 5)
	if os.Getenv("VMWARE_HOME") != "" {
		paths = append(paths, os.Getenv("VMWARE_HOME"))
	}

	if path != "" {
		paths = append(paths, path)
	}

	if os.Getenv("ProgramFiles(x86)") != "" {
		paths = append(paths,
			filepath.Join(os.Getenv("ProgramFiles(x86)"), "/VMware/VMware Player"))
	}

	if os.Getenv("ProgramFiles") != "" {
		paths = append(paths,
			filepath.Join(os.Getenv("ProgramFiles"), "/VMware/VMware Player"))
	}

	if os.Getenv("QEMU_HOME") != "" {
		paths = append(paths, os.Getenv("QEMU_HOME"))
	}

	if os.Getenv("ProgramFiles(x86)") != "" {
		paths = append(paths,
			filepath.Join(os.Getenv("ProgramFiles(x86)"), "/QEMU"))
	}

	if os.Getenv("ProgramFiles") != "" {
		paths = append(paths,
			filepath.Join(os.Getenv("ProgramFiles"), "/QEMU"))
	}

	if os.Getenv("SystemDrive") != "" {
		paths = append(paths,
			filepath.Join(os.Getenv("SystemDrive"), "/QEMU"))
	}

	return paths
}

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


Question:
Remove an observer to a valid signal.

        Parameters
        ----------
        signal : str
            a valid signal.
        observer : @func
            an obervation function to be removed.

def _remove_observer(self, signal, observer):

        if observer in self._observers[signal]:
            self._observers[signal].remove(observer)

func (ac *AuthorizationCache) syncRequest(request *reviewRequest, userSubjectRecordStore cache.Store, groupSubjectRecordStore cache.Store, reviewRecordStore cache.Store) error {

	lastKnownValue, err := lastKnown(reviewRecordStore, request.namespace)
	if err != nil {
		return err
	}

	if skipReview(request, lastKnownValue) {
		return nil
	}

	namespace := request.namespace
	review, err := ac.reviewer.Review(namespace)
	if err != nil {
		return err
	}

	usersToRemove := sets.NewString()
	groupsToRemove := sets.NewString()
	if lastKnownValue != nil {
		usersToRemove.Insert(lastKnownValue.users...)
		usersToRemove.Delete(review.Users()...)
		groupsToRemove.Insert(lastKnownValue.groups...)
		groupsToRemove.Delete(review.Groups()...)
	}

	deleteNamespaceFromSubjects(userSubjectRecordStore, usersToRemove.List(), namespace)
	deleteNamespaceFromSubjects(groupSubjectRecordStore, groupsToRemove.List(), namespace)
	addSubjectsToNamespace(userSubjectRecordStore, review.Users(), namespace)
	addSubjectsToNamespace(groupSubjectRecordStore, review.Groups(), namespace)
	cacheReviewRecord(request, lastKnownValue, review, reviewRecordStore)
	ac.notifyWatchers(namespace, lastKnownValue, sets.NewString(review.Users()...), sets.NewString(review.Groups()...))

	if errMsg := review.EvaluationError(); len(errMsg) > 0 {
		klog.V(5).Info(errMsg)
	}
	return nil
}

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


Question:
Set the output level based on the parameters.

This reconfigures both the output level for out()
and the configured stdout/stderr logging

@return void

protected function _setOutputLevel()
    {
        $this->_io->setLoggers(ConsoleIo::NORMAL);
        if (!empty($this->params['quiet'])) {
            $this->_io->level(ConsoleIo::QUIET);
            $this->_io->setLoggers(ConsoleIo::QUIET);
        }
        if (!empty($this->params['verbose'])) {
            $this->_io->level(ConsoleIo::VERBOSE);
            $this->_io->setLoggers(ConsoleIo::VERBOSE);
        }
    }

def conditions(self, start, last_attempt):

        if time.time() - start > self.timeout:
            yield WaitCondition.Timedout
            return

        if last_attempt is not None and time.time() - last_attempt < self.wait_between_attempts:
            yield WaitCondition.KeepWaiting
            return

        if self.greps is not NotSpecified:
            for name, val in self.greps.items():
                yield 'grep "{0}" "{1}"'.format(val, name)

        if self.file_value is not NotSpecified:
            for name, val in self.file_value.items():
                command = 'diff <(echo {0}) <(cat {1})'.format(val, name)
                if not self.harpoon.debug:
                    command = "{0} > /dev/null".format(command)
                yield command

        if self.port_open is not NotSpecified:
            for port in self.port_open:
                yield 'nc -z 127.0.0.1 {0}'.format(port)

        if self.curl_result is not NotSpecified:
            for url, content in self.curl_result.items():
                yield 'diff <(curl "{0}") <(echo {1})'.format(url, content)

        if self.file_exists is not NotSpecified:
            for path in self.file_exists:
                yield 'cat {0} > /dev/null'.format(path)

        if self.command not in (None, "", NotSpecified):
            for command in self.command:
                yield command

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


Question: Upgrade required genome data files in place.

def _install_data(data_dir, path_flavor, args):

    try:
       from bcbio import install as bcb
    except:
        raise ImportError("It needs bcbio to do the quick installation.")

    bio_data = op.join(path_flavor, "../biodata.yaml")
    s = {"flavor": path_flavor,
         # "target": "[brew, conda]",
         "vm_provider": "novm",
         "hostname": "localhost",
         "fabricrc_overrides": {"edition": "minimal",
                                "use_sudo": "false",
                                "keep_isolated": "true",
                                "conda_cmd": bcb._get_conda_bin(),
                                "distribution": "__auto__",
                                "dist_name": "__auto__"}}
    s["actions"] = ["setup_biodata"]
    s["fabricrc_overrides"]["data_files"] = data_dir
    s["fabricrc_overrides"]["galaxy_home"] = os.path.join(data_dir, "galaxy")
    cbl = bcb.get_cloudbiolinux(bcb.REMOTES)
    s["genomes"] = _get_biodata(bio_data, args)
    sys.path.insert(0, cbl["dir"])
    cbl_deploy = __import__("cloudbio.deploy", fromlist=["deploy"])
    cbl_deploy.deploy(s)

def sync(self):
        """"""
        self.driver.create_schema()
        self.driver.set_metadata({
            'current_version': Gauged.VERSION,
            'initial_version': Gauged.VERSION,
            'block_size': self.config.block_size,
            'resolution': self.config.resolution,
            'created_at': long(time() * 1000)
        }, replace=False)

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


function onMessage(message) {
    if (!channel._wsConn) return
    if (message.type != "utf8") return

    message = JSON.parse(message.utf8Data)
    DEBUGMSG("onMessage", utils.JL(message))

    channel.emit("message", message)
  }

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:
Create a dep and store it in the self.dep

        :returns: None
        :rtype: None
        :raises: None

def create_dep(self, ):

        name = self.name_le.text()
        short = self.short_le.text()
        assetflag = self.asset_rb.isChecked()
        ordervalue = self.ordervalue_sb.value()
        desc = self.desc_pte.toPlainText()
        try:
            dep = djadapter.models.Department(name=name, short=short, assetflag=assetflag, ordervalue=ordervalue, description=desc)
            dep.save()
            for prj in self.projects:
                dep.projects.add(prj)
            self.dep = dep
            self.accept()
        except:
            log.exception("Could not create new department.")

def _end(ins):

    global FLAG_end_emitted
    output = _16bit_oper(ins.quad[1])
    output.append('ld b, h')
    output.append('ld c, l')

    if FLAG_end_emitted:
        return output + ['jp %s' % END_LABEL]

    FLAG_end_emitted = True

    output.append('%s:' % END_LABEL)
    if OPTIONS.headerless.value:
        return output + ['ret']

    output.append('di')
    output.append('ld hl, (%s)' % CALL_BACK)
    output.append('ld sp, hl')
    output.append('exx')
    output.append('pop hl')
    output.append('exx')
    output.append('pop iy')
    output.append('pop ix')
    output.append('ei')
    output.append('ret')
    output.append('%s:' % CALL_BACK)
    output.append('DEFW 0')

    return output

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


Question:
Normalization of the data includes subtracting mean from
each dimension therefore dimensions will be centered to zero

protected function normalize(array $data, int $n): array
    {
        if (count($this->means) === 0) {
            $this->calculateMeans($data, $n);
        }

        // Normalize data
        foreach (array_keys($data) as $i) {
            for ($k = 0; $k < $n; ++$k) {
                $data[$i][$k] -= $this->means[$k];
            }
        }

        return $data;
    }

protected function checkDimensionalConstraints(Item $itemToPack): bool
    {
        $orientatedItemFactory = new OrientatedItemFactory($this->box);
        $orientatedItemFactory->setLogger($this->logger);

        return (bool) $orientatedItemFactory->getPossibleOrientationsInEmptyBox($itemToPack);
    }

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


Question: // Connect returns a handler for the pod proxy

func (r *ProxyREST) Connect(ctx context.Context, id string, opts runtime.Object, responder rest.Responder) (http.Handler, error) {
	proxyOpts, ok := opts.(*api.PodProxyOptions)
	if !ok {
		return nil, fmt.Errorf("Invalid options object: %#v", opts)
	}
	location, transport, err := pod.ResourceLocation(r.Store, r.ProxyTransport, ctx, id)
	if err != nil {
		return nil, err
	}
	location.Path = net.JoinPreservingTrailingSlash(location.Path, proxyOpts.Path)
	// Return a proxy handler that uses the desired transport, wrapped with additional proxy handling (to get URL rewriting, X-Forwarded-* headers, etc)
	return newThrottledUpgradeAwareProxyHandler(location, transport, true, false, false, responder), nil
}

@Process(actionType = CreateConnection.class)
    public void createConnection(final CreateConnection action, final Dispatcher.Channel channel) {
        create(action.getAddressTemplate(), action.getInstanceName(), action.getNewModel(),
                getModelsFor(action.getAddressTemplate()), channel);
    }

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