Question:
=========================================================================
 視黄経・視黄緯の計算（太陽）

 @param:  <none>
 @return: [[視赤経, 視赤緯, 地心距離], [視黄経, 視黄緯, 地心距離], [視半径, 視差]]
=========================================================================

def compute_sun
      # === 太陽が光を発した時刻 t1(JD) の計算
      t_1_jd = calc_t1(:sun, @tdb)
      # === 時刻 t1(= TDB) におけるの位置・速度（ICRS 座標）の計算 (地球, 月, 太陽)
      Const::BODIES.each { |k, v| @icrs_1[k] = get_icrs(v, t_1_jd) }
      # === 時刻 t2 における地球重心から時刻 t1 における太陽への方向ベクトルの計算
      v_12 = calc_unit_vector(@icrs_2[:earth][0,3], @icrs_1[:sun][0,3])
      # === GCRS 座標系: 光行差の補正（方向ベクトルの Lorentz 変換）
      dd = conv_lorentz(v_12)
      pos_sun = calc_pos(dd, @r_e[:sun])
      # === 瞬時の真座標系: GCRS への bias & precession（歳差） & nutation（章動）の適用
      bpn = EphBpn.new(@tdb.strftime("%Y%m%d%H%M%S"))
      pos_sun_bpn = bpn.apply_bpn(pos_sun)
      # === 座標変換
      eq_pol_s  = MkCoord.rect2pol(pos_sun_bpn)
      ec_rect_s = MkCoord.rect_eq2ec(pos_sun_bpn, bpn.eps)
      ec_pol_s  = MkCoord.rect2pol(ec_rect_s)
      # === 視半径／（地平）視差計算
      radius = Math.asin(@asun / (eq_pol_s[2] * Const::AU / 1000))
      radius *= 180 / Math::PI * 3600
      parallax = Math.asin(@re / (eq_pol_s[2] * Const::AU / 1000))
      parallax *= 180 / Math::PI * 3600
      return [eq_pol_s, ec_pol_s, [radius, parallax]]
    rescue => e
      raise
    end

def http_error_handler(f):

    def hrefs_to_resources(hrefs):
        for href in hrefs.replace(',', '').split():
            type, uuid = href.split('/')[-2:]
            yield Resource(type, uuid=uuid)

    def hrefs_list_to_resources(hrefs_list):
        for href in eval(hrefs_list):
            type, uuid = href.split('/')[-2:]
            yield Resource(type, uuid=uuid)

    @wraps(f)
    def wrapper(self, *args, **kwargs):
        try:
            return f(self, *args, **kwargs)
        except HttpError as e:
            if e.http_status == 404:
                # remove previously created resource
                # from the cache
                self.emit('deleted', self)
                if isinstance(self, Resource):
                    raise ResourceNotFound(resource=self)
                elif isinstance(self, Collection):
                    raise CollectionNotFound(collection=self)
            elif e.http_status == 409:
                # contrail 3.2
                matches = re.match(r'^Delete when children still present: (\[[^]]*\])', e.message)
                if matches:
                    raise ChildrenExists(
                        resources=list(hrefs_list_to_resources(matches.group(1))))
                matches = re.match(r'^Delete when resource still referred: (\[[^]]*\])', e.message)
                if matches:
                    raise BackRefsExists(
                        resources=list(hrefs_list_to_resources(matches.group(1))))
                # contrail 2.21
                matches = re.match(r'^Children (.*) still exist$', e.message)
                if matches:
                    raise ChildrenExists(
                        resources=list(hrefs_to_resources(matches.group(1))))
                matches = re.match(r'^Back-References from (.*) still exist$', e.message)
                if matches:
                    raise BackRefsExists(
                        resources=list(hrefs_to_resources(matches.group(1))))
            raise
    return wrapper

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


Question: Use this operation to reboot Repeater Instance.

public static br reboot(nitro_service client, br resource) throws Exception
	{
		return ((br[]) resource.perform_operation(client, "reboot"))[0];
	}

def set_relay(self, relay_pin=0, state=True):
        ''''''
        if self.mavlink10():
            self.mav.command_long_send(
                self.target_system,  # target_system
                self.target_component, # target_component
                mavlink.MAV_CMD_DO_SET_RELAY, # command
                0, # Confirmation
                relay_pin, # Relay Number
                int(state), # state (1 to indicate arm)
                0, # param3 (all other params meaningless)
                0, # param4
                0, # param5
                0, # param6
                0) # param7
        else:
            print("Setting relays not supported.")

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


Question: Background process function for RuuviTag Sensors

def _run_get_data_background(macs, queue, shared_data, bt_device):

    run_flag = RunFlag()

    def add_data(data):
        if not shared_data['run_flag']:
            run_flag.running = False

        data[1]['time'] = datetime.utcnow().isoformat()
        queue.put(data)

    RuuviTagSensor.get_datas(add_data, macs, run_flag, bt_device)

def cleanup_images(self):

        for image in self.list_images():
            if CONU_ARTIFACT_TAG in image.name:
                image.rmi()
        # remove all hidden images -> causes trouble when pulling the image again
        run_cmd(["machinectl", "--no-pager", "clean"])

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


Question: /* applies function to value at given key

function reduceJSON(accum, json, fn, searchFor) {
  if (isKey(json, searchFor)) {
    return fn(accum, json[searchFor]);
  } else if (isAtom(json)) {
    return accum;
  } else if (isArray(json)) {
    return json.reduce((acc, item) => {
      return reduceJSON(acc, item, fn, searchFor);
    }, accum);
  } else {
    const keys = Object.keys(json);

    return keys.reduce((acc, key) => {
      return reduceJSON(acc, json[key], fn, searchFor);
    }, accum);
  }
}

func MakeKey(name []byte, tags Tags) []byte {
	return AppendMakeKey(nil, name, tags)
}

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


Question:
Retrieve an HTML population analysis table report from a multi exposure
    analysis.

def population_analysis_summary_report(feature, parent):

    _ = feature, parent  # NOQA
    analysis_dir = get_analysis_dir(exposure_population['key'])
    if analysis_dir:
        return get_impact_report_as_string(analysis_dir)
    return None

protected function addStepRoundMatch(\MUtil_Model_Bridge_FormBridgeInterface $bridge, \MUtil_Model_ModelAbstract $model)
    {
        $this->displayHeader($bridge, $this->_('Match the current track rounds to import rounds.'), 'h3');

        // Load the import data form settings
        $import = $this->loadImportData();

        $this->addExistingRoundsToModel($import, $model);

        $rounds = $model->getColNames('existingRound');

        if ($rounds) {
            $this->addItems($bridge, $rounds);
        } else {
            $bridge->addHtml('existingRound')->pInfo($this->_('No rounds in current track.'));
        }
    }

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


Question:
Short description of method getOperator

@access public
@author Jerome Bogaerts, <jerome.bogaerts@tudor.lu>
@return core_kernel_classes_Resource

public function getOperator()
    {
        $returnValue = null;

        if(empty($this->arithmeticOperator)){
        	$property = new core_kernel_classes_Property(RulesRdf::PROPERTY_OPERATION_OPERATOR);
        	$this->arithmeticOperator = $this->getUniquePropertyValue($property);
        }
        $returnValue = $this->arithmeticOperator;

        return $returnValue;
    }

func Convert_core_ResourceFieldSelector_To_v1_ResourceFieldSelector(in *core.ResourceFieldSelector, out *v1.ResourceFieldSelector, s conversion.Scope) error {
	return autoConvert_core_ResourceFieldSelector_To_v1_ResourceFieldSelector(in, out, s)
}

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


Question: // Copy dispatches to the appropriate FileManager or VirtualDiskManager Copy method based on file name extension

func (m *DatastoreFileManager) Copy(ctx context.Context, src string, dst string) error {
	srcp := m.Path(src)
	dstp := m.Path(dst)

	f := m.FileManager.CopyDatastoreFile

	if srcp.IsVMDK() {
		// types.VirtualDiskSpec=nil as it is not implemented by vCenter
		f = func(ctx context.Context, src string, srcDC *Datacenter, dst string, dstDC *Datacenter, force bool) (*Task, error) {
			return m.VirtualDiskManager.CopyVirtualDisk(ctx, src, srcDC, dst, dstDC, nil, force)
		}
	}

	task, err := f(ctx, srcp.String(), m.Datacenter, dstp.String(), m.DatacenterTarget, m.Force)
	if err != nil {
		return err
	}

	return m.wait(ctx, task)
}

public static String getMimeTypeByPath(String suffix) {
		while(suffix.startsWith(".") && suffix.length() > 0) {
			suffix = suffix.substring(1);
		}
		String mimeType = null;
		while((mimeType = findInMap(suffix)) == null) {
			int pos = suffix.indexOf('.');
			if(pos == -1) {
				break;
			}
			suffix = suffix.substring(pos+1);
		}
		return mimeType;
	}

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


Question: // See cairo_surface_create_observer().

func (target *Surface) CreateObserver(mode SurfaceObserverMode) *SurfaceObserver {
	ret := &SurfaceObserver{wrapSurface(C.cairo_surface_create_observer(target.Ptr, C.cairo_surface_observer_mode_t(mode)))}
	if err := target.status(); err != nil {
		panic(err)
	}
	return ret
}

public function initCron($src, $controller, $action) {
        if (!Config::config()['user']['debug']['maintenance']) {
            $this->_routeCron($src, $controller, $action);

            if ($this->_route == true) {
                $this->_setFunction($this->request->src);
                $this->_setEvent($this->request->src);
            }
        }
    }

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


Question:
Get the indentation for the given index

        :param index: the index to query
        :type index: :class:`QtCore.ModelIndex`
        :returns: the number of parents
        :rtype: int
        :raises: None

def get_total_indentation(self, index):

        n = 0
        while index.isValid():
            n += 1
            index = index.parent()
        return n * self.indentation()

public function index(Request $request)
    {
        $contentFolder = $this->content->getRoot();

        $content = $this->content->listFolder($request, $contentFolder);

        if (! $request->has('search')) {
            $contentTypes = $this->content->getCreatableContentTypes($contentFolder->id);
            $shortcuts = $this->content->getShortcuts($contentFolder);
            $isMovable = $content->where('is_movable', true)->count() ? true : false;
        } else {
            app('soda.interface')->breadcrumbs()->addLink(route('soda.content.index'), ucfirst(trans('soda::terminology.content_plural')));
            app('soda.interface')->setHeading('Search');
        }

        return soda_cms_view('data.content.index', compact('contentFolder', 'content', 'contentTypes', 'shortcuts', 'isMovable'));
    }

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


Question:
Sending message

@param string $message
@return string

public static function message($message) {

        return (new Color())->getColoredString(sprintf(self::MESSAGE, self::date(), $message), 'black', 'light_gray').PHP_EOL;

    }

private function convertToAmqpLibMessage(\Interop\Amqp\AmqpMessage $amqpMessage)
    {
        $amqpLibProperties = $amqpMessage->getHeaders();
        $amqpLibProperties['application_headers'] = $amqpMessage->getProperties();

        $amqpLibMessage = new AMQPMessage($amqpMessage->getBody(), $amqpLibProperties);
        $amqpLibMessage->delivery_info = [
            'consumer_tag' => $this->consumer->getConsumerTag(),
            'delivery_tag' => $amqpMessage->getDeliveryTag(),
            'redelivered' => $amqpMessage->isRedelivered(),
            'routing_key' => $amqpMessage->getRoutingKey(),
            'channel' => $this->channel,
        ];

        return $amqpLibMessage;
    }

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


Question:
Make sure the options object has an id on property,
either from caller or one we generate using supplied guid fn.

function ensureID(options, prop, callback) {
  if(options[prop]) {
    return callback();
  }

  options.guid(function(err, id) {
    if(err) {
      return callback(err);
    }
    options[prop] = id;
    callback();
  });
}

def _get_ref(data, position, obj_end, opts, element_name):
    """"""
    collection, position = _get_string(
        data, position, obj_end, opts, element_name)
    oid, position = _get_oid(data, position, obj_end, opts, element_name)
    return DBRef(collection, oid), position

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


Question:
Find objects by attribute

@param string $category
@param string $attribute
@param mixed $value

@return array List of object identifiers as integers

@throws Exception on error

public function find($category, $attribute, $value) {
        $cmdbObjects = new CMDBObjects($this->api);

        $limit = 100;
        $offset = 0;

        $objectIDs = [];

        while (true) {
            $objects = $cmdbObjects->read([], $limit, $offset);

            $count = count($objects);

            if ($count === 0) {
                break;
            }

            foreach ($objects as $object) {
                $objectIDs[] = (int)$object['id'];
            }

            unset($objects);

            $cmdbCategory = new CMDBCategory($this->api);

            $result = $cmdbCategory->batchRead(
                $objectIDs,
                [$category]
            );

            $objectIDs = [];

            foreach ($result as $categoryEntries) {
                foreach ($categoryEntries as $categoryEntry) {
                    if (!array_key_exists($attribute, $categoryEntry)) {
                        continue;
                    }

                    $found = false;

                    if (is_array($categoryEntry[$attribute]) &&
                        array_key_exists('ref_title', $categoryEntry[$attribute]) &&
                        $categoryEntry[$attribute]['ref_title'] === $value
                    ) {
                        $found = true;
                    } elseif (is_array($categoryEntry[$attribute]) &&
                        array_key_exists('title', $categoryEntry[$attribute]) &&
                        $categoryEntry[$attribute]['title'] === $value
                    ) {
                        $found = true;
                    } elseif (is_numeric($categoryEntry[$attribute]) &&
                        is_int($value) &&
                        (int)$categoryEntry[$attribute] === $value
                    ) {
                        $found = true;
                    } elseif (is_string($categoryEntry[$attribute]) &&
                        is_string($value) &&
                        $categoryEntry[$attribute] === $value
                    ) {
                        $found = true;
                    }

                    if ($found === false) {
                        continue;
                    }

                    if (!array_key_exists('objID', $categoryEntry)) {
                        throw new RuntimeException('Found attribute for unknown object');
                    }

                    $objectIDs[] = (int)$categoryEntry['objID'];
                }
            }

            if ($count < $limit) {
                break;
            }

            $offset += $limit;
        }

        return $objectIDs;
    }

@Override
    @Path("/{dataType}")
    public JSONObject get(String path, Map<String,String> headers) throws ServiceException, JSONException {
        String dataType = getSegment(path, 1);
        if (dataType == null)
            throw new ServiceException("Missing path segment: {dataType}");
        try {
            BaselineData baselineData = DataAccess.getBaselineData();
            if (dataType.equals("VariableTypes")) {
                List<VariableType> variableTypes = baselineData.getVariableTypes();
                JSONArray jsonArray = new JSONArray();
                for (VariableType variableType : variableTypes)
                    jsonArray.put(variableType.getJson());
                return new JsonArray(jsonArray).getJson();
            }
            else if (dataType.equals("TaskCategories")) {
                List<TaskCategory> taskCats = new ArrayList<TaskCategory>();
                taskCats.addAll(baselineData.getTaskCategories().values());
                Collections.sort(taskCats);
                JSONArray jsonArray = new JSONArray();
                for (TaskCategory taskCat : taskCats)
                    jsonArray.put(taskCat.getJson());
                return new JsonArray(jsonArray).getJson();
            }
            else {
                throw new ServiceException("Unsupported dataType: " + dataType);
            }
        }
        catch (Exception ex) {
            throw new ServiceException(ex.getMessage(), ex);
        }
    }

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


Question:
Helper function to set the appropriate path metadata

 from - the relative path to the redirect page
 to   - the relative path or absolute URL to the redirect target

def set_paths(from, to)
      @context ||= context
      from = ensure_leading_slash(from)
      data.merge!(
        "permalink" => from,
        "redirect"  => {
          "from" => from,
          "to"   => to =~ %r!^https?://! ? to : absolute_url(to),
        }
      )
    end

def match(self, request, service):

		uri = self.normalize_uri(request.path())

		if request.session().protocol() not in self.protocols:
			return

		if request.method() not in self.methods:
			return

		if self.virtual_hosts and request.virtual_host() not in self.virtual_hosts:
			return

		if self.ports and int(request.session().server_address().port()) not in self.ports:
			return

		match_obj = self.re_pattern.match(uri)

		if not match_obj:
			return

		presenter_action = self.action
		presenter_args = self.presenter_args.copy()

		for i in range(len(self.route_args)):
			if self.route_args[i] == 'action':
				presenter_action = match_obj.group(i + 1)
			else:
				presenter_args[self.route_args[i]] = match_obj.group(i + 1)

		return WWebTargetRoute(self.presenter, presenter_action, self, service.route_map(), **presenter_args)

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


Question: // finalize was the only func that did not strobe Done

func (tracker *callTracker) finalize(sn uint32) {
	tracker.lck.Lock()
	defer tracker.lck.Unlock()
	c, ok := tracker.calls[sn]
	if ok {
		delete(tracker.calls, sn)
		c.ContextCancel()
	}
	return
}

protected function shutdownItems(string $type, array $items)
    {
        if ($items !== []) {
            array_walk($items, function ($item) use ($type) {
                $provider = $this->make($item, [$this]);
                $provider->shutdown();

                unset($boot);

                // {{ log
                $this->get('logger')->info('关闭 ' . ucfirst($type) . ' 启动项 ' . $item);
                // }}
            });
        }
    }

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


Question:
Determine if two JSONObjects are similar.
They must contain the same set of names which must be associated with
similar values.

@param other The other JSONObject
@return true if they are equal

public boolean similar(Object other) {
        try {
            if (!(other instanceof JSONObject)) {
                return false;
            }
            if (!this.keySet().equals(((JSONObject)other).keySet())) {
                return false;
            }
            for (final Entry<String,?> entry : this.entrySet()) {
                String name = entry.getKey();
                Object valueThis = entry.getValue();
                Object valueOther = ((JSONObject)other).get(name);
                if(valueThis == valueOther) {
                	continue;
                }
                if(valueThis == null) {
                	return false;
                }
                if (valueThis instanceof JSONObject) {
                    if (!((JSONObject)valueThis).similar(valueOther)) {
                        return false;
                    }
                } else if (valueThis instanceof JSONArray) {
                    if (!((JSONArray)valueThis).similar(valueOther)) {
                        return false;
                    }
                } else if (!valueThis.equals(valueOther)) {
                    return false;
                }
            }
            return true;
        } catch (Throwable exception) {
            return false;
        }
    }

static boolean pointRelatePoint_(Point point_a, Point point_b,
			double tolerance, String scl, ProgressTracker progress_tracker) {
		Point2D pt_a = point_a.getXY();
		Point2D pt_b = point_b.getXY();
		int[] matrix = new int[9];

		for (int i = 0; i < 9; i++)
			matrix[i] = -1;

		if (Point2D.sqrDistance(pt_a, pt_b) <= tolerance * tolerance) {
			matrix[MatrixPredicate.InteriorInterior] = 0;
		} else {
			matrix[MatrixPredicate.InteriorExterior] = 0;
			matrix[MatrixPredicate.ExteriorInterior] = 0;
		}

		matrix[MatrixPredicate.ExteriorExterior] = 2;

		boolean bRelation = relationCompare_(matrix, scl);
		return bRelation;
	}

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


Question:
Normal Init level APIs

@param gwAPI
@param facade
@throws Exception

public static void init(final GwAPI gwAPI, GwFacade facade) throws Exception {
		String aftenv = gwAPI.env.getProperty(API_AAFAccess.AFT_ENVIRONMENT);
		if(aftenv==null) throw new Exception(API_AAFAccess.AFT_ENVIRONMENT + " must be set");

		////////
		// Do not deploy these to PROD
		///////
		if(API_AAFAccess.AFTUAT.equals(aftenv)) {
			gwAPI.route(HttpMethods.GET,"/tguard/:path*",API.VOID,new GwCode(facade,"TGuard Test", true) {
				@Override
				public void handle(AuthzTrans trans, HttpServletRequest req, HttpServletResponse resp) throws Exception {
					Result<Void> r = context.getAPI(trans,resp,gwAPI);
					switch(r.status) {
						case OK:
							resp.setStatus(HttpStatus.OK_200);
							break;
						default:
							context.error(trans,resp,r);
					}
				}
			});
		}
	}

func (c *InternalClient) FragmentNodes(ctx context.Context, index string, shard uint64) ([]*pilosa.Node, error) {
	span, ctx := tracing.StartSpanFromContext(ctx, "InternalClient.FragmentNodes")
	defer span.Finish()

	// Execute request against the host.
	u := uriPathToURL(c.defaultURI, "/internal/fragment/nodes")
	u.RawQuery = (url.Values{"index": {index}, "shard": {strconv.FormatUint(shard, 10)}}).Encode()

	// Build request.
	req, err := http.NewRequest("GET", u.String(), nil)
	if err != nil {
		return nil, errors.Wrap(err, "creating request")
	}

	req.Header.Set("User-Agent", "pilosa/"+pilosa.Version)
	req.Header.Set("Accept", "application/json")

	// Execute request.
	resp, err := c.executeRequest(req.WithContext(ctx))
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var a []*pilosa.Node
	if err := json.NewDecoder(resp.Body).Decode(&a); err != nil {
		return nil, fmt.Errorf("json decode: %s", err)
	}
	return a, nil
}

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


Question:
Set the time at which the resource was last modified.

@param lastModified the lastModified value to set
@return the JobScheduleTerminateHeaders object itself.

public JobScheduleTerminateHeaders withLastModified(DateTime lastModified) {
        if (lastModified == null) {
            this.lastModified = null;
        } else {
            this.lastModified = new DateTimeRfc1123(lastModified);
        }
        return this;
    }

def zone_schedules_backup(self, filename):
        """"""
        _LOGGER.info("Backing up schedules from ControlSystem: %s (%s)...",
                     self.systemId, self.location.name)

        schedules = {}

        if self.hotwater:
            _LOGGER.info("Retrieving DHW schedule: %s...",
                         self.hotwater.zoneId)

            schedule = self.hotwater.schedule()
            schedules[self.hotwater.zoneId] = {
                'name': 'Domestic Hot Water',
                'schedule': schedule}

        for zone in self._zones:
            zone_id = zone.zoneId
            name = zone.name

            _LOGGER.info("Retrieving Zone schedule: %s - %s", zone_id, name)

            schedule = zone.schedule()
            schedules[zone_id] = {'name': name, 'schedule': schedule}

        schedule_db = json.dumps(schedules, indent=4)

        _LOGGER.info("Writing to backup file: %s...", filename)
        with open(filename, 'w') as file_output:
            file_output.write(schedule_db)

        _LOGGER.info("Backup completed.")

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


Question:
/*
Execute functions on value.
Index functions.

public function process($parentRule)
    {
        static $thisFunction;
        if (! $thisFunction) {
            $thisFunction = new Functions(array('this' => 'CssCrush\fn__this'));
        }

        if (! $this->skip) {

            // this() function needs to be called exclusively because it is self referencing.
            $context = (object) array(
                'rule' => $parentRule
            );
            $this->value = $thisFunction->apply($this->value, $context);

            if (isset($parentRule->declarations->data)) {
                $parentRule->declarations->data += array($this->property => $this->value);
            }

            $context = (object) array(
                'rule' => $parentRule,
                'property' => $this->property
            );
            $this->value = Crush::$process->functions->apply($this->value, $context);
        }

        // Whitespace may have been introduced by functions.
        $this->value = trim($this->value);

        if ($this->value === '') {
            $this->valid = false;
            return;
        }

        $parentRule->declarations->queryData[$this->property] = $this->value;

        $this->indexFunctions();
    }

func WhereID(docID ID) func(DocumentIndex, DocumentDecorator) ([]ID, error) {
	return func(idx DocumentIndex, _ DocumentDecorator) ([]ID, error) {
		return []ID{docID}, nil
	}
}

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


Question:
Returns the Node at given index.

        :param index: Index.
        :type index: QModelIndex
        :return: Node.
        :rtype: AbstractCompositeNode or GraphModelNode

def get_node(self, index):

        if not index.isValid():
            return self.__root_node
        return index.internalPointer() or self.__root_node

public function treePageBlock(ServerRequestInterface $request, Tree $tree): ResponseInterface
    {
        $block_id = $request->get('block_id');

        $block_id = (int) DB::table('block')
            ->where('block_id', '=', $block_id)
            ->where('gedcom_id', '=', $tree->id())
            ->value('block_id');

        $module = $this->getBlockModule($tree, $block_id);

        $html = view('layouts/ajax', [
            'content' => $module->getBlock($tree, $block_id, 'gedcom'),
        ]);

        return response($html);
    }

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


Question:
Writes a JSON null.

@throws IOException if an error occurs

JsonEvent readEvent() throws IOException {
        char next = readNext();
        // whitespace
        while (next == ' ' || next == '\t' || next == '\n' || next == '\r') {
            next = readNext();
        }
        // identify token
        switch (next) {
            case '{':
                return JsonEvent.OBJECT;
            case '}':
                return JsonEvent.OBJECT_END;
            case '[':
                return JsonEvent.ARRAY;
            case ']':
                return JsonEvent.ARRAY_END;
            case '"':
                return JsonEvent.STRING;
            case '-':
            case '0':
            case '1':
            case '2':
            case '3':
            case '4':
            case '5':
            case '6':
            case '7':
            case '8':
            case '9':
                return acceptNumber(next);
            case 'n':
                return acceptNull();
            case 't':
                return acceptTrue();
            case 'f':
                return acceptFalse();
            case ',':
                return JsonEvent.COMMA;
            case ':':
                return JsonEvent.COLON;
            default:
                throw new IllegalArgumentException("Invalid JSON data: Expected JSON character but found '" + next + "'");
        }
    }

public void writeSuccessResult(int line) {
        logger.debug("Write Success result => line:{}", line);
        writeValue(resultColumnName, line, Messages.getMessage(Messages.SUCCESS_MESSAGE));
    }

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


Question: // Size implements the cache.Measurable interface.

func (udkimV3 UserDeviceKeyInfoMapV3) Size() int {
	// statically-sized part
	mapSize := cache.StaticSizeOfMapWithSize(
		cache.PtrSize, cache.PtrSize, len(udkimV3))

	// go through pointer type content
	var contentSize int
	for k, v := range udkimV3 {
		contentSize += len(k) + v.Size()
	}

	return mapSize + contentSize
}

def shrink (self):
        """"""
        trim = int(0.05*len(self))
        if trim:
            items = super(LFUCache, self).items()
            # sorting function for items
            keyfunc = lambda x: x[1][0]
            values = sorted(items, key=keyfunc)
            for item in values[0:trim]:
                del self[item[0]]

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


Question: // String returns the name for the given HealthcheckType.

func (h HealthcheckType) String() string {
	switch h {
	case HCTypeDNS:
		return "DNS"
	case HCTypeHTTP:
		return "HTTP"
	// TODO(angusc): Drop HTTPS as a separate type.
	case HCTypeHTTPS:
		return "HTTP" // NB: Not HTTPS
	case HCTypeICMP:
		return "ICMP"
	case HCTypeRADIUS:
		return "RADIUS"
	case HCTypeTCP:
		return "TCP"
	// TODO(angusc): Drop TCPTLS as a separate type.
	case HCTypeTCPTLS:
		return "TCP" // NB: Not TCPTLS
	case HCTypeUDP:
		return "UDP"
	}
	return "(unknown)"
}

def print(self, indent=2):
        """"""
        status = {
            ResultCode.NOT_IMPLEMENTED: '{}not implemented{}'.format(
                Fore.YELLOW, Style.RESET_ALL),
            ResultCode.IGNORED: '{}failed (ignored){}'.format(
                Fore.YELLOW, Style.RESET_ALL),
            ResultCode.FAILED: '{}failed{}'.format(
                Fore.RED, Style.RESET_ALL),
            ResultCode.PASSED: '{}passed{}'.format(
                Fore.GREEN, Style.RESET_ALL),
        }.get(self.code)
        print('{bold}{group}{provider}{checker}: {none}{status}{none}'.format(
            bold=Style.BRIGHT,
            group=(self.group.name + ' – ') if self.group.name else '',
            provider=(self.provider.name + ' – ') if self.provider else '',
            checker=self.checker.name,
            none=Style.RESET_ALL,
            status=status))
        if self.messages:
            for message in self.messages.split('\n'):
                print(pretty_description(message, indent=indent))
            if self.checker.hint:
                print(pretty_description(
                    'Hint: ' + self.checker.hint, indent=indent))

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


Question:
Generates instances from the sources using either cls.transform_args or transform_args
    argument if present.

def map(cls, sources, *, transform_args=None):

    for idx, source in enumerate(sources):
      try:
        yield cls.create(source, transform_args=transform_args)
      except Exception as ex:
        raise Exception("An error occurred with item {0}".format(idx)) from ex

def square_batch_region(data, region, bam_files, vrn_files, out_file):

    from bcbio.variation import sentieon, strelka2
    if not utils.file_exists(out_file):
        jointcaller = tz.get_in(("config", "algorithm", "jointcaller"), data)
        if jointcaller in ["%s-joint" % x for x in SUPPORTED["general"]]:
            _square_batch_bcbio_variation(data, region, bam_files, vrn_files, out_file, "square")
        elif jointcaller in ["%s-merge" % x for x in SUPPORTED["general"]]:
            _square_batch_bcbio_variation(data, region, bam_files, vrn_files, out_file, "merge")
        elif jointcaller in ["%s-joint" % x for x in SUPPORTED["gatk"]]:
            gatkjoint.run_region(data, region, vrn_files, out_file)
        elif jointcaller in ["%s-joint" % x for x in SUPPORTED["gvcf"]]:
            strelka2.run_gvcfgenotyper(data, region, vrn_files, out_file)
        elif jointcaller in ["%s-joint" % x for x in SUPPORTED["sentieon"]]:
            sentieon.run_gvcftyper(vrn_files, out_file, region, data)
        else:
            raise ValueError("Unexpected joint calling approach: %s." % jointcaller)
    if region:
        data["region"] = region
    data = _fix_orig_vcf_refs(data)
    data["vrn_file"] = out_file
    return [data]

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


Question:
copy styles from $from to this

@param \AppShed\Remote\Element\Styleable $from

public function copyStyles(Styleable $from)
    {
        $this->color = $from->getColor();
        $this->titleColor = $from->getTitleColor();
        $this->subtitleColor = $from->getSubtitleColor();
        $this->glowColor = $from->getGlowColor();
        $this->borderColor = $from->getBorderColor();
        $this->underline = $from->getUnderline();
        $this->size = $from->getSize();
        $this->fontFamily = $from->getFontFamily();
        $this->align = $from->getAlign();
        $this->bold = $from->getBold();
        $this->italic = $from->getItalic();
        $this->listBackground = $from->getListBackground();
        $this->galleryBackground = $from->getGalleryBackground();
        $this->iconBackground = $from->getIconBackground();
        $this->appsBackground = $from->getAppsBackground();
        $this->background = $from->getBackground();
        $this->hrAfter = $from->getHrAfter();
        $this->hrColor = $from->getHrColor();
        $this->hrWidth = $from->getHrWidth();
        $this->headerColor = $from->getHeaderColor();
        $this->headerTextColor = $from->getHeaderTextColor();
        $this->paddingTop = $from->getPaddingTop();
        $this->paddingBottom = $from->getPaddingBottom();
        $this->paddingLeft = $from->getPaddingLeft();
        $this->paddingRight = $from->getPaddingRight();
        $this->titleSize = $from->getTitleSize();
        $this->subtitleSize = $from->getSubtitleSize();
        $this->titleFont = $from->getTitleFont();
        $this->subtitleFont = $from->getSubtitleFont();
        $this->autoCompleteColor = $from->getAutoCompleteColor();
        $this->autoCompleteBackgroundColor = $from->getAutoCompleteBackgroundColor();
        $this->autoCompleteHighlightColor = $from->getAutoCompleteHighlightColor();
    }

private void extractAndWriteExtensionsAsDirectChild(IBase theElement, JsonLikeWriter theEventWriter, BaseRuntimeElementDefinition<?> theElementDef, RuntimeResourceDefinition theResDef,
																		 IBaseResource theResource, CompositeChildElement theChildElem, CompositeChildElement theParent, EncodeContext theEncodeContext) throws IOException {
		List<HeldExtension> extensions = new ArrayList<>(0);
		List<HeldExtension> modifierExtensions = new ArrayList<>(0);

		// Undeclared extensions
		extractUndeclaredExtensions(theElement, extensions, modifierExtensions, theChildElem, theParent);

		// Declared extensions
		if (theElementDef != null) {
			extractDeclaredExtensions(theElement, theElementDef, extensions, modifierExtensions, theChildElem);
		}

		// Write the extensions
		writeExtensionsAsDirectChild(theResource, theEventWriter, theResDef, extensions, modifierExtensions, theEncodeContext);
	}

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


Question:
Get the default phases at which restrictions should be applied, by looking for a @RestrictAtPhase on a matching

@param viewId
@return default phases for a view
@ViewPattern, falling back on global defaults if none are found

public PhaseIdType[] getDefaultPhases(String viewId) {
        PhaseIdType[] defaultPhases = null;
        RestrictAtPhase restrictAtPhase = viewConfigStore.getAnnotationData(viewId, RestrictAtPhase.class);
        if (restrictAtPhase != null) {
            defaultPhases = restrictAtPhase.value();
        }
        if (defaultPhases == null) {
            defaultPhases = RestrictAtPhaseDefault.DEFAULT_PHASES;
        }
        return defaultPhases;
    }

func (v *Value) setRaw(name, str string) error {
	var err error
	switch resolveAlias(name) {
	case Arch:
		err = v.setArch(str)
	case Container:
		err = v.setContainer(str)
	case Cores:
		err = v.setCpuCores(str)
	case CpuPower:
		err = v.setCpuPower(str)
	case Mem:
		err = v.setMem(str)
	case RootDisk:
		err = v.setRootDisk(str)
	case RootDiskSource:
		err = v.setRootDiskSource(str)
	case Tags:
		err = v.setTags(str)
	case InstanceType:
		err = v.setInstanceType(str)
	case Spaces:
		err = v.setSpaces(str)
	case VirtType:
		err = v.setVirtType(str)
	case Zones:
		err = v.setZones(str)
	default:
		return errors.Errorf("unknown constraint %q", name)
	}
	if err != nil {
		return errors.Annotatef(err, "bad %q constraint", name)
	}
	return nil
}

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


Question: Convert CF projection parameters to PROJ.4 dict.

def _get_proj_specific_params(self, projection):
        """"""
        proj = self._get_proj4_name(projection)
        proj_dict = {
            'proj': proj,
            'a': float(projection.attrs['semi_major_axis']),
            'b': float(projection.attrs['semi_minor_axis']),
            'units': 'm',
        }
        if proj == 'geos':
            proj_dict['h'] = float(projection.attrs['perspective_point_height'])
            proj_dict['sweep'] = projection.attrs.get('sweep_angle_axis', 'y')
            proj_dict['lon_0'] = float(projection.attrs['longitude_of_projection_origin'])
            proj_dict['lat_0'] = float(projection.attrs.get('latitude_of_projection_origin', 0.0))
        elif proj == 'lcc':
            proj_dict['lat_0'] = float(projection.attrs['standard_parallel'])
            proj_dict['lon_0'] = float(projection.attrs['longitude_of_central_meridian'])
            proj_dict['lat_1'] = float(projection.attrs['latitude_of_projection_origin'])
        elif proj == 'stere':
            proj_dict['lat_ts'] = float(projection.attrs['standard_parallel'])
            proj_dict['lon_0'] = float(projection.attrs['straight_vertical_longitude_from_pole'])
            proj_dict['lat_0'] = float(projection.attrs['latitude_of_projection_origin'])
        elif proj == 'merc':
            proj_dict['lat_ts'] = float(projection.attrs['standard_parallel'])
            proj_dict['lat_0'] = proj_dict['lat_ts']
            proj_dict['lon_0'] = float(projection.attrs['longitude_of_projection_origin'])
        else:
            raise ValueError("Can't handle projection '{}'".format(proj))
        return proj_dict

def prepare_request(settings):

    # Set the ACS url and binding method
    settings["sp"]["assertionConsumerService"] = {
        "url": web.ctx.homedomain + web.ctx.homepath + "/auth/callback/" + settings["id"],
        "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
    }

    # If server is behind proxys or balancers use the HTTP_X_FORWARDED fields
    data = web.input()
    return {
        'https': 'on' if web.ctx.protocol == 'https' else 'off',
        'http_host': web.ctx.environ["SERVER_NAME"],
        'server_port': web.ctx.environ["SERVER_PORT"],
        'script_name': web.ctx.homepath,
        'get_data': data.copy(),
        'post_data': data.copy(),
        # Uncomment if using ADFS as IdP, https://github.com/onelogin/python-saml/pull/144
        # 'lowercase_urlencoding': True,
        'query_string': web.ctx.query
    }

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


Question: Add a union statement to the query.

function union(callbacks, wrap) {
    if (arguments.length === 1 || arguments.length === 2 && typeof wrap === 'boolean') {
      if (!Array.isArray(callbacks)) {
        callbacks = [callbacks];
      }
      for (var i = 0, l = callbacks.length; i < l; i++) {
        this._statements.push({
          grouping: 'union',
          clause: 'union',
          value: callbacks[i],
          wrap: wrap || false
        });
      }
    } else {
      callbacks = normalizeArr.apply(null, arguments).slice(0, arguments.length - 1);
      wrap = arguments[arguments.length - 1];
      if (typeof wrap !== 'boolean') {
        callbacks.push(wrap);
        wrap = false;
      }
      this.union(callbacks, wrap);
    }
    return this;
  }

public static SMARTSAtom and(IQueryAtom left, IQueryAtom right) {
        return new Conjunction(left.getBuilder(), left, right);
    }

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


Question:
Validates the certificate revocation status

@param pairIssuerSubject a pair of issuer and subject certificates
@param ocspRespB64       Base64 encoded OCSP Response object
@throws CertificateException raises if any other error occurs

private void validateRevocationStatusMain(
      SFPair<Certificate, Certificate> pairIssuerSubject,
      String ocspRespB64) throws CertificateException
  {
    try
    {
      OCSPResp ocspResp = b64ToOCSPResp(ocspRespB64);
      Date currentTime = new Date();
      BasicOCSPResp basicOcspResp = (BasicOCSPResp) (ocspResp.getResponseObject());
      X509CertificateHolder[] attachedCerts = basicOcspResp.getCerts();
      X509CertificateHolder signVerifyCert;
      if (attachedCerts.length > 0)
      {
        LOGGER.debug(
            "Certificate is attached for verification. " +
            "Verifying it by the issuer certificate.");
        signVerifyCert = attachedCerts[0];
        if (currentTime.after(signVerifyCert.getNotAfter()) || currentTime.before(signVerifyCert.getNotBefore()))
        {
          throw new OCSPException(String.format("Cert attached to OCSP Response is invalid." +
                                                "Current time - %s" +
                                                "Certificate not before time - %s" +
                                                "Certificate not after time - %s",
                                                currentTime.toString(),
                                                signVerifyCert.getNotBefore().toString(),
                                                signVerifyCert.getNotAfter().toString()));
        }
        verifySignature(
            new X509CertificateHolder(pairIssuerSubject.left.getEncoded()),
            signVerifyCert.getSignature(),
            CONVERTER_X509.getCertificate(signVerifyCert).getTBSCertificate(),
            signVerifyCert.getSignatureAlgorithm());
        LOGGER.debug(
            "Verifying OCSP signature by the attached certificate public key."
        );
      }
      else
      {
        LOGGER.debug("Certificate is NOT attached for verification. " +
                     "Verifying OCSP signature by the issuer public key.");
        signVerifyCert = new X509CertificateHolder(
            pairIssuerSubject.left.getEncoded());
      }
      verifySignature(
          signVerifyCert,
          basicOcspResp.getSignature(),
          basicOcspResp.getTBSResponseData(),
          basicOcspResp.getSignatureAlgorithmID());

      validateBasicOcspResponse(currentTime, basicOcspResp);
    }
    catch (IOException | OCSPException ex)
    {
      throw new CertificateEncodingException(
          "Failed to check revocation status.", ex);
    }
  }

public function call($method, $parameters)
    {
        try {
            $ch = curl_init($this->base_url);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $this->encode($method, $parameters));
            curl_setopt($ch, CURLOPT_TIMEOUT, 600);

            $response = curl_exec($ch);

            if ($response === false) {
                $e = new TransportException(curl_error($ch), curl_getinfo($ch, CURLINFO_HTTP_CODE));
                curl_close($ch);

                throw  $e;
            }

            curl_close($ch);

            return $this->decode($response);
        } catch (XmlrpcException $e) {
            throw new TransportException('XML parsing error', 0, $e);
        }
    }

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


Question: Marshall the given parameter object.

public void marshall(ElastiCacheInstanceDetails elastiCacheInstanceDetails, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getFamily(), FAMILY_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getNodeType(), NODETYPE_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getRegion(), REGION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getProductDescription(), PRODUCTDESCRIPTION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getCurrentGeneration(), CURRENTGENERATION_BINDING);
            protocolMarshaller.marshall(elastiCacheInstanceDetails.getSizeFlexEligible(), SIZEFLEXELIGIBLE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

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


Question:
This is an optional operation, by default supported.

@return The next token in the token stream.
@throws java.util.NoSuchElementException
if the token stream has no more tokens.

public T peek() {
    if (nextToken == null) {
      nextToken = getNext();
    }
    if (nextToken == null) {
      throw new NoSuchElementException();
    }
    return nextToken;
  }

func (s *ListExecutionsOutput) SetNextToken(v string) *ListExecutionsOutput {
	s.NextToken = &v
	return s
}

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


Question: Auto Generated Code

def mac_access_list_extended_hide_mac_acl_ext_seq_action(self, **kwargs):

        config = ET.Element("config")
        mac = ET.SubElement(config, "mac", xmlns="urn:brocade.com:mgmt:brocade-mac-access-list")
        access_list = ET.SubElement(mac, "access-list")
        extended = ET.SubElement(access_list, "extended")
        name_key = ET.SubElement(extended, "name")
        name_key.text = kwargs.pop('name')
        hide_mac_acl_ext = ET.SubElement(extended, "hide-mac-acl-ext")
        seq = ET.SubElement(hide_mac_acl_ext, "seq")
        seq_id_key = ET.SubElement(seq, "seq-id")
        seq_id_key.text = kwargs.pop('seq_id')
        action = ET.SubElement(seq, "action")
        action.text = kwargs.pop('action')

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

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

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

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


Question:
Returns:
            dict: In the form { (item_id, metadata) -> [(x, y, amount), ...] }

def ingredient_positions(self):

        positions = defaultdict(list)
        for y, row in enumerate(self.in_shape):
            for x, (item_id, metadata, amount) in enumerate(row):
                positions[(item_id, metadata)].append((x, y, amount))
        return positions

public function fill_meta($meta_data) {
	foreach ($meta_data as $key => $single_meta_data) {
		$this->add_meta($key, $single_meta_data);
	}
}

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


Question:
Retrieves the properties of a piece of content.

@param spaceID
@param contentID
@return Map of content properties

@Override
    public Map<String, String> getContentProperties(String spaceID,
                                                    String contentID,
                                                    String storeID)
        throws ResourceException {
        try {
            StorageProvider storage =
                storageProviderFactory.getStorageProvider(storeID);
            return storage.getContentProperties(spaceID, contentID);
        } catch (NotFoundException e) {
            throw new ResourceNotFoundException("get properties for content",
                                                spaceID,
                                                contentID,
                                                e);
        } catch (Exception e) {
            storageProviderFactory.expireStorageProvider(storeID);
            throw new ResourceException("get properties for content",
                                        spaceID,
                                        contentID,
                                        e);
        }
    }

public void marshall(CodeContentDescription codeContentDescription, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(codeContentDescription.getTextContent(), TEXTCONTENT_BINDING);
            protocolMarshaller.marshall(codeContentDescription.getCodeMD5(), CODEMD5_BINDING);
            protocolMarshaller.marshall(codeContentDescription.getCodeSize(), CODESIZE_BINDING);
            protocolMarshaller.marshall(codeContentDescription.getS3ApplicationCodeLocationDescription(), S3APPLICATIONCODELOCATIONDESCRIPTION_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:
{@inheritDoc}

@param HasActions $service

public function register_actions( HasActions $service ) {
		foreach ( $service->action_hooks() as $action ) {
			$this->actions = $this->add(
				$this->actions,
				$action['hook'],
				$service,
				$action['method'],
				isset( $action['priority'] ) ? $action['priority'] : 10,
				isset( $action['args'] ) ? $action['args'] : 1
			);
		}
	}

func GetActionDescriptor(action *Action) ActionDescriptor {
	bee := GetBee(action.Bee)
	if bee == nil {
		panic("Bee " + action.Bee + " not registered")
	}
	factory := (*GetFactory((*bee).Namespace()))
	for _, ac := range factory.Actions() {
		if ac.Name == action.Name {
			return ac
		}
	}

	return ActionDescriptor{}
}

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


Question: // val is a 12-bit int

func writeData(val uint, sinPin hwio.Pin, sclkPin hwio.Pin, xlatPin hwio.Pin) {
	fmt.Printf("writing data %d\n", val)
	bits := 0
	mask := uint(1) << 11
	for i := 0; i < 16; i++ {
		v := val
		for j := 0; j < 12; j++ {
			if (v & mask) != 0 {
				hwio.DigitalWrite(sinPin, hwio.HIGH)
			} else {
				hwio.DigitalWrite(sinPin, hwio.HIGH)
			}
			hwio.DigitalWrite(sclkPin, hwio.HIGH)
			hwio.DigitalWrite(sclkPin, hwio.LOW)

			v = v << 1
			bits++
		}
	}

	hwio.DigitalWrite(xlatPin, hwio.HIGH)
	hwio.DigitalWrite(xlatPin, hwio.LOW)
	fmt.Printf("Wrote %d bits\n", bits)
}

func (c *Client) ExpireAt(key string, unixTime uint64) (bool, error) {
	var ret bool
	err := c.command(
		&ret,
		[]byte("EXPIREAT"),
		[]byte(key),
		to.Bytes(unixTime),
	)
	return ret, err
}

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


Question:
Validates a {@code @RestrictedApi} annotation and that the declared restriction makes sense.

The other match functions in this class check the usages of a restricted API.

@Override
  public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
    // TODO(bangert): Validate all the fields
    if (!ASTHelpers.getSymbol(tree).toString().equals(RestrictedApi.class.getName())) {
      return Description.NO_MATCH;
    }
    // TODO(bangert): make a more elegant API to get the annotation within an annotation tree.
    // Maybe find the declared object and get annotations on that...
    AnnotationMirror restrictedApi = ASTHelpers.getAnnotationMirror(tree);
    if (restrictedApi == null) {
      return Description.NO_MATCH;
    }
    return Description.NO_MATCH;
  }

def check_api_version(resource_root, min_version):

  if resource_root.version < min_version:
    raise Exception("API version %s is required but %s is in use."
        % (min_version, resource_root.version))

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


Question:
// DocvalueFields adds one or more fields to load from the field data cache
// and return as part of the search.

func (s *SearchService) DocvalueFields(docvalueFields ...string) *SearchService {
	s.searchSource = s.searchSource.DocvalueFields(docvalueFields...)
	return s
}

private function updateTerm(JsonDocument $document, Category $category)
    {
        $offerLD = $document->getBody();

        $oldTerms = property_exists($offerLD, 'terms') ? $offerLD->terms : [];
        $newTerm = (object) $category->serialize();

        $newTerms = array_filter(
            $oldTerms,
            function ($term) use ($category) {
                return !property_exists($term, 'domain') || $term->domain !== $category->getDomain();
            }
        );

        array_push($newTerms, $newTerm);

        $offerLD->terms = array_values($newTerms);

        return $document->withBody($offerLD);
    }

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


Question:
Instantiate and run the perform method od given task data.

    :param task_cls: task class
    :param task_data: task data
    :type task_data: TaskData
    :return: task's result

def run_task(task_cls, task_data):

    task = instantiate(task_cls)
    task_callable = get_callable(task)
    return task_callable(TaskData(task_data))

@Override public DeepWaterModel createImpl() {
    DeepWaterParameters parms = parameters.createImpl();
    return new DeepWaterModel(Key.<DeepWaterModel>make() /*dest*/, parms, new DeepWaterModelOutput(null), null, null, 0);
  }

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


Question: Exclude source files that have no executable statements.

public function excludeNoStatementsFiles()
    {
        $this->sourceFiles = array_filter(
            $this->sourceFiles,
            function (SourceFile $sourceFile) {
                return $sourceFile->getMetrics()->hasStatements();
            }
        );
    }

func (toolkit BashToolkit) StepRunCommandArguments(step stepmanModels.StepModel, sIDData models.StepIDData, stepAbsDirPath string) ([]string, error) {
	entryFile := "step.sh"
	if step.Toolkit != nil && step.Toolkit.Bash != nil && step.Toolkit.Bash.EntryFile != "" {
		entryFile = step.Toolkit.Bash.EntryFile
	}

	stepFilePath := filepath.Join(stepAbsDirPath, entryFile)
	cmd := []string{"bash", stepFilePath}
	return cmd, nil
}

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


Question: Note that a GETFIELD call has been replaced to method call.

public void addGetFieldIntercept(String owner, String name) {

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

func (entry *Entry) Field(name string) (value string, err error) {
	value, ok := entry.fields[name]
	if !ok {
		err = fmt.Errorf("field '%v' does not found in record %+v", name, *entry)
	}
	return
}

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


Question:
Detect the coupling errors of the nodes that are found among a set of rules.

@param Finder          $finder
@param RuleInterface[] $rules

@return ViolationInterface[]

public function detect(Finder $finder, array $rules): array
    {
        $nodes = $this->parseNodes($finder);
        $violations = array();

        $this->eventDispatcher->dispatch(Events::PRE_RULES_CHECKED, new PreRulesCheckedEvent($rules));

        foreach ($rules as $rule) {
            $ruleViolations = array();

            foreach ($nodes as $node) {
                $violation = $this->ruleChecker->check($rule, $node);
                if (null !== $violation) {
                    $ruleViolations[] = $violation;
                }

                $this->eventDispatcher->dispatch(
                    Events::NODE_CHECKED,
                    new NodeChecked($node, $rule, $violation)
                );
            }

            $this->eventDispatcher->dispatch(
                Events::RULE_CHECKED,
                new RuleCheckedEvent($rule, $ruleViolations)
            );

            $violations = array_merge($violations, $ruleViolations);
        }

        $this->eventDispatcher->dispatch(Events::POST_RULES_CHECKED, new PostRulesCheckedEvent($violations));

        return $violations;
    }

public function pass(DataBagInterface $dataBag): DataBagInterface
    {
        if (!($this->callback)($dataBag)) {
            throw new FlowTerminationException(
                sprintf(
                    'Flow was terminated by Filter (%s) for data %s.',
                    $this->getIdentifier(),
                    json_encode($dataBag)
                )
            );
        }

        return $dataBag;
    }

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


Question:
/* (non-Javadoc)
@see com.ibm.ws.sib.processor.runtime.MessageProcessorControllable#getForeignBusIterator()

public SIMPIterator getForeignBusIterator()
  {
    ForeignBusTypeFilter filter = new ForeignBusTypeFilter();
    SIMPIterator foreignBusItr = destinationManager.getForeignBusIndex().iterator(filter);
    return new ControllableIterator(foreignBusItr);
  }

def get_handlers(self, component_context, instance):

        # Extract information from the context
        configs = component_context.get_handler(
            ipopo_constants.HANDLER_TEMPORAL
        )
        requires_filters = component_context.properties.get(
            ipopo_constants.IPOPO_REQUIRES_FILTERS, None
        )
        temporal_timeouts = component_context.properties.get(
            ipopo_constants.IPOPO_TEMPORAL_TIMEOUTS, None
        )

        # Prepare requirements
        new_configs = self._prepare_configs(
            configs, requires_filters, temporal_timeouts
        )

        # Return handlers
        return [
            TemporalDependency(field, requirement, timeout)
            for field, (requirement, timeout) in new_configs.items()
        ]

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


Question:
/* (non-PHPdoc)
@see \Zend\Hydrator\HydratorInterface::extract()

public function extract($object)
    {
        $controllerPluginManager = $this->serviceManager->get('controllerPluginManager');

        $data = parent::extract($object);
        $viewLink = $controllerPluginManager->get('url')->fromRoute(
            'lang/jobs/view',
            array(
              ),
            array(
                  'query' => array(
                      'id' => $data['id'],
                  )
              )
        );

        $data['previewLink']         = $viewLink;
        return $data;
    }

public function resolveLoader($resource)
    {
        foreach ($this->loaders as $loader) {
            if ($loader->supports($resource)) {
                return $loader;
            }
        }

        return null;
    }

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


Question: Set relay_pin to value of state

def set_relay(self, relay_pin=0, state=True):
        ''''''
        if self.mavlink10():
            self.mav.command_long_send(
                self.target_system,  # target_system
                self.target_component, # target_component
                mavlink.MAV_CMD_DO_SET_RELAY, # command
                0, # Confirmation
                relay_pin, # Relay Number
                int(state), # state (1 to indicate arm)
                0, # param3 (all other params meaningless)
                0, # param4
                0, # param5
                0, # param6
                0) # param7
        else:
            print("Setting relays not supported.")

def readRGB(self):

        self.reset_bits_pending();
        r = self.readUI8()
        g = self.readUI8()
        b = self.readUI8()
        return (0xff << 24) | (r << 16) | (g << 8) | b

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


Question: // SetLimit sets the Limit field's value.

func (s *GetResourceConfigHistoryInput) SetLimit(v int64) *GetResourceConfigHistoryInput {
	s.Limit = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question: Use this operation to get bluecat XVA file.

public static xen_bluecatvpx_image[] get(nitro_service client) throws Exception
	{
		xen_bluecatvpx_image resource = new xen_bluecatvpx_image();
		resource.validate("get");
		return (xen_bluecatvpx_image[]) resource.get_resources(client);
	}

def buildcss(app, buildpath, imagefile):
    """"""
    # set default values
    div = 'body'
    repeat = 'repeat-y'
    position = 'center'
    attachment = 'scroll'

    if app.config.sphinxmark_div != 'default':
        div = app.config.sphinxmark_div

    if app.config.sphinxmark_repeat is False:
        repeat = 'no-repeat'

    if app.config.sphinxmark_fixed is True:
        attachment = 'fixed'

    border = app.config.sphinxmark_border
    if border == 'left' or border == 'right':
        css = template('border', div=div, image=imagefile, side=border)
    else:
        css = template('watermark', div=div, image=imagefile, repeat=repeat,
                       position=position, attachment=attachment)
    LOG.debug('[sphinxmark] Template: ' + css)
    cssname = 'sphinxmark.css'
    cssfile = os.path.join(buildpath, cssname)

    with open(cssfile, 'w') as f:
        f.write(css)

    return(cssname)

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


Question: Decodes received data.

public function decode(SplFixedArray $data, SplFixedArray $erasures = null) : ?int
    {
        // This speeds up the initialization a bit.
        $numRootsPlusOne = SplFixedArray::fromArray(array_fill(0, $this->numRoots + 1, 0), false);
        $numRoots = SplFixedArray::fromArray(array_fill(0, $this->numRoots, 0), false);

        $lambda = clone $numRootsPlusOne;
        $b = clone $numRootsPlusOne;
        $t = clone $numRootsPlusOne;
        $omega = clone $numRootsPlusOne;
        $root = clone $numRoots;
        $loc = clone $numRoots;

        $numErasures = (null !== $erasures ? count($erasures) : 0);

        // Form the Syndromes; i.e., evaluate data(x) at roots of g(x)
        $syndromes = SplFixedArray::fromArray(array_fill(0, $this->numRoots, $data[0]), false);

        for ($i = 1; $i < $this->blockSize - $this->padding; ++$i) {
            for ($j = 0; $j < $this->numRoots; ++$j) {
                if ($syndromes[$j] === 0) {
                    $syndromes[$j] = $data[$i];
                } else {
                    $syndromes[$j] = $data[$i] ^ $this->alphaTo[
                        $this->modNn($this->indexOf[$syndromes[$j]] + ($this->firstRoot + $j) * $this->primitive)
                    ];
                }
            }
        }

        // Convert syndromes to index form, checking for nonzero conditions
        $syndromeError = 0;

        for ($i = 0; $i < $this->numRoots; ++$i) {
            $syndromeError |= $syndromes[$i];
            $syndromes[$i] = $this->indexOf[$syndromes[$i]];
        }

        if (! $syndromeError) {
            // If syndrome is zero, data[] is a codeword and there are no errors to correct, so return data[]
            // unmodified.
            return 0;
        }

        $lambda[0] = 1;

        if ($numErasures > 0) {
            // Init lambda to be the erasure locator polynomial
            $lambda[1] = $this->alphaTo[$this->modNn($this->primitive * ($this->blockSize - 1 - $erasures[0]))];

            for ($i = 1; $i < $numErasures; ++$i) {
                $u = $this->modNn($this->primitive * ($this->blockSize - 1 - $erasures[$i]));

                for ($j = $i + 1; $j > 0; --$j) {
                    $tmp = $this->indexOf[$lambda[$j - 1]];

                    if ($tmp !== $this->blockSize) {
                        $lambda[$j] = $lambda[$j] ^ $this->alphaTo[$this->modNn($u + $tmp)];
                    }
                }
            }
        }

        for ($i = 0; $i <= $this->numRoots; ++$i) {
            $b[$i] = $this->indexOf[$lambda[$i]];
        }

        // Begin Berlekamp-Massey algorithm to determine error+erasure locator polynomial
        $r  = $numErasures;
        $el = $numErasures;

        while (++$r <= $this->numRoots) {
            // Compute discrepancy at the r-th step in poly form
            $discrepancyR = 0;

            for ($i = 0; $i < $r; ++$i) {
                if ($lambda[$i] !== 0 && $syndromes[$r - $i - 1] !== $this->blockSize) {
                    $discrepancyR ^= $this->alphaTo[
                        $this->modNn($this->indexOf[$lambda[$i]] + $syndromes[$r - $i - 1])
                    ];
                }
            }

            $discrepancyR = $this->indexOf[$discrepancyR];

            if ($discrepancyR === $this->blockSize) {
                $tmp = $b->toArray();
                array_unshift($tmp, $this->blockSize);
                array_pop($tmp);
                $b = SplFixedArray::fromArray($tmp, false);
                continue;
            }

            $t[0] = $lambda[0];

            for ($i = 0; $i < $this->numRoots; ++$i) {
                if ($b[$i] !== $this->blockSize) {
                    $t[$i + 1] = $lambda[$i + 1] ^ $this->alphaTo[$this->modNn($discrepancyR + $b[$i])];
                } else {
                    $t[$i + 1] = $lambda[$i + 1];
                }
            }

            if (2 * $el <= $r + $numErasures - 1) {
                $el = $r + $numErasures - $el;

                for ($i = 0; $i <= $this->numRoots; ++$i) {
                    $b[$i] = (
                        $lambda[$i] === 0
                        ? $this->blockSize
                        : $this->modNn($this->indexOf[$lambda[$i]] - $discrepancyR + $this->blockSize)
                    );
                }
            } else {
                $tmp = $b->toArray();
                array_unshift($tmp, $this->blockSize);
                array_pop($tmp);
                $b = SplFixedArray::fromArray($tmp, false);
            }

            $lambda = clone $t;
        }

        // Convert lambda to index form and compute deg(lambda(x))
        $degLambda = 0;

        for ($i = 0; $i <= $this->numRoots; ++$i) {
            $lambda[$i] = $this->indexOf[$lambda[$i]];

            if ($lambda[$i] !== $this->blockSize) {
                $degLambda = $i;
            }
        }

        // Find roots of the error+erasure locator polynomial by Chien search.
        $reg = clone $lambda;
        $reg[0] = 0;
        $count = 0;
        $i = 1;

        for ($k = $this->iPrimitive - 1; $i <= $this->blockSize; ++$i, $k = $this->modNn($k + $this->iPrimitive)) {
            $q = 1;

            for ($j = $degLambda; $j > 0; $j--) {
                if ($reg[$j] !== $this->blockSize) {
                    $reg[$j] = $this->modNn($reg[$j] + $j);
                    $q ^= $this->alphaTo[$reg[$j]];
                }
            }

            if ($q !== 0) {
                // Not a root
                continue;
            }

            // Store root (index-form) and error location number
            $root[$count] = $i;
            $loc[$count] = $k;

            if (++$count === $degLambda) {
                break;
            }
        }

        if ($degLambda !== $count) {
            // deg(lambda) unequal to number of roots: uncorrectable error detected
            return null;
        }

        // Compute err+eras evaluate poly omega(x) = s(x)*lambda(x) (modulo x**numRoots). In index form. Also find
        // deg(omega).
        $degOmega = $degLambda - 1;

        for ($i = 0; $i <= $degOmega; ++$i) {
            $tmp = 0;

            for ($j = $i; $j >= 0; --$j) {
                if ($syndromes[$i - $j] !== $this->blockSize && $lambda[$j] !== $this->blockSize) {
                    $tmp ^= $this->alphaTo[$this->modNn($syndromes[$i - $j] + $lambda[$j])];
                }
            }

            $omega[$i] = $this->indexOf[$tmp];
        }

        // Compute error values in poly-form. num1 = omega(inv(X(l))), num2 = inv(X(l))**(firstRoot-1) and
        // den = lambda_pr(inv(X(l))) all in poly form.
        for ($j = $count - 1; $j >= 0; --$j) {
            $num1 = 0;

            for ($i = $degOmega; $i >= 0; $i--) {
                if ($omega[$i] !== $this->blockSize) {
                    $num1 ^= $this->alphaTo[$this->modNn($omega[$i] + $i * $root[$j])];
                }
            }

            $num2 = $this->alphaTo[$this->modNn($root[$j] * ($this->firstRoot - 1) + $this->blockSize)];
            $den  = 0;

            // lambda[i+1] for i even is the formal derivativelambda_pr of lambda[i]
            for ($i = min($degLambda, $this->numRoots - 1) & ~1; $i >= 0; $i -= 2) {
                if ($lambda[$i + 1] !== $this->blockSize) {
                    $den ^= $this->alphaTo[$this->modNn($lambda[$i + 1] + $i * $root[$j])];
                }
            }

            // Apply error to data
            if ($num1 !== 0 && $loc[$j] >= $this->padding) {
                $data[$loc[$j] - $this->padding] = $data[$loc[$j] - $this->padding] ^ (
                    $this->alphaTo[
                        $this->modNn(
                            $this->indexOf[$num1] + $this->indexOf[$num2] + $this->blockSize - $this->indexOf[$den]
                        )
                    ]
                );
            }
        }

        if (null !== $erasures) {
            if (count($erasures) < $count) {
                $erasures->setSize($count);
            }

            for ($i = 0; $i < $count; $i++) {
                $erasures[$i] = $loc[$i];
            }
        }

        return $count;
    }

func HandleCD(server *Server, sender *player.Player) {
	pkt := new(packet.ClientStatuses)
	pkt.ReadFrom(sender.Conn)

	switch pkt.Payload {
	case 0:
		server.HandleLogin(sender)
	case 1:
	default:
		log.Println("Weird packet 0xCB payload:", pkt.Payload)
		r := packet.Disconnect{"Weird packet 0xCB payload"}
		r.WriteTo(sender.Conn)
	}
}

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


Question: // New returns a new Bee instance configured with the supplied options.

func (factory *FacebookBeeFactory) New(name, description string, options bees.BeeOptions) bees.BeeInterface {
	bee := FacebookBee{
		Bee: bees.NewBee(name, factory.ID(), description, options),
	}
	bee.ReloadOptions(options)

	return &bee
}

def hvac_autosize(self):

        for i in range(len(self.BEM)):
            if self.is_near_zero(self.autosize) == False:
                self.BEM[i].building.coolCap = 9999.
                self.BEM[i].building.heatCap = 9999.

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


Question:
:class:`~zhmcclient.StorageGroupManager`:
          Manager object for the Storage Groups in scope of this Console.

def storage_groups(self):

        # We do here some lazy loading.
        if not self._storage_groups:
            self._storage_groups = StorageGroupManager(self)
        return self._storage_groups

func (bs *blobStatter) Stat(ctx context.Context, dgst digest.Digest) (distribution.Descriptor, error) {
	path, err := pathFor(blobDataPathSpec{
		digest: dgst,
	})

	if err != nil {
		return distribution.Descriptor{}, err
	}

	fi, err := bs.driver.Stat(ctx, path)
	if err != nil {
		switch err := err.(type) {
		case driver.PathNotFoundError:
			return distribution.Descriptor{}, distribution.ErrBlobUnknown
		default:
			return distribution.Descriptor{}, err
		}
	}

	if fi.IsDir() {
		// NOTE(stevvooe): This represents a corruption situation. Somehow, we
		// calculated a blob path and then detected a directory. We log the
		// error and then error on the side of not knowing about the blob.
		dcontext.GetLogger(ctx).Warnf("blob path should not be a directory: %q", path)
		return distribution.Descriptor{}, distribution.ErrBlobUnknown
	}

	// TODO(stevvooe): Add method to resolve the mediatype. We can store and
	// cache a "global" media type for the blob, even if a specific repo has a
	// mediatype that overrides the main one.

	return distribution.Descriptor{
		Size: fi.Size(),

		// NOTE(stevvooe): The central blob store firewalls media types from
		// other users. The caller should look this up and override the value
		// for the specific repository.
		MediaType: "application/octet-stream",
		Digest:    dgst,
	}, nil
}

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


Question: Get one or more configuration parameters.

def config_get(self, pattern='*'):

        result = {}
        for name, value in self.redis_config.items():
            if fnmatch.fnmatch(name, pattern):
                try:
                    result[name] = int(value)
                except ValueError:
                    result[name] = value
        return result

def get_config(self):

        # Fill this dict with config data
        return {
            'hash_name': self.hash_name,
            'dim': self.dim,
            'projection_count': self.projection_count,
            'normals': self.normals,
            'tree_root': self.tree_root,
            'minimum_result_size': self.minimum_result_size
        }

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


Question:
Decode long from byte array at offset

@param ba byte array
@param offset Offset
@return long value

public void encodeData(AsnOutputStream asnOs) throws MAPException {

        if (this.ssCode == null)
            throw new MAPException("Error while encoding " + _PrimitiveName + ": ssCode required.");

        if (this.callBarringFeatureList == null)
            throw new MAPException("Error while encoding " + _PrimitiveName + ": callBarringFeatureList required.");

        if (this.callBarringFeatureList.size() < 1 || this.callBarringFeatureList.size() > 32) {
            throw new MAPException("Error while encoding " + _PrimitiveName
                    + ": Parameter callBarringFeatureList size must be from 1 to 32, found: "
                    + this.callBarringFeatureList.size());
        }

        try {

            ((SSCodeImpl) this.ssCode).encodeAll(asnOs);

            asnOs.writeTag(Tag.CLASS_UNIVERSAL, false, Tag.SEQUENCE);
            int pos = asnOs.StartContentDefiniteLength();
            for (ExtCallBarringFeature featureItem : this.callBarringFeatureList) {
                ((ExtCallBarringFeatureImpl) featureItem).encodeAll(asnOs);
            }
            asnOs.FinalizeContent(pos);

            if (this.extensionContainer != null)
                ((MAPExtensionContainerImpl) this.extensionContainer).encodeAll(asnOs);
        } catch (AsnException e) {
            throw new MAPException("AsnException when encoding " + _PrimitiveName + ": " + e.getMessage(), e);
        }
    }

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 *BootstrapActionConfig) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "BootstrapActionConfig"}
	if s.Name == nil {
		invalidParams.Add(request.NewErrParamRequired("Name"))
	}
	if s.ScriptBootstrapAction == nil {
		invalidParams.Add(request.NewErrParamRequired("ScriptBootstrapAction"))
	}
	if s.ScriptBootstrapAction != nil {
		if err := s.ScriptBootstrapAction.Validate(); err != nil {
			invalidParams.AddNested("ScriptBootstrapAction", err.(request.ErrInvalidParams))
		}
	}

	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:
Dispatch selected event

@param selectedKeySet

public final void dispatchEvent(Set<SelectionKey> selectedKeySet) {
    Iterator<SelectionKey> it = selectedKeySet.iterator();
    boolean skipOpRead = false;
    while (it.hasNext()) {
      SelectionKey key = it.next();
      it.remove();
      if (!key.isValid()) {
        if (key.attachment() != null) {
          controller.closeSelectionKey(key);
        } else {
          key.cancel();
        }
        continue;
      }
      try {
        if (key.isValid() && key.isAcceptable()) {
          controller.onAccept(key);
          continue;
        }
        if (key.isValid() && (key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {
          // Remove write interest
          key.interestOps(key.interestOps() & ~SelectionKey.OP_WRITE);
          controller.onWrite(key);
          if (!controller.isHandleReadWriteConcurrently()) {
            skipOpRead = true;
          }
        }
        if (!skipOpRead && key.isValid()
            && (key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {
          key.interestOps(key.interestOps() & ~SelectionKey.OP_READ);
          if (!controller.getStatistics().isReceiveOverFlow()) {
            // Remove read interest
            controller.onRead(key);
          } else {
            key.interestOps(key.interestOps() | SelectionKey.OP_READ);
          }

        }
        if ((key.readyOps() & SelectionKey.OP_CONNECT) == SelectionKey.OP_CONNECT) {
          controller.onConnect(key);
        }

      } catch (CancelledKeyException e) {
        // ignore
      } catch (RejectedExecutionException e) {

        if (key.attachment() instanceof AbstractNioSession) {
          ((AbstractNioSession) key.attachment()).onException(e);
        }
        controller.notifyException(e);
        if (selector.isOpen()) {
          continue;
        } else {
          break;
        }
      } catch (Exception e) {
        if (key.attachment() instanceof AbstractNioSession) {
          ((AbstractNioSession) key.attachment()).onException(e);
        }
        controller.closeSelectionKey(key);
        controller.notifyException(e);
        log.error("Reactor dispatch events error", e);
        if (selector.isOpen()) {
          continue;
        } else {
          break;
        }
      }
    }
  }

public function set(KeyInterface $key, $value, $ttlInMillis)
    {
        return $this->connection->psetex(
            $key,
            $ttlInMillis,
            serialize($value)
        );
    }

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


Question:
Deactivates the given user

@param User $user The user to deactivate
@return void
@api

public function deactivateUser(User $user)
    {
        /** @var Account $account */
        foreach ($user->getAccounts() as $account) {
            $account->setExpirationDate($this->now);
            $this->accountRepository->update($account);
        }
        $this->emitUserDeactivated($user);
    }

private function parse($body)
    {
        $result = array();
        $data = json_decode($body);

        $response = is_array($data->response) ? new \stdClass : $data->response;
        if (null == $response) {
            $response = $data;
        }
        $response->errors = $data->errors;
        $response->test = isset($data->test) ? $data->test : $response->test;

        if ($data->successful == true) {
            if ((isset($response->authorized)
                && $response->authorized == true)
                || (isset($response->id)
                && $response->id !== null)
            ) {
                $response->authorization_id = isset($response->id)
                    ? $response->id
                    : $response->token;
            } else {
                $response->authorization_id = null;
            }

            $response->success = true;
        } else {
            $response->success = false;
            $response->authorization_id = null;
        }

        $response->message = isset($response->message) ? $response->message : $data->errors;

        return (array) $response;

    }

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


Question: qualifier: includeSet | extraPropertySet | KW_CLOSED

def visitQualifier(self, ctx: ShExDocParser.QualifierContext):

        if ctx.includeSet():
            if self.shape.inherit is None:
                self.shape.inherit = []
            self.shape.inherit += [self.context.tripleexprlabel_to_iriref(tel)
                                   for tel in ctx.includeSet().tripleExpressionLabel()]
        elif ctx.extraPropertySet():
            if self.shape.extra is None:
                self.shape.extra = []
            self.shape.extra += [self.context.predicate_to_IRI(p) for p in ctx.extraPropertySet().predicate()]

        elif ctx.KW_CLOSED():
            self.shape.closed = True

@Override
    public void setParameters(Object[] params) throws CDKException {
        if (params.length != 1) throw new CDKException("ElementRule expects one parameters");

        if (!(params[0] == null || params[0] instanceof MolecularFormulaRange))
            throw new CDKException("The parameter must be of type MolecularFormulaExpand");

        mfRange = (MolecularFormulaRange) params[0];
    }

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


Question:
Adds a 'post_status' condition
@param  string $status
@return Query

public function status($status = null)
    {
        if (is_null($status)) {
            unset($this->filters['post_status']);
        } else {
            $this->filters['post_status'] = $status;
        }

        return $this;
    }

function(setting, value) {
        if (-1 === this._supportedPostParams.indexOf(setting)) {
            this.console.error('Parameter unsupported, may cause error:', setting);
        }
        this._reqParam[setting] = value;
        return this;
    }

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


Question: Collect values for a given web service operation input parameter.

def __process_parameter(self, param_name, param_type, ancestry=None):
        """"""
        assert self.active()
        param_optional = param_type.optional()
        has_argument, value = self.__get_param_value(param_name)
        if has_argument:
            self.__params_with_arguments.add(param_name)
        self.__update_context(ancestry)
        self.__stack[-1].process_parameter(param_optional, value is not None)
        self.__external_param_processor(param_name, param_type,
            self.__in_choice_context(), value)

public String getReqPar(final String name, final String def) {
    final String s = Util.checkNull(request.getParameter(name));

    if (s != null) {
      return s;
    }

    return def;
  }

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


Question:
Composes the config from the 3 sources that it may reside.
Precedence is 1. Arguments, 2. qnamakerrc and 3. env variables

@returns {Promise<*>}

async function composeConfig() {
    const {QNAMAKER_SUBSCRIPTION_KEY, QNAMAKER_HOSTNAME, QNAMAKER_ENDPOINTKEY, QNAMAKER_KBID} = process.env;
    const {subscriptionKey, hostname, endpointKey, kbId} = args;

    let qnamakerrcJson = {};
    let config;
    try {
        await fs.access(path.join(process.cwd(), '.qnamakerrc'), fs.R_OK);
        qnamakerrcJson = JSON.parse(await txtfile.read(path.join(process.cwd(), '.qnamakerrc')));
    } catch (e) {
        // Do nothing
    } finally {
        config = {
            subscriptionKey: (subscriptionKey || qnamakerrcJson.subscriptionKey || QNAMAKER_SUBSCRIPTION_KEY),
            hostname: (hostname || qnamakerrcJson.hostname || QNAMAKER_HOSTNAME),
            endpointKey: (endpointKey || qnamakerrcJson.endpointKey || QNAMAKER_ENDPOINTKEY),
            kbId: (kbId || qnamakerrcJson.kbId || QNAMAKER_KBID)
        };
    }
    return config;
}

def _parse_command_spec(self, spec, precmds):
        '''

        '''
        if 'pre_command' in spec:
            precmd_alias = spec['pre_command']
            try:
                precmd = precmds[precmd_alias]

                if self._blacklist_check(precmd):
                    raise RuntimeError("Command Blacklist: " + precmd)

                args = self._run_pre_command(precmd)
                logger.debug('Pre-command results: %s', args)

                expanded_specs = []
                for arg in args:
                    _spec = copy.copy(spec)
                    _spec['command'] = _spec['command'] + ' ' + arg
                    expanded_specs.append(_spec)
                return expanded_specs
            except LookupError:
                logger.debug('Pre-command %s not found. Skipping %s...',
                             precmd_alias, spec['command'])
                return []
        else:
            return [spec]

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


Question:
Sets the new address

@param \Aimeos\MW\View\Iface $view View object
@throws \Aimeos\Client\Html\Exception If an error occurs
@since 2016.05

protected function setAddress( \Aimeos\MW\View\Iface $view )
	{
		$address = null;
		$context = $this->getContext();
		$basketCtrl = \Aimeos\Controller\Frontend::create( $context, 'basket' );

		/** client/html/checkout/standard/address/delivery/disable-new
		 * Disables the option to enter a different delivery address for an order
		 *
		 * Besides the billing address, customers can usually enter a different
		 * delivery address as well. To suppress displaying the form fields for
		 * a delivery address, you can set this configuration option to "1".
		 *
		 * Until 2015-02, the configuration option was available as
		 * "client/html/common/address/delivery/disable-new" starting from 2014-03.
		 *
		 * @param boolean A value of "1" to disable, "0" enables the delivery address form
		 * @since 2015.02
		 * @category User
		 * @category Developer
		 * @see client/html/checkout/standard/address/delivery/salutations
		 * @see client/html/checkout/standard/address/delivery/mandatory
		 * @see client/html/checkout/standard/address/delivery/optional
		 * @see client/html/checkout/standard/address/delivery/hidden
		*/
		$disable = $view->config( 'client/html/checkout/standard/address/delivery/disable-new', false );
		$type = \Aimeos\MShop\Order\Item\Base\Address\Base::TYPE_DELIVERY;

		if( ( $option = $view->param( 'ca_deliveryoption', 'null' ) ) === 'null' && $disable === false ) // new address
		{
			$params = $view->param( 'ca_delivery', [] );

			if( ( $view->deliveryError = $this->checkFields( $params ) ) !== [] ) {
				throw new \Aimeos\Client\Html\Exception( sprintf( 'At least one delivery address part is missing or invalid' ) );
			}

			$basketCtrl->addAddress( $type, $params );
		}
		else if( ( $option = $view->param( 'ca_deliveryoption', 'null' ) ) !== '-1' ) // existing address
		{
			$params = $view->param( 'ca_delivery_' . $option, [] );

			if( !empty( $params ) && ( $view->deliveryError = $this->checkFields( $params ) ) !== [] ) {
				throw new \Aimeos\Client\Html\Exception( sprintf( 'At least one delivery address part is missing or invalid' ) );
			}

			$cntl = \Aimeos\Controller\Frontend::create( $context, 'customer' );

			if( ( $address = $cntl->uses( ['customer/address'] )->get()->getAddressItem( $option ) ) !== null )
			{
				$cntl->addAddressItem( $address->fromArray( $params ), $option )->store();
				$params = $address->toArray();
			}

			$basketCtrl->addAddress( $type, $params );
		}
		else
		{
			$basketCtrl->deleteAddress( $type );
		}
	}

def _exc_middleware_factory(app):

    @web.middleware
    async def middleware(request, handler):
        try:
            return await handler(request)
        except Exception as exc:
            for cls in type(exc).mro():
                if cls in app._error_handlers:
                    request.exception = exc
                    response = await app._error_handlers[cls](request)
                    return response
            raise

    return middleware

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


Question:
Render an intermediate representation of plain text

@param  string $xml Intermediate representation
@return string      Rendered result

protected function renderPlainText($xml)
	{
		// Remove the <t> and </t> tags
		$html = substr($xml, 3, -4);

		// Replace all
 with

		$html = str_replace('
', '
', $html);

		// Decode encoded characters from the Supplementary Multilingual Plane
		$html = $this->decodeSMP($html);

		return $html;
	}

def _rt_parse_execs(self, statement, element, mode, lineparser):
        """"""
        #This is the same deal as with _rt_parse_types() below.
        if mode == "insert":
            enew, start, end = self.xparser.parse_signature(statement, element, element)
            if enew is not None:
                enew.start, enew.end = lineparser.absolute_charindex(statement, start, end)
                enew.incomplete = True
                element.executables[enew.name.lower()] = enew
                lineparser.additions.append((enew, element))

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


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

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

	return response, nil
}

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

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

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


Question: // SetStatus sets the Status field's value.

func (s *Certificate) SetStatus(v string) *Certificate {
	s.Status = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question: // SignEncryptUpdate continues a multiple-part signing and encryption operation.

func (c *Ctx) SignEncryptUpdate(sh SessionHandle, part []byte) ([]byte, error) {
	var (
		enc    C.CK_BYTE_PTR
		enclen C.CK_ULONG
	)
	e := C.SignEncryptUpdate(c.ctx, C.CK_SESSION_HANDLE(sh), cMessage(part), C.CK_ULONG(len(part)), &enc, &enclen)
	if toError(e) != nil {
		return nil, toError(e)
	}
	h := C.GoBytes(unsafe.Pointer(enc), C.int(enclen))
	C.free(unsafe.Pointer(enc))
	return h, nil
}

public function composerUpdateHash()
    {
        $paths = $this->getPaths();
        $this->stopOnFail(true);
        $this->info('Updating Composer lock file');
        $command = $this->taskExec('composer')->dir($paths['root']);
        $command
            ->arg('update')
            ->option('lock')
            ->printOutput(true)
            ->run();
        $this->info('Composer lock file updated');
    }

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


Question: Renders dendrogram

def _render_dendrogram(dnd, ax, displacement):
    ''''''
    # set of unique colors that reflect the set of types of the neurites
    colors = set()

    for n, (indices, ctype) in enumerate(zip(dnd.groups, dnd.types)):

        # slice rectangles array for the current neurite
        group = dnd.data[indices[0]:indices[1]]

        if n > 0:
            # displace the neurites by half of their maximum x dimension
            # plus half of the previous neurite's maxmimum x dimension
            displacement += 0.5 * (dnd.dims[n - 1][0] + dnd.dims[n][0])

        # arrange the trees without overlapping with each other
        group += (displacement, 0.)

        # create the polygonal collection of the dendrogram
        # segments
        _generate_collection(group, ax, ctype, colors)

    soma_square = dnd.soma

    if soma_square is not None:

        _generate_collection((soma_square + (displacement / 2., 0.),), ax, NeuriteType.soma, colors)
        ax.plot((displacement / 2., displacement), (0., 0.), color='k')
        ax.plot((0., displacement / 2.), (0., 0.), color='k')

    return displacement

def walk_target_deps_topological_order(self, target: Target):
        """"""
        all_deps = get_descendants(self.target_graph, target.name)
        for dep_name in topological_sort(self.target_graph):
            if dep_name in all_deps:
                yield self.targets[dep_name]

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


Question: Fetches the tasks for either the profile, or the passed task

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

            return;
        }

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

def instagram_user_recent_media(parser, token):

    try:
        tagname, username = token.split_contents()

        return InstagramUserRecentMediaNode(username)
    except ValueError:
        raise template.TemplateSyntaxError(
            "%r tag requires a single argument" % token.contents.split()[0]
        )

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


Question:
Mark as read

@link https://developer.github.com/v3/activity/notifications/#mark-as-read

@param string $lastReadAt

@return array

public function markAsRead(string $lastReadAt = 'now'): array
    {
        return $this->getApi()->request($this->getApi()->sprintf('/notifications?:args',
            http_build_query(['last_read_at' => (new DateTime($lastReadAt))->format(DateTime::ATOM)])),
            Request::METHOD_PUT);
    }

public function addAction( $action, $callback, $priority = 10 )
    {
        if ( !isset( $this->actions[ $action ] ) )
        {
            $this->actions[ $action ] = array();
        }

        $this->actions[ $action ][] = array(
            'priority' => $priority,
            'callback' => $callback,
        );

        if ( 1 < count( $this->actions[ $action ] ) )
        {
            usort( $this->actions[ $action ], array( $this, '_sortByPriority' ) );
        }

        if ( $this->debug )
        {
            echo PHP_EOL . '+ACTION: ' . $action . ' -> '
                    . $this->_serializeCallback( $callback )
                    . ' + Priority: ' . $priority
                    . PHP_EOL;
        }
    }

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


Question:
Check if string is not empty

@param string $string The string

@return bool

public static function isNotEmpty($string)
    {
        if (!self::isValid($string) &&
            null !== $string
        ) {
            return false;
        }

        return (!self::isEmpty($string));
    }

public static void isBlankThen(String str, Consumer<String> consumer) {
        if (isBlank(str)) {
            consumer.accept(str);
        }
    }

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


Question:
Produce the OperableTrigger.

@return a OperableTrigger that meets the specifications of the builder.

public OperableTrigger build() {

    //    if (scheduleBuilder == null) {
    //      scheduleBuilder = SimpleScheduleBuilder.simpleScheduleBuilder();
    //    }

    // get a trigger impl. but without the meta data filled in yet
    //    OperableTrigger operableTrigger = operableTrigger;

    operableTrigger = instantiate();

    // fill in metadata
    operableTrigger.setCalendarName(calendarName);
    operableTrigger.setDescription(description);
    operableTrigger.setEndTime(endTime);
    if (name == null) {
      name = UUID.randomUUID().toString();
    }
    operableTrigger.setName(name);
    if (jobName != null) {
      operableTrigger.setJobName(jobName);
    }
    operableTrigger.setPriority(priority);
    operableTrigger.setStartTime(startTime);

    if (!jobDataMap.isEmpty()) {
      operableTrigger.setJobDataMap(jobDataMap);
    }

    return operableTrigger;
  }

public function isTrustedTag($tag_name, $compiler)
    {
        // check for internal always required tags
        if (in_array($tag_name, array('assign', 'call', 'private_filter', 'private_block_plugin', 'private_function_plugin', 'private_object_block_function',
                    'private_object_function', 'private_registered_function', 'private_registered_block', 'private_special_variable', 'private_print_expression', 'private_modifier'))) {
            return true;
        }
        // check security settings
        if (empty($this->allowed_tags)) {
            if (empty($this->disabled_tags) || !in_array($tag_name, $this->disabled_tags)) {
                return true;
            } else {
                $compiler->trigger_template_error("tag '{$tag_name}' disabled by security setting", $compiler->lex->taglineno);
            }
        } elseif (in_array($tag_name, $this->allowed_tags) && !in_array($tag_name, $this->disabled_tags)) {
            return true;
        } else {
            $compiler->trigger_template_error("tag '{$tag_name}' not allowed by security setting", $compiler->lex->taglineno);
        }

        return false; // should not, but who knows what happens to the compiler in the future?
    }

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