Question:
处理代码调用跟踪
@param \Imi\Log\Record $record
@return string

public function parseTrace(\Imi\Log\Record $record)
    {
        $result = [];
        $trace = $record->getTrace();
        if($this->traceMinimum)
        {
            $trace = App::getBean(TraceMinimum::class)->parse($trace);
        }
        foreach($trace as $index => $vars)
        {
            $vars['call'] = $this->getTraceCall($vars);
            $vars['index'] = $index;
            $line = $this->traceFormat;
            foreach($vars as $name => $value)
            {
                if(is_scalar($value))
                {
                    $line = str_replace('{' . $name . '}', (string)$value, $line);
                }
            }
            $result[] = $line;
        }
        return implode(PHP_EOL, $result);
    }

public void handleMessage(
    MessageItem msg,
    TransactionCommon transaction,
    SIBUuid8 sourceMEUuid)
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "handleMessage", new Object[]{msg, transaction, sourceMEUuid});

    SIErrorException e = new SIErrorException(
      nls.getFormattedMessage(
        "INTERNAL_MESSAGING_ERROR_CWSIP0001",
        new Object[] {
          "com.ibm.ws.sib.processor.impl.DurableInputHandler",
          "1:143:1.52.1.1" },
        null));

    // FFDC
    FFDCFilter.processException(
      e,
      "com.ibm.ws.sib.processor.impl.DurableInputHandler.handleMessage",
      "1:150:1.52.1.1",
      this);

    SibTr.exception(tc, e);

    SibTr.error(tc, "INTERNAL_MESSAGING_ERROR_CWSIP0001",
      new Object[] {
        "com.ibm.ws.sib.processor.impl.DurableInputHandler",
        "1:158:1.52.1.1" });

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "handleMessage", e);

    throw e;
  }

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


Question:
Name of the pred tensor.

optional string pred_name = 2;

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

def proxy_label_for(label: str) -> str:

        label_java = _VertexLabel(label).unwrap()
        proxy_label_java = k.jvm_view().SequenceBuilder.proxyLabelFor(label_java)
        return proxy_label_java.getQualifiedName()

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


Question:
Creates a Temporal object filling the missing fields of the provided time with default values.
@param target the temporal object to be converted
@param defaultZoneId the default value for ZoneId
@return a Temporal object

public static ChronoZonedDateTime zonedTime(final Object target, final ZoneId defaultZoneId) {
        Validate.notNull(target, "Target cannot be null");
        Validate.notNull(defaultZoneId, "ZoneId cannot be null");
        if (target instanceof Instant) {
            return ZonedDateTime.ofInstant((Instant) target, defaultZoneId);
        } else if (target instanceof LocalDate) {
            return ZonedDateTime.of((LocalDate) target, LocalTime.MIDNIGHT, defaultZoneId);
        } else if (target instanceof LocalDateTime) {
            return ZonedDateTime.of((LocalDateTime) target, defaultZoneId);
        } else if (target instanceof LocalTime) {
            return ZonedDateTime.of(LocalDate.now(), (LocalTime) target, defaultZoneId);
        } else if (target instanceof OffsetDateTime) {
            return ((OffsetDateTime) target).toZonedDateTime();
        } else if (target instanceof OffsetTime) {
            LocalTime localTime = ((OffsetTime) target).toLocalTime();
            return ZonedDateTime.of(LocalDate.now(), localTime, defaultZoneId);
        } else if (target instanceof Year) {
            LocalDate localDate = ((Year) target).atDay(1);
            return ZonedDateTime.of(localDate, LocalTime.MIDNIGHT, defaultZoneId);
        } else if (target instanceof YearMonth) {
            LocalDate localDate = ((YearMonth) target).atDay(1);
            return ZonedDateTime.of(localDate, LocalTime.MIDNIGHT, defaultZoneId);
        } else if (target instanceof ZonedDateTime) {
            return (ChronoZonedDateTime) target;
        } else {
            throw new IllegalArgumentException(
                "Cannot format object of class \"" + target.getClass().getName() + "\" as a date");
        }
    }

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

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

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

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

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

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

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

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

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

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

    return null;
  }

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


Question:
@param string $method
@param string $uri
@param mixed $body
@param array $query
@param array $headers
@param array $options

@return PromiseInterface

public function sendAsync($method, $uri, $body = null, array $query = [], array $headers = [], array $options = [])
    {
        try {
            $this->validateMethod($method);
        } catch (\InvalidArgumentException $e) {
            return rejection_for($e);
        }

        $query = array_merge($this->getDefaultQuery(), $query);
        $headers = array_merge($this->getDefaultHeaders(), $headers);

        return $this->client->sendAsync($method, $uri, $body, $query, $headers, $options)->then(
            function (ResponseInterface $response) {
                $this->lastResponse = $response;

                $this->validateResponse($this->lastResponse);

                return $this->lastResponse;
            }
        );
    }

public Observable<ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders>> listWithServiceResponseAsync(final PoolListOptions poolListOptions) {
        return listSinglePageAsync(poolListOptions)
            .concatMap(new Func1<ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders>, Observable<ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders>>>() {
                @Override
                public Observable<ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders>> call(ServiceResponseWithHeaders<Page<CloudPool>, PoolListHeaders> page) {
                    String nextPageLink = page.body().nextPageLink();
                    if (nextPageLink == null) {
                        return Observable.just(page);
                    }
                    PoolListNextOptions poolListNextOptions = null;
                    if (poolListOptions != null) {
                        poolListNextOptions = new PoolListNextOptions();
                        poolListNextOptions.withClientRequestId(poolListOptions.clientRequestId());
                        poolListNextOptions.withReturnClientRequestId(poolListOptions.returnClientRequestId());
                        poolListNextOptions.withOcpDate(poolListOptions.ocpDate());
                    }
                    return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink, poolListNextOptions));
                }
            });
    }

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


Question:
Counts the number of bytes the string will have when coded; utf-16be if non-ascii characters are present.
@param string $val The string value
@return integer The length of the coded string in bytes

protected static function binaryStrlen($val)
    {
        for ($i=0; $i<strlen($val); ++$i) {
            if (ord($val{$i}) >= 128) {
                $val = self::convertCharset($val, 'UTF-8', 'UTF-16BE');
                return strlen($val);
            }
        }

        return strlen($val);
    }

protected function acceptString( $until = ';' )
    {
        if ( '"' == $this->buffer[0] )
        {
            $matches        = array();
            $this->buffer   = substr( $this->buffer, 1 );

            if ( preg_match( '/^(.*?[^\\\\])"/', $this->buffer, $matches ) )
            {
                $result         = $matches[1];
                $this->buffer   = substr( $this->buffer, strlen( $matches[0] ) );
            }
            else
            {
                $result         = $this->buffer;
                $this->buffer   = '';
            }

            $result = str_replace(
                '\\\\', '\\',
                preg_replace_callback(
                    '/\\\\([0-9A-F]{0,6})/', function ( $matches ) {
                        return hex2bin( $matches[1] );
                    }, str_replace( '\\"', '"', $result )
                )
            );

            $this->buffer = preg_replace(
                '/^[^' . preg_quote( $until ) . ']+/',
                '', $this->buffer
            );
        }
        else
        {
            list( $result, $this->buffer ) = preg_split(
                '/[' . preg_quote( $until ) . ']/',
                $this->buffer, 2
            );
        }

        return $result;
    }

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


Question: Return the list of table names in the database

def tables(self):
        """"""
        tables = []
        self.cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
        for table_info in self.cursor.fetchall():
            if table_info[0] != 'sqlite_sequence':
                tables.append(table_info[0])
        return tables

public function getTables($which_connection='')
    {
        if ($which_connection == '') {
            $which_connection=$this->default_db;
        }
        $conn = $this->connections[$which_connection];

        return $conn->MetaTables();
    }

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


Question: Context manager that yields an instance of ``Consumer``.

def create_consumer(self):
        """"""
        with self.connection_pool.acquire(block=True) as conn:
            yield self.consumer(conn)

def get_maintainer(self):
        # type: () -> hdx.data.user.User

        return hdx.data.user.User.read_from_hdx(self.data['maintainer'], configuration=self.configuration)

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


Question:
Show the form for editing the specified resource.

@param int $id

@return \Illuminate\Http\Response

public function edit($id)
    {
        $user = \App\User::findOrfail($id);
        $roles = Role::all()->pluck('name');
        $permissions = Permission::all()->pluck('name');
        $userRoles = $user->roles;
        $userPermissions = $user->permissions;

        return view('scaffold-interface.users.edit', compact('user', 'roles', 'permissions', 'userRoles', 'userPermissions'));
    }

def new
      @parameter = Parameter.new

      respond_to do |format|
        format.html # new.html.erb
        format.json { render json: @parameter }
      end
    end

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


Question:
For Task overall stock display
        顯示資訊樣式之一，兩行資訊。

def Task_display(self):

    re = """%(stock_name)s %(stock_no)s %(stock_date)s
Today: %(stock_price)s %(stock_range)s
=-=-=-=""" % {
        'stock_name': unicode(self.stock_name),
        'stock_no': unicode(self.stock_no),
        'stock_date': unicode(self.data_date[-1]),
        'stock_price': unicode(self.raw_data[-1]),
        'stock_range': unicode(self.stock_range[-1]),
      }
    return re

def stack config={}, &block
      s = WsStack.new config
      _configure s
      @_ws_active << s
      yield_or_eval &block if block_given?
      @_ws_active.pop

      # ---- stack is finished now
      last = @_ws_active.last
      if last
        case last
        when WsStack
        when WsFlow
          last[:col] += last[:item_width] || 0
          # this tries to set height of outer flow based on highest row
          # printed, however that does not account for height of object,
          # so user should give a height to the flow.
          last[:height] = s[:row] if s[:row] > (last[:height]||0)
          $log.debug "XXX: STACK setting col to #{s[:col]} "
        end
      end

    end

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


private String fixName(String name) {
		return name.replace(HibernateLayerUtil.XPATH_SEPARATOR, HibernateLayerUtil.SEPARATOR);
	}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        G2.dispose();
    }

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


Question:
Split the hash into its calculated hash and salt.

@param string $hash The hash to split.
@return string[] An array in the form [$hash, $hashFunc, $salt].

private function splitHash($hash) {
        $parts = @unserialize($hash, ['allowed_classes' => false]);

        if (!is_array($parts)) {
            $result = ['', '', ''];
        } else {
            $parts += ['hash' => '', 'hashFunc' => '', 'salt' => ''];

            if (!$parts['hashFunc']) {
                switch (strlen($parts['hash'])) {
                    //xf11, XenForo_Authentication_Core11
                    case 32:
                        $parts['hashFunc'] = 'md5';
                        break;
                    case 40:
                        $parts['hashFunc'] = 'sha1';
                        break;
                    //xf12, XenForo_Authentication_Core12
                    default:
                        $parts['hashFunc'] = 'crypt';
                        break;
                }
            }

            $result = [$parts['hash'], $parts['hashFunc'], $parts['salt']];
        }
        return $result;
    }

private function unparseUrl($data)
    {
        $scheme = isset($data['scheme']) ? $data['scheme'] . '://' : '';
        $host = isset($data['host']) ? $data['host'] : '';
        $port = isset($data['port']) ? ':' . $data['port'] : '';
        $user = isset($data['user']) ? $data['user'] : '';
        $pass = isset($data['pass']) ? ':' . $data['pass'] : '';
        $pass = ($user || $pass) ? "$pass@" : '';
        $path = isset($data['path']) ? $data['path'] : '';
        $query = isset($data['query']) ? '?' . $data['query'] : '';
        $fragment = isset($data['fragment']) ? '#' . $data['fragment'] : '';

        return "$scheme$user$pass$host$port$path$query$fragment";
    }

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


Question: Generate row ids for all rows

def all_row_ids(data_batch):

    all_users = mx.nd.arange(0, MOVIELENS['max_user'], dtype='int64')
    all_movies = mx.nd.arange(0, MOVIELENS['max_movie'], dtype='int64')
    return {'user_weight': all_users, 'item_weight': all_movies}

function NextRecordSet()
	{
		if (!sqlsrv_next_result($this->_queryID)) return false;
		$this->_inited = false;
		$this->bind = false;
		$this->_currentRow = -1;
		$this->Init();
		return true;
	}

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


Question:
``PackGZip`` - Concats the build output of all params and gzips the
    resulting data, returning a char array.

    Example: ::

        char data[0x100]<pack=PackGZip, ...>;

def pack_gzip(params, ctxt, scope, stream, coord):

    if len(params) == 0:
        raise errors.InvalidArguments(coord, "{} args".format(len(params)), "at least one argument")

    built = utils.binary("")
    for param in params:
        if isinstance(param, pfp.fields.Field):
            built += param._pfp__build()
        else:
            built += param

    return zlib.compress(built)

func assemblePostBody(req Request) string {
	// Make a list of key/value pairs and sort them by key.
	kvPairs := keyValueList{}
	for key, val := range req {
		kvPairs = append(kvPairs, keyValuePair{key, val})
	}

	sort.Sort(kvPairs)

	// Assemble the appropriate parts.
	parts := make([]string, len(kvPairs))
	for i, kvPair := range kvPairs {
		parts[i] = url.QueryEscape(kvPair.Key) + "=" + url.QueryEscape(kvPair.Val)
	}

	result := strings.Join(parts, "&")

	// Amazon disagrees with Go about what to do with spaces; Go uses '+'
	// characters and Amazon wants "%20". Transform '+' characters appropriately.
	// This is safe because actual '+' characters have already been encoded as
	// "%2B".
	result = strings.Replace(result, "+", "%20", -1)

	return result
}

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


Question:
Send an event to all the client listening for notifications

        :param action: Action name
        :param event: Event to send
        :param kwargs: Add this meta to the notification (project_id for example)

def emit(self, action, event, **kwargs):

        for listener in self._listeners:
            listener.put_nowait((action, event, kwargs))

public function groupQuickJoin(GetResponseEvent $event) {

    // First check if the current route is the group canonical.
    $routeMatch = $this->currentRoute->getRouteName();
    // Not group canonical, then we leave.
    if ($routeMatch != 'entity.group.join') {
      return;
    }

    // Fetch the group parameter and check if's an actual group.
    $group = $this->currentRoute->getParameter('group');
    // Not group, then we leave.
    if (!$group instanceof Group) {
      return;
    }

    // Fetch the settings.
    $settings = $this->configFactory->get('social_group_quickjoin.settings');

    // Check if the feature enabled.
    if ($settings->get('social_group_quickjoin_enabled') == FALSE) {
      return;
    }

    // Check if the current group type is enabled.
    if ($settings->get('social_group_quickjoin_' . $group->getGroupType()->id()) == FALSE) {
      return;
    }

    // Create quickjoin URL from route.
    $url = Url::fromRoute('social_group_quickjoin.quickjoin_group', [
      'group' => $group->id(),
    ])->toString();

    // Redirect to quickjoin.
    $event->setResponse(new RedirectResponse($url));
  }

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


Question:
// String() converts the error into a human-readable, logfmt-compliant string.
// See http://godoc.org/github.com/kr/logfmt for details on logfmt formatting.

func (e *UnexpectedResponseError) String() string {
	return fmt.Sprintf("UnexpectedResponseError URL=%s ExpectedOneOf=%#v Got=%d Error: %s", e.URL, e.Expected, e.Actual, string(e.Data))
}

func (logs *Logs) Fatalf(code int, format string, v ...interface{}) {
	logs.allf(format, v...)
	logs.Flush()
	os.Exit(code)
}

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


Question:
All entries.

@return array

public function all() {
        $size = $this->maxPageSize();

        $firstPageResponse = $this->request( $this->createPaginatedRequestQuery( 0, $size ) );
        $header_values = $firstPageResponse->getResponse()->getHeader('X-Result-Total');
        $total = array_shift($header_values);

        $result = $firstPageResponse->json();

        if( $total <= $size ) {
            return $result;
        }

        $requests = [];
        for( $page = 1; $page < ceil( $total / $size ); $page++ ) {
            $requests[] = $this->createPaginatedRequestQuery( $page, $size );
        }

        $responses = $this->requestMany( $requests );

        foreach( $responses as $response ) {
            $result = array_merge( $result, $response->json() );
        }

        return $result;
    }

public function walk($callback, $output = null)
    {
        if ($output === null) {
            $output = clone $this;
            $output->exchangeArray([]);
        } elseif (is_string($output) and class_exists($output)) {
            $output = new $output();
        }

        foreach ($this as $key => $value) {
            $output[$key] = $callback($value, $key);
        }

        return $output;
    }

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


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

public JvmDeclaredType getImportedType()
	{
		if (importedType != null && importedType.eIsProxy())
		{
			InternalEObject oldImportedType = (InternalEObject)importedType;
			importedType = (JvmDeclaredType)eResolveProxy(oldImportedType);
			if (importedType != oldImportedType)
			{
				if (eNotificationRequired())
					eNotify(new ENotificationImpl(this, Notification.RESOLVE, XtypePackage.XIMPORT_DECLARATION__IMPORTED_TYPE, oldImportedType, importedType));
			}
		}
		return importedType;
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

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


Question:
// OnFirstStartup adds fn to the list of callback functions to execute
// when the server is about to be started NOT as part of a restart.

func (c *Controller) OnFirstStartup(fn func() error) {
	c.instance.OnFirstStartup = append(c.instance.OnFirstStartup, fn)
}

func (p *Project) Up(ctx context.Context, options options.Up, services ...string) error {
	if err := p.initialize(ctx); err != nil {
		return err
	}
	return p.perform(events.ProjectUpStart, events.ProjectUpDone, services, wrapperAction(func(wrapper *serviceWrapper, wrappers map[string]*serviceWrapper) {
		wrapper.Do(wrappers, events.ServiceUpStart, events.ServiceUp, func(service Service) error {
			return service.Up(ctx, options)
		})
	}), func(service Service) error {
		return service.Create(ctx, options.Create)
	})
}

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


Question:
Check if user is running spaCy from a Jupyter notebook by detecting the
    IPython kernel. Mainly used for the displaCy visualizer.
    RETURNS (bool): True if in Jupyter, False if not.

def is_in_jupyter():

    # https://stackoverflow.com/a/39662359/6400719
    try:
        shell = get_ipython().__class__.__name__
        if shell == "ZMQInteractiveShell":
            return True  # Jupyter notebook or qtconsole
    except NameError:
        return False  # Probably standard Python interpreter
    return False

def _parse_lightgbm_simple_model(scope, model, inputs):
    '''

    '''
    this_operator = scope.declare_local_operator(_get_lightgbm_operator_name(type(model)), model)
    this_operator.inputs = inputs

    if type(model) in lightgbm_classifier_list:
        # For classifiers, we may have two outputs, one for label and the other one for probabilities of all classes.
        # Notice that their types here are not necessarily correct and they will be fixed in shape inference phase
        label_variable = scope.declare_local_variable('label', FloatTensorType())
        probability_map_variable = scope.declare_local_variable('probabilities', FloatTensorType())
        this_operator.outputs.append(label_variable)
        this_operator.outputs.append(probability_map_variable)
    else:
        # We assume that all scikit-learn operator can only produce a single float tensor.
        variable = scope.declare_local_variable('variable', FloatTensorType())
        this_operator.outputs.append(variable)
    return this_operator.outputs

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


Question:
Parse the data

        :param data: the data (may be None)

def _parse_data(self, data, charset):

        return self._decode_data(data, charset) if data else u''

private function getParam(string $name, string $default = null): ?string
	{
		return $this->request->getPost($name, $default);
	}

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


Question:
Adds the specified Filter to the composition of Filters joined using the AND operator.

@param filter the Filter to add to the composition joined using the AND operator.
@return this FilterBuilder instance.
@see org.cp.elements.lang.Filter

public FilterBuilder<T> addWithAnd(final Filter<T> filter) {
    filterInstance = ComposableFilter.and(filterInstance, filter);
    return this;
  }

function (selector) {
        var match = this.match;

        function compileNameFilter(name) {
          if (name) {
            name = name.toLowerCase();

            return function (item) {
              return name === '*' || item.type === name;
            };
          }
        }

        function compileIdFilter(id) {
          if (id) {
            return function (item) {
              return item._name === id;
            };
          }
        }

        function compileClassesFilter(classes) {
          if (classes) {
            classes = classes.split('.');

            return function (item) {
              var i = classes.length;

              while (i--) {
                if (!item.classes.contains(classes[i])) {
                  return false;
                }
              }

              return true;
            };
          }
        }

        function compileAttrFilter(name, cmp, check) {
          if (name) {
            return function (item) {
              var value = item[name] ? item[name]() : '';

              return !cmp ? !!check :
                cmp === "=" ? value === check :
                  cmp === "*=" ? value.indexOf(check) >= 0 :
                    cmp === "~=" ? (" " + value + " ").indexOf(" " + check + " ") >= 0 :
                      cmp === "!=" ? value != check :
                        cmp === "^=" ? value.indexOf(check) === 0 :
                          cmp === "$=" ? value.substr(value.length - check.length) === check :
                            false;
            };
          }
        }

        function compilePsuedoFilter(name) {
          var notSelectors;

          if (name) {
            name = /(?:not\((.+)\))|(.+)/i.exec(name);

            if (!name[1]) {
              name = name[2];

              return function (item, index, length) {
                return name === 'first' ? index === 0 :
                  name === 'last' ? index === length - 1 :
                    name === 'even' ? index % 2 === 0 :
                      name === 'odd' ? index % 2 === 1 :
                        item[name] ? item[name]() :
                          false;
              };
            }

            // Compile not expression
            notSelectors = parseChunks(name[1], []);

            return function (item) {
              return !match(item, notSelectors);
            };
          }
        }

        function compile(selector, filters, direct) {
          var parts;

          function add(filter) {
            if (filter) {
              filters.push(filter);
            }
          }

          // Parse expression into parts
          parts = expression.exec(selector.replace(whiteSpace, ''));

          add(compileNameFilter(parts[1]));
          add(compileIdFilter(parts[2]));
          add(compileClassesFilter(parts[3]));
          add(compileAttrFilter(parts[4], parts[5], parts[6]));
          add(compilePsuedoFilter(parts[7]));

          // Mark the filter with pseudo for performance
          filters.pseudo = !!parts[7];
          filters.direct = direct;

          return filters;
        }

        // Parser logic based on Sizzle by John Resig
        function parseChunks(selector, selectors) {
          var parts = [], extra, matches, i;

          do {
            chunker.exec("");
            matches = chunker.exec(selector);

            if (matches) {
              selector = matches[3];
              parts.push(matches[1]);

              if (matches[2]) {
                extra = matches[3];
                break;
              }
            }
          } while (matches);

          if (extra) {
            parseChunks(extra, selectors);
          }

          selector = [];
          for (i = 0; i < parts.length; i++) {
            if (parts[i] != '>') {
              selector.push(compile(parts[i], [], parts[i - 1] === '>'));
            }
          }

          selectors.push(selector);

          return selectors;
        }

        this._selectors = parseChunks(selector, []);
      }

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


Question: -- END defaults --

def parent_class_inspector
      @parent_class_inspector ||= ParentClass.new(parsed_source:        class_introspector.parsed_source,
                                                  klasses_to_be_mocked: klasses_to_be_mocked,
                                                  mock_append_name:     mock_append_name).call
    end

func (ctx *context) PostValueInt64Default(name string, def int64) int64 {
	if v, err := ctx.PostValueInt64(name); err == nil {
		return v
	}

	return def
}

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


Question:
// setError returns an Error inidicating option o and the specified
// error while setting it to value.

func setError(o Option, value string, err error) *Error {
	return &Error{
		ErrorCode: Invalid,
		Name:      o.Name(),
		Parameter: value,
		Err:       err,
	}
}

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: Create a filename for the destination zip file.

def _resolve_file_name(source, destination):
        """"""
        number = 1
        if os.path.exists(os.path.join(destination, os.path.basename(source) + '.zip')):
            while True:
                zip_filename = os.path.join(destination, os.path.basename(source) + '_' + str(number) + '.zip')
                if not os.path.exists(zip_filename):
                    break
                number = number + 1
        else:
            zip_filename = os.path.join(destination, os.path.basename(source) + '.zip')
        return zip_filename

def add_tarball(self, tarball, package):
        """"""
        if tarball is None:
            logger.error(
                "No tarball found for %s: probably a renamed project?",
                package)
            return
        target_dir = os.path.join(self.root_directory, package)
        if not os.path.exists(target_dir):
            os.mkdir(target_dir)
            logger.info("Created %s", target_dir)
        logger.info("Copying tarball to %s", target_dir)
        shutil.copy(tarball, target_dir)

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


Question:
Check a permission for a given instance or field.  Raises an error if
    denied.

    :param instance: The instance to check
    :param field: The field name to check or None for instance
    :param permission: The permission to check

def check_permission(instance, field, permission):

    if not get_permission_test(instance, field, permission)(instance):
        raise PermissionDeniedError(permission, instance, instance, field)

public function index(): void
    {
        $calendars = $options = [];

        // ajax-based request for public calendars
        if ($this->request->is(['post', 'put', 'patch'])) {
            $data = $this->request->getData();

            if (!empty($data['public'])) {
                $options['conditions'] = ['is_public' => true];
            }
        }

        $calendars = $this->Calendars->getCalendars($options);

        $event = new Event((string)EventName::APP_CALENDARS_CHECK_PERMISSIONS(), $this, [
            'entities' => $calendars,
            'user' => $this->Auth->user(),
            'options' => []
        ]);

        $this->getEventManager()->dispatch($event);
        $calendars = $event->result;

        $this->set(compact('calendars'));
        $this->set('_serialize', 'calendars');
    }

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


Question:
Checks to see if unique.0 already exists

@param *string $objectKey

@return bool

public function exists($key, $value)
    {
        if (is_null($this->schema)) {
            throw SystemException::forNoSchema();
        }

        $search = $this
            ->resource
            ->search($this->schema->getName())
            ->addFilter($key . ' = %s', $value);

        return !!$search->getRow();
    }

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:
Helper method to build the POST request for the server.

@param path the path.
@param paramMap the parameters map.
@return the post object.

protected HttpPost generatePostRequest(final String path, final Map<String, Object> paramMap) {
        final HttpPost post = new HttpPost(buildUri(path));
        post.setEntity(new StringEntity(JSONObject.toJSONString(paramMap), ContentType.APPLICATION_JSON));
        return post;
    }

public static Map<String, Object> getRequestParameters(final Collection<String> attributes, final HttpServletRequest context) {
        return attributes.stream()
            .filter(a -> StringUtils.isNotBlank(context.getParameter(a)))
            .map(m -> {
                val values = context.getParameterValues(m);
                val valuesSet = new LinkedHashSet<Object>();
                if (values != null && values.length > 0) {
                    Arrays.stream(values).forEach(v -> valuesSet.addAll(Arrays.stream(v.split(" ")).collect(Collectors.toSet())));
                }
                return Pair.of(m, valuesSet);
            })
            .collect(Collectors.toMap(Pair::getKey, Pair::getValue));
    }

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


Question: insertion function for parameters to toolbar

function addParams(name,command,key,tag,emphasis)
		{
			var thisCssNo  = buttons.length+1;
			return buttons.push({name:name, cls:thisCssNo, command:command, key:key, tag:tag, emphasis:emphasis});
		}

func NewPlugin(name string, fn LogFunc) *Plugin {
	return &Plugin{name: name, logFn: fn}
}

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


Question:
Performs the actual projection of the source onto the canvas.

@param resource $source
@param resource $canvas
@return void

private function _projectSourceOnCanvas(&$source, &$canvas) {
        $srcX = 0;
        $srcY = 0;
        list($projectionWidth, $projectionHeight) = $this->_getProjectionSize();
        list($destX, $destY) = $this->_getLeftUpperCoordinateOnCanvas(
            $projectionWidth,
            $projectionHeight
        );
        imagecopyresampled(
            $canvas,
            $source,
            $destX,
            $destY,
            $srcX,
            $srcY,
            $projectionWidth,
            $projectionHeight,
            $this->_params['sourceWidth'],
            $this->_params['sourceHeight']
        );
    }

public function getAuthorizationUrl()
    {
        // Check for required items
        if (!$this->clientId) {
            throw new Exception('Client ID is required');
        }
        if (!$this->scope) {
            throw new Exception('Scope is required');
        }
        if (!$this->redirectUri) {
            throw new Exception('Redirect URI is required');
        }

        // Start building url (enpoint is the same for public and member APIs)
        $url  = 'https://';
        $url .= (!empty($this->environment)) ? $this->environment . '.' : '';
        $url .= self::HOSTNAME . '/' . self::AUTHORIZE;
        $url .= '?client_id='    . $this->clientId;
        $url .= '&scope='        . $this->scope;
        $url .= '&redirect_uri=' . urlencode($this->redirectUri);
        $url .= '&response_type=code';

        // Process non-required fields
        $url .= ($this->showLogin)          ? '&show_login=true'                    : '';
        $url .= (isset($this->state))       ? '&state=' . $this->state              : '';
        $url .= (isset($this->familyNames)) ? '&family_names=' . $this->familyNames : '';
        $url .= (isset($this->givenNames))  ? '&given_names=' . $this->givenNames   : '';
        $url .= (isset($this->email))       ? '&email=' . urlencode($this->email)   : '';

        return $url;
    }

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


Question:
[buildAdditionalHeadersString description]

@param array $headers headers

@return string

protected static function buildAdditionalHeadersString(&$headers)
    {
        $headersAddStr = '';
        $eol = "\r\n";
        foreach ($headers as $k => $v) {
            if (in_array($k, array('To','Subject','Body','Attachments'))) {
                continue;
            }
            if (empty($v)) {
                continue;
            }
            if ($k == 'From' && isset($_SERVER['WINDIR'])) {
                $fromAddress = preg_match('/<(.*?)>/', $v, $matches)
                    ? $matches[1]
                    : $v;
                // $this->debug->log('setting sendmail_from to '.$fromAddress);
                ini_set('sendmail_from', $fromAddress);
            }
            $headersAddStr .= $k.': '.$v.$eol;
        }
        $headersAddStr = substr($headersAddStr, 0, -strlen($eol));  // remove final $eol;
        return $headersAddStr;
    }

public function create($data)
    {
        $descriptor = new ReturnDescriptor($data->getName());
        $descriptor->setDescription($data->getDescription());
        $descriptor->setType(AssemblerAbstract::deduplicateTypes($data->getType()));

        return $descriptor;
    }

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


Question: Simple function that adds fixed colors depending on the class

def compute_colors_for_labels(self, labels):

        colors = labels[:, None] * self.palette
        colors = (colors % 255).numpy().astype("uint8")
        return colors

public void configureColor(AbstractButton button) {
        Assert.notNull(button, "button");
        if (foreground != null) {
        	button.setForeground(foreground);
        }
        if (background != null) {
        	button.setBackground(background);
        }
    }

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


Question: ******************** Resizing ******************************************

private void resizeStaticText() {
        double maxWidth = width * 0.28472222;
        double fontSize = height * 0.12631579;

        minValueText.setFont(Fonts.latoRegular(fontSize));
        if (minValueText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(minValueText, maxWidth, fontSize); }
        minValueText.relocate((width * 0.28472222) - minValueText.getLayoutBounds().getWidth(), height * 0.885);

        maxValueText.setFont(Fonts.latoRegular(fontSize));
        if (maxValueText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(maxValueText, maxWidth, fontSize); }
        maxValueText.relocate(width * 0.71527778, height * 0.885);

        maxWidth = width * 0.9;
        titleText.setFont(Fonts.latoRegular(fontSize));
        if (titleText.getLayoutBounds().getWidth() > maxWidth) { Helper.adjustTextSize(titleText, maxWidth, fontSize); }
        titleText.relocate((width - titleText.getLayoutBounds().getWidth()) * 0.5, height * 0.95);
    }

public function getThumbnailSizeList(): array
    {
        $thumbnails = [];
        $versions = Configure::read('ThumbnailVersions', []);
        foreach ($versions as $version => $definition) {
            $thumbnails[$version] = sprintf(
                '%s (%d x %d)',
                ucfirst($version),
                $definition['thumbnail']['width'],
                $definition['thumbnail']['height']
            );
        }

        return $thumbnails;
    }

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


Question: Initialize a QueryResult object from a json dictionary.

def _from_dict(cls, _dict):
        """"""
        args = {}
        xtra = _dict.copy()
        if 'id' in _dict:
            args['id'] = _dict.get('id')
            del xtra['id']
        if 'metadata' in _dict:
            args['metadata'] = _dict.get('metadata')
            del xtra['metadata']
        if 'collection_id' in _dict:
            args['collection_id'] = _dict.get('collection_id')
            del xtra['collection_id']
        if 'result_metadata' in _dict:
            args['result_metadata'] = QueryResultMetadata._from_dict(
                _dict.get('result_metadata'))
            del xtra['result_metadata']
        if 'title' in _dict:
            args['title'] = _dict.get('title')
            del xtra['title']
        args.update(xtra)
        return cls(**args)

@Override
	public <T> List<T> dynamicQuery(DynamicQuery dynamicQuery) {
		return cpDefinitionVirtualSettingPersistence.findWithDynamicQuery(dynamicQuery);
	}

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


Question: //AppendStreamSetColorFill  set the color fill

func (c *ContentObj) AppendStreamSetColorFill(r uint8, g uint8, b uint8) {
	var cache cacheContentColor
	cache.colorType = colorTypeFill
	cache.r = r
	cache.g = g
	cache.b = b
	c.listCache.append(&cache)
}

public function emitter(string $emitter, string $streamEmitter = null): void
    {
        $server = $this->server ?? $this->getServer();
        $server->setEmitter($emitter);

        $streamEmitter && $this->get('response')->setEmitter($streamEmitter);
    }

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


Question:
@param ContactSource  $contactSource
@param \DateTime|null $fromDate
@param \DateTime|null $toDate

@return mixed

protected function getEngagementData(
        ContactSource $contactSource,
        \DateTime $fromDate = null,
        \DateTime $toDate = null
    ) {
        $translator = $this->get('translator');

        if (null == $fromDate) {
            $fromDate = new \DateTime('first day of this month 00:00:00');
            $fromDate->modify('-6 months');
        }
        if (null == $toDate) {
            $toDate = new \DateTime();
        }

        $lineChart  = new LineChart(null, $fromDate, $toDate);
        $chartQuery = new ChartQuery($this->getDoctrine()->getConnection(), $fromDate, $toDate);

        /** @var ContactSourceModel $model */
        $model       = $this->getModel('contactSource');
        $engagements = $model->getEngagementCount($contactSource, $fromDate, $toDate, 'm', $chartQuery);
        $lineChart->setDataset(
            $translator->trans('mautic.contactSource.graph.line.all_engagements'),
            $engagements['byUnit']
        );

        $pointStats = $chartQuery->fetchTimeData(
            'contactSource_points_change_log',
            'date_added',
            ['contactSource_id' => $contactSource->getId()]
        );
        $lineChart->setDataset($translator->trans('mautic.contactSource.graph.line.points'), $pointStats);

        return $lineChart->render();
    }

func (sf *ScalarFunction) Eval(row chunk.Row) (d types.Datum, err error) {
	var (
		res    interface{}
		isNull bool
	)
	switch tp, evalType := sf.GetType(), sf.GetType().EvalType(); evalType {
	case types.ETInt:
		var intRes int64
		intRes, isNull, err = sf.EvalInt(sf.GetCtx(), row)
		if mysql.HasUnsignedFlag(tp.Flag) {
			res = uint64(intRes)
		} else {
			res = intRes
		}
	case types.ETReal:
		res, isNull, err = sf.EvalReal(sf.GetCtx(), row)
	case types.ETDecimal:
		res, isNull, err = sf.EvalDecimal(sf.GetCtx(), row)
	case types.ETDatetime, types.ETTimestamp:
		res, isNull, err = sf.EvalTime(sf.GetCtx(), row)
	case types.ETDuration:
		res, isNull, err = sf.EvalDuration(sf.GetCtx(), row)
	case types.ETJson:
		res, isNull, err = sf.EvalJSON(sf.GetCtx(), row)
	case types.ETString:
		res, isNull, err = sf.EvalString(sf.GetCtx(), row)
	}

	if isNull || err != nil {
		d.SetValue(nil)
		return d, err
	}
	d.SetValue(res)
	return
}

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


Question: Backport support for original codes.

def get(key, default=-1):
        """"""
        if isinstance(key, int):
            return LinkType(key)
        if key not in LinkType._member_map_:
            extend_enum(LinkType, key, default)
        return LinkType[key]

func (in *RollbackConfig) DeepCopy() *RollbackConfig {
	if in == nil {
		return nil
	}
	out := new(RollbackConfig)
	in.DeepCopyInto(out)
	return out
}

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


Question:
Returns a string containing a set of numbers with a fixed number of digits

@param digits number of digits in the final number
@return Random number as a string with a fixed length

public String getNumberText(final int digits) {
    String result = "";
    for (int i = 0; i < digits; i++) {
      result = result + random.nextInt(10);
    }
    return result;
  }

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

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

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

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

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

        $this->seed = $seed;
    }

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


Question:
提供的URL是否为Jar文件URL 判断依据为file协议且扩展名为.jar

@param url the URL to check
@return whether the URL has been identified as a JAR file URL
@since 4.1

public static boolean isJarFileURL(URL url) {
		return (URL_PROTOCOL_FILE.equals(url.getProtocol()) && //
				url.getPath().toLowerCase().endsWith(FileUtil.JAR_FILE_EXT));
	}

static public List<String> convertLoadpathVariable(Element element) {

        // Create the list of strings. Always add the empty string as this will
        // force the lookup routine to always include the "current" directory.
        LinkedList<String> filelist = new LinkedList<String>();
        filelist.add("");

        // If the argument is null (the variable doesn't exist), then just
        // return the list with the current directory.
        if (element == null) {
            return filelist;
        }

        // Verify that the element is of the correct type (i.e. a list).
        if (!(element instanceof ListResource)) {
            throw new EvaluationException("LOADPATH variable must be a list");
        }

        // Loop over the values in the list.
        ListResource loadpath = (ListResource) element;
        for (int i = 0; i < loadpath.size(); i++) {
            try {
                Element child = loadpath.get(TermFactory.create(i));
                if (child instanceof StringProperty) {
                    String sfile = ((StringProperty) child).getValue();
                    if (sfile.startsWith("/")) {
                        throw new EvaluationException(
                                "LOADPATH can only contain relative paths");
                    }
                    filelist.add(sfile);
                } else {
                    throw new EvaluationException(
                            "LOADPATH contains non-string value");
                }
            } catch (InvalidTermException ite) {
                // This exception should never be encountered because the terms
                // are all indexes and the resource is a list.
                throw CompilerError.create(MSG_INVALID_KEY_OR_INDEX);
            }

        }

        return filelist;
    }

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


Question: ECMA-262 12.14 Assignment Operators

function parseAssignmentExpression() {
        var token, expr, right, list, startToken;

        startToken = lookahead;
        token = lookahead;

        if (!state.allowYield && matchKeyword('yield')) {
            return parseYieldExpression();
        }

        expr = parseConditionalExpression();

        if (expr.type === PlaceHolders.ArrowParameterPlaceHolder || match('=>')) {
            isAssignmentTarget = isBindingElement = false;
            list = reinterpretAsCoverFormalsList(expr);

            if (list) {
                firstCoverInitializedNameError = null;
                return parseArrowFunctionExpression(list, new WrappingNode(startToken));
            }

            return expr;
        }

        if (matchAssign()) {
            if (!isAssignmentTarget) {
                tolerateError(Messages.InvalidLHSInAssignment);
            }

            // ECMA-262 12.1.1
            if (strict && expr.type === Syntax.Identifier) {
                if (isRestrictedWord(expr.name)) {
                    tolerateUnexpectedToken(token, Messages.StrictLHSAssignment);
                }
                if (isStrictModeReservedWord(expr.name)) {
                    tolerateUnexpectedToken(token, Messages.StrictReservedWord);
                }
            }

            if (!match('=')) {
                isAssignmentTarget = isBindingElement = false;
            } else {
                reinterpretExpressionAsPattern(expr);
            }

            token = lex();
            right = isolateCoverGrammar(parseAssignmentExpression);
            expr = new WrappingNode(startToken).finishAssignmentExpression(token.value, expr, right);
            firstCoverInitializedNameError = null;
        }

        return expr;
    }

public Matrix4f m22(float m22) {
        this.m22 = m22;
        properties &= ~PROPERTY_ORTHONORMAL;
        if (m22 != 1.0f)
            properties &= ~(PROPERTY_IDENTITY | PROPERTY_TRANSLATION);
        return this;
    }

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


Question: Un-registers from the WebSocketScopeManager.

public void unregister() {
        // clean up the connections by first closing them
        for (WebSocketConnection conn : conns) {
            conn.close();
        }
        conns.clear();
        // clean up the listeners by first stopping them
        for (IWebSocketDataListener listener : listeners) {
            listener.stop();
        }
        listeners.clear();
    }

function(purged_unit, peer){
			var ws = getPeerWebSocket(peer);
			if (ws)
				sendErrorResult(ws, purged_unit, "error on (indirect) parent unit "+objJoint.unit.unit+": "+error);
		}

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


Question:
finds the corresponding functional interface method for a lambda expression or method reference

@param tree the lambda expression or method reference
@return the functional interface method

public static Symbol.MethodSymbol getFunctionalInterfaceMethod(ExpressionTree tree, Types types) {
    Preconditions.checkArgument(
        (tree instanceof LambdaExpressionTree) || (tree instanceof MemberReferenceTree));
    Type funcInterfaceType = ((JCTree.JCFunctionalExpression) tree).type;
    return (Symbol.MethodSymbol) types.findDescriptorSymbol(funcInterfaceType.tsym);
  }

func (_m *ClientInterface) GetServiceEndpoints(serviceIDs []string, reportImports bool, reportExports bool, validate bool) ([]applicationendpoint.EndpointReport, error) {
	ret := _m.Called(serviceIDs, reportImports, reportExports, validate)

	var r0 []applicationendpoint.EndpointReport
	if rf, ok := ret.Get(0).(func([]string, bool, bool, bool) []applicationendpoint.EndpointReport); ok {
		r0 = rf(serviceIDs, reportImports, reportExports, validate)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]applicationendpoint.EndpointReport)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func([]string, bool, bool, bool) error); ok {
		r1 = rf(serviceIDs, reportImports, reportExports, validate)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

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


Question:
Normalizes an object to sending into body of the request
@private

@param  {Object} obj - An object with data for sending
@return {Object|form-data}

function normalize(obj) {
    const isMultipart = isFormData(obj);
    const content = { filename: '', value: '', mime: '' };
    const result = ((isMultipart) ? new FormData() : {});
    let file = null;

    Object.keys(obj).forEach((item) => {
        if (isMultipart) {
            if (obj[item].value) content.value = obj[item].value;
            else content.value = obj[item];

            content.filename = obj[item].filename || null;
            content.mime = obj[item].mime || null;

            if (content.value instanceof stream.Stream) {
                result.append(item, content.value, {
                    contentType: content.mime,
                    filename: content.filename,
                });

                return;
            }

            if (Buffer.isBuffer(content.value)) {
                file = FileType(content.value);
                result.append(item, content.value, {
                    contentType: content.mime || file.mime || 'application/octet-stream',
                    filename: content.filename || `data-${Date.now()}.${file.ext || ''}`,
                });

                return;
            }

            if (typeof content.value === 'object') {
                result.append(item, JSON.stringify(content.value), {
                    contentType: 'application/json',
                });

                return;
            }

            result.append(item, content.value);
        } else {
            if (typeof obj[item] === 'object') {
                result[item] = JSON.stringify(obj[item]);
                return;
            }

            result[item] = obj[item];
        }
    });

    return result;
}

protected function getBody($method)
    {
        if ($method === "get") {
            return parent::getBody($method);
        }
        $acls = array();
        foreach ($this->getArguments() as $value) {
            $acls[] = $value;
        }
        return json_encode(array("acl" => $acls));
    }

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


Question:
Assembles an iterable of :class:`~jawa.util.bytecode.Instruction`
        objects into a method's code body.

def assemble(self, code):

        with io.BytesIO() as code_out:
            for ins in code:
                write_instruction(code_out, code_out.tell(), ins)
            self._code = code_out.getvalue()

def shade_jar(self, shading_rules, jar_path):

    self.context.log.debug('Shading {}.'.format(jar_path))
    with temporary_dir() as tempdir:
      output_jar = os.path.join(tempdir, os.path.basename(jar_path))
      with self.shader.binary_shader_for_rules(output_jar, jar_path, shading_rules) as shade_runner:
        result = execute_runner(shade_runner, workunit_factory=self.context.new_workunit,
                                workunit_name='jarjar')
        if result != 0:
          raise TaskError('Shading tool failed to shade {0} (error code {1})'.format(jar_path,
                                                                                result))
        if not os.path.exists(output_jar):
          raise TaskError('Shading tool returned success for {0}, but '
                          'the output jar was not found at {1}'.format(jar_path, output_jar))
        atomic_copy(output_jar, jar_path)
        return jar_path

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


Question:
Returns a dictionary of packages in the following
        format::

            {'package_name': {'name': 'package_name',
                              'version': 'major.minor.version'}}

def get_pkg_list(self):

        if self.query_command:
            cmd = self.query_command
            pkg_list = shell_out(
                cmd, timeout=0, chroot=self.chroot
            ).splitlines()

            for pkg in pkg_list:
                if '|' not in pkg:
                    continue
                elif pkg.count("|") == 1:
                    name, version = pkg.split("|")
                    release = None
                elif pkg.count("|") == 2:
                    name, version, release = pkg.split("|")
                self.packages[name] = {
                    'name': name,
                    'version': version.split(".")
                }
                release = release if release else None
                self.packages[name]['release'] = release

        return self.packages

def set_version(request, response):

    settings = request.registry.settings
    resolver = DottedNameResolver()

    # get version config
    version_header = settings.get(
        'api.version_header',
        'X-Version',
    )
    version_header_value = settings.get('api.version_header_value')
    if callable(version_header_value):
        version_header_value = version_header_value()
    elif version_header_value:
        version_header_value = resolver.resolve(version_header_value)

    # get revision config
    revision_header = settings.get(
        'api.revision_header',
        'X-Revision',
    )
    revision_header_value = settings.get('api.revision_header_value')
    if callable(revision_header_value):
        revision_header_value = revision_header_value()
    elif revision_header_value:
        revision_header_value = resolver.resolve(revision_header_value)

    if version_header and version_header_value:
        response.headers[str(version_header)] = str(version_header_value)
    if revision_header and revision_header_value:
        response.headers[str(revision_header)] = str(revision_header_value)

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


Question:
Use MySQL-specific comments so we can run these queries on other RDBMS.

@param string $field
@param string $collation

@return Expression

private function fieldWithCollation(string $field, string $collation): Expression
    {
        return DB::raw($field . ' /*! COLLATE ' . $collation . ' */');
    }

def collapse(self, id_user):
        """"""
        c = CmtCOLLAPSED(id_bibrec=self.id_bibrec, id_cmtRECORDCOMMENT=self.id,
                         id_user=id_user)
        db.session.add(c)
        db.session.commit()

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


Question:
Register any application services.

@return void

public function register()
    {
        /**
         * Sort the collection using by designated key.
         */
        Collection::macro('sortByIds', function (array $ids, $key = 'id') {
            $ids = array_flip($ids);

            return $this->sort(function ($a, $b) use ($ids, $key) {
                $a_value = Arr::get($a, $key, '');
                $b_value = Arr::get($b, $key, '');

                return Arr::get($ids, $a_value, PHP_INT_MAX) - Arr::get($ids, $b_value, PHP_INT_MAX);
            });
        });

        /**
         * Chunk the results of a query by time.
         */
        Builder::macro('chunkByTime', function ($time_interval, callable $callback, $column = 'created_at') {
            $clone = clone $this;
            $result = $clone->orderBy($column)->first([$column]);
            if (is_null($result)) {
                return true;
            }
            $start_time = strtotime($this->getModel()->fromDateTime($result->$column));

            $clone = clone $this;
            $result = $clone->orderBy($column, 'desc')->first([$column]);
            $end_time = strtotime($this->getModel()->fromDateTime($result->$column));

            for ($min_time = $start_time; $min_time <= $end_time; $min_time += $time_interval) {

                $start_date = $this->getModel()->fromDateTime($min_time);
                $end_date = $this->getModel()->fromDateTime($min_time + $time_interval);

                $clone = clone $this;

                $results = $clone->where($column, '>=', $start_date)->where($column, '<', $end_date)->get();

                if ($callback($results) === false) {
                    return false;
                }

                unset($results);
            }

            return true;
        });
    }

func (s *NumberValidateResponse) SetCarrier(v string) *NumberValidateResponse {
	s.Carrier = &v
	return s
}

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


Question:
/*
overQualLastAccessTimeUpdate
Attempts to update the last access time ensuring the old value matches.
This verifies that the copy we have in cache is still valid.

protected int overQualLastAccessTimeUpdate(BackedSession sess, long nowTime) {
        if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            StringBuffer sb = new StringBuffer(" lastAccessTime= ");
            sb.append(sess.getCurrentAccessTime());
            sb.append("; nowTime= ").append(nowTime);
            LoggingUtil.SESSION_LOGGER_WAS.entering(methodClassName, methodNames[OVERQUAL_LAST_ACCESS_TIME_UPDATE], sb);
        }
        Connection con = null;
        PreparedStatement s = null;
        String id = sess.getId();
        int rowsRet = 1; //Assume that it will be cache hit.
        try {

            // PQ76937 BEGIN
            synchronized (sess) {
                con = getConnection(false);
                if (con == null) {
                    return 1;
                    /*
                     * REG if the database goes down, we will not update the lastAccessTime because we still want to find a match
                     * when the database does come back up. I do see a problem if the database goes down, we keep hitting a session
                     * and then because we haven't updated the lastAccessTime, our invalidator thread invalidates the session.
                     */
                }

                s = con.prepareStatement(optUpdatePrimRow);
                setPSLong(s, 1, nowTime);
                s.setString(2, id);
                s.setString(3, id);
                s.setString(4, sess.getAppName());
                //the currentAccessTime has not been updated so this is really the lastAccessTime until we call updateLastAccessTime
                setPSLong(s, 5, sess.getCurrentAccessTime());
                rowsRet = s.executeUpdate();

                if (rowsRet > 0) {
                    sess.updateLastAccessTime(nowTime);
                }
            }
            // PQ76937 END

            if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled() && LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
                if (rowsRet > 0) {
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[OVERQUAL_LAST_ACCESS_TIME_UPDATE], "after upd (row changed " + id);
                } else {
                    //It might be either cache hit or session is not in cache
                    LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[OVERQUAL_LAST_ACCESS_TIME_UPDATE],
                                                        "It might be either cache hit or session is not in cache for  " + id);
                }
            }
        } catch (Throwable th) {
            //           if (isStaleConnectionException(th)) {
            //               com.ibm.ws.ffdc.FFDCFilter.processException(th, "com.ibm.ws.session.store.db.DatabaseHashMap.overQualLastAccessTimeUpdate", "1527", sess);
            //               if (com.ibm.websphere.ras.TraceComponent.isAnyTracingEnabled()&&LoggingUtil.SESSION_LOGGER_WAS.isLoggable(Level.FINE)) {
            //                   LoggingUtil.SESSION_LOGGER_WAS.logp(Level.FINE, methodClassName, methodNames[OVERQUAL_LAST_ACCESS_TIME_UPDATE], "StaleConnectionException");
            //               }
            //           } else {
            com.ibm.ws.ffdc.FFDCFilter.processException(th, "com.ibm.ws.session.store.db.DatabaseHashMap.overQualLastAccessTimeUpdate", "1531", sess);
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[OVERQUAL_LAST_ACCESS_TIME_UPDATE], "CommonMessage.sessionid", id);
            LoggingUtil.SESSION_LOGGER_WAS.logp(Level.SEVERE, methodClassName, methodNames[OVERQUAL_LAST_ACCESS_TIME_UPDATE], "CommonMessage.exception", th);
            //           }
        } finally {
            if (s != null) {
                closeStatement(s);
            }
            if (con != null) {
                closeConnection(con);
            }
        }

        return rowsRet;
    }

func IsChaincodeDeployed(chainid, ccName, ccVersion string, ccHash []byte, sccp sysccprovider.SystemChaincodeProvider) (bool, error) {
	qe, err := sccp.GetQueryExecutorForLedger(chainid)
	if err != nil {
		return false, fmt.Errorf("Could not retrieve QueryExecutor for channel %s, error %s", chainid, err)
	}
	defer qe.Done()

	// XXX We are leaking details of the LSCC table structure to other parts of the code, and this is terrible
	chaincodeDataBytes, err := qe.GetState("lscc", ccName)
	if err != nil {
		return false, fmt.Errorf("Could not retrieve state for chaincode %s on channel %s, error %s", ccName, chainid, err)
	}

	if chaincodeDataBytes == nil {
		return false, nil
	}

	chaincodeData := &ChaincodeData{}
	err = proto.Unmarshal(chaincodeDataBytes, chaincodeData)
	if err != nil {
		return false, fmt.Errorf("Unmarshalling ChaincodeQueryResponse failed, error %s", err)
	}
	return chaincodeData.CCVersion() == ccVersion && bytes.Equal(chaincodeData.Hash(), ccHash), nil
}

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


Question: Return the string representation of a given numeric format.

def _format_str(format_int):
    """"""
    for dictionary in _formats, _subtypes, _endians:
        for k, v in dictionary.items():
            if v == format_int:
                return k
    else:
        return 'n/a'

def set_digit(self, pos, digit, decimal=False):

        if self.invert:
            self.set_digit_raw(pos, IDIGIT_VALUES.get(str(digit).upper(), 0x00))
        else:
            self.set_digit_raw(pos, DIGIT_VALUES.get(str(digit).upper(), 0x00))

        if decimal:
            self.set_decimal(pos, True)

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


Question: Returns the z-component of the spin of the secondary mass.

def spin_sz(self):
        """"""
        return conversions.secondary_spin(self.mass1, self.mass2, self.spin1z,
                                        self.spin2z)

def since(self, ts):

        while True:
            items = super(TailingOplog, self).since(ts)
            for doc in items:
                yield doc
                ts = doc['ts']

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


Question: View for setting cookies on spammers.

def spammer_view(request):
    """"""

    # Permits use of CSRF middleware
    context = RequestContext(request, {})
    template = Template("")

    response = HttpResponse(template.render(context))
    # Sets a cookie with a 10 years lifetime, accessible only via HTTP:
    response.set_cookie(COOKIE_KEY, value=COOKIE_SPAM, httponly=True,
                        expires=datetime.now()+timedelta(days=3650))

    if DJANGOSPAM_LOG:
        log("BLOCK RESPONSE", request.method, request.path_info,
            request.META.get("HTTP_USER_AGENT", "undefined"))

    return response

public String getCookie(String name, String dfvalue) {
        for (HttpCookie c : getCookies()) {
            if (name.equals(c.getName())) return c.getValue();
        }
        return dfvalue;
    }

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


Question:
Start a daemon Thread with the given closure as a Runnable instance.

@param self    placeholder variable used by Groovy categories; ignored for default static methods
@param closure the Runnable closure
@return the started thread
@since 1.0

public static Thread startDaemon(Thread self, Closure closure) {
        return createThread(null, true, closure);
    }

def wrap_code(code: str, args: str = '') -> ast.Module:

    if sys.version_info >= (3, 7):
        user_code = import_expression.parse(code, mode='exec')
        injected = ''
    else:
        injected = code

    mod = import_expression.parse(CORO_CODE.format(args, textwrap.indent(injected, ' ' * 8)), mode='exec')

    definition = mod.body[-1]  # async def ...:
    assert isinstance(definition, ast.AsyncFunctionDef)

    try_block = definition.body[-1]  # try:
    assert isinstance(try_block, ast.Try)

    if sys.version_info >= (3, 7):
        try_block.body.extend(user_code.body)
    else:
        ast.increment_lineno(mod, -16)  # bring line numbers back in sync with repl

    ast.fix_missing_locations(mod)

    is_asyncgen = any(isinstance(node, ast.Yield) for node in ast.walk(try_block))

    last_expr = try_block.body[-1]

    # if the last part isn't an expression, ignore it
    if not isinstance(last_expr, ast.Expr):
        return mod

    # if the last expression is not a yield
    if not isinstance(last_expr.value, ast.Yield):
        # copy the expression into a return/yield
        if is_asyncgen:
            # copy the value of the expression into a yield
            yield_stmt = ast.Yield(last_expr.value)
            ast.copy_location(yield_stmt, last_expr)
            # place the yield into its own expression
            yield_expr = ast.Expr(yield_stmt)
            ast.copy_location(yield_expr, last_expr)

            # place the yield where the original expression was
            try_block.body[-1] = yield_expr
        else:
            # copy the expression into a return
            return_stmt = ast.Return(last_expr.value)
            ast.copy_location(return_stmt, last_expr)

            # place the return where the original expression was
            try_block.body[-1] = return_stmt

    return mod

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


Question:
A helper function to explain each of the matched attributes returned by the explain-API

@param attribute The attribute found
@param collectExpandedQueryMap ?
@param query the query used to find the attribute
@return Set of explained query strings

public Set<ExplainedQueryString> convertAttributeToExplainedAttribute(
      Attribute attribute, Map<String, String> collectExpandedQueryMap, Query<Entity> query) {
    EntityType attributeMetaData = dataService.getEntityType(ATTRIBUTE_META_DATA);
    String attributeID = attribute.getIdentifier();
    Explanation explanation =
        elasticSearchExplainService.explain(query, attributeMetaData, attributeID);
    return elasticSearchExplainService.findQueriesFromExplanation(
        collectExpandedQueryMap, explanation);
  }

def _run__http(self, action, replace):
        """"""

        query = action['query']
#        self._debug = True
        url = '{type}://{host}{path}'.format(path=query['path'], **action)
        content = None
        method = query.get('method', "get").lower()
        self.debug("{} {} url={}\n", action['type'], method, url)
        if method == "post":
            content = query['content']
        headers = query.get('headers', {})

        if replace and action.get('template'):
            self.rfxcfg.macro_expand(url, replace)
            if content:
                if isinstance(content, dict):
                    for key, value in content.items():
                        content[key] = self.rfxcfg.macro_expand(value, replace)
                else:
                    content = self.rfxcfg.macro_expand(content, replace)

            newhdrs = dict()
            for key, value in headers.items():
                newhdrs[key.lower()] = self.rfxcfg.macro_expand(value, replace)
            headers = newhdrs

        self.debug("{} headers={}\n", action['type'], headers)
        self.debug("{} content={}\n", action['type'], content)

        if content and isinstance(content, dict):
            content = json.dumps(content)

        self.logf("Action {name} {type}\n", **action)
        result = getattr(requests, method)(url, headers=headers, data=content, timeout=action.get('timeout', 5))
        expect = action.get('expect', {})
        expected_codes = expect.get("response-codes", (200, 201, 202, 204))
        self.debug("{} expect codes={}\n", action['type'], expected_codes)
        self.debug("{} status={} content={}\n", action['type'], result.status_code, result.text)
        if result.status_code not in expected_codes:
            self.die("Unable to make {} call, unexpected result ({})",
                     action['type'], result.status_code)

        if 'content' in expect:
            self.debug("{} expect content={}\n", action['type'], expect['content'])
            if expect['content'] not in result.text:
                self.die("{} call to {} failed\nExpected: {}\nReceived:\n{}",
                         action['type'], url, expect['content'], result.text)

        if 'regex' in expect:
            self.debug("{} expect regex={}\n", action['type'], expect['regex'])
            if not re.search(expect['regex'], result.text):
                self.die("{} call to {} failed\nRegex: {}\nDid not match:\n{}",
                         action['type'], url, expect['regex'], result.text)

        self.log(result.text, level=common.log_msg)

        self.logf("Success, status={}\n", result.status_code, level=common.log_good)
        return True

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


Question:
<p>
The validation status of the model package.
</p>

@param validationStatuses
The validation status of the model package.

public void setValidationStatuses(java.util.Collection<ModelPackageStatusItem> validationStatuses) {
        if (validationStatuses == null) {
            this.validationStatuses = null;
            return;
        }

        this.validationStatuses = new java.util.ArrayList<ModelPackageStatusItem>(validationStatuses);
    }

public NotificationChain basicSetName(JvmParameterizedTypeReference newName, NotificationChain msgs)
	{
		JvmParameterizedTypeReference oldName = name;
		name = newName;
		if (eNotificationRequired())
		{
			ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, SarlPackage.SARL_BEHAVIOR_UNIT__NAME, oldName, newName);
			if (msgs == null) msgs = notification; else msgs.add(notification);
		}
		return msgs;
	}

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


Question:
Keep all templates withe the custom_class in array $templatesToKeep
@param $templatesToKeep

public function keepDefaultTemplates($templatesToKeep)
  {
    add_filter('vc_load_default_templates', function ($templates) use ($templatesToKeep) {
      $returnArray = [];
      if (is_array($templatesToKeep) && count($templatesToKeep) > 0) {
        $returnArray = array_filter($templates, function ($var) use ($templatesToKeep) {
          return in_array($var['custom_class'], $templatesToKeep);
        });
      }

      return $returnArray;
    });
  }

public function preserveWhiteSpace($value = true)
    {
        if (!is_bool($value)) {
            throw new InvalidArgumentException(sprintf('%s expects parameter 1 to be boolean, %s given', __METHOD__, gettype($value)));
        }

        $this->document->preserveWhiteSpace = $value;

        return $this;
    }

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


Question: // WebsocketRead implements WebsocketPrinter.WebsocketRead.

func (p DebugPrinter) WebsocketRead(typ int, content []byte, closeCode int) {
	b := &bytes.Buffer{}
	fmt.Fprintf(b, "<- Received: %s", wsMessageTypeName(typ))
	if typ == websocket.CloseMessage {
		fmt.Fprintf(b, " (%d)", closeCode)
	}
	fmt.Fprint(b, "\n")
	if len(content) > 0 {
		if typ == websocket.BinaryMessage {
			fmt.Fprintf(b, "%v\n", content)
		} else {
			fmt.Fprintf(b, "%s\n", content)
		}
	}
	fmt.Fprintf(b, "\n")
	p.logger.Logf(b.String())
}

def tcp_client(tcp_addr):
  """"""
  family = socket.AF_INET6 if ":" in tcp_addr.ip else socket.AF_INET
  sock = socket.socket(family, socket.SOCK_STREAM, socket.IPPROTO_TCP)
  for i in range(300):
    logging.info("Connecting to: %s, attempt %d", tcp_addr, i)
    try:
      sock.connect(tcp_addr)
      break
    except socket.error:
      time.sleep(1)
  else:
    sock.connect(tcp_addr)  # One last try, but don't catch this error.
  logging.info("Connected.")

  map_data = read_tcp(sock)
  settings_str = read_tcp(sock)
  if not settings_str:
    raise socket.error("Failed to read")
  settings = json.loads(settings_str.decode())
  logging.info("Got settings. map_name: %s.", settings["map_name"])
  logging.debug("settings: %s", settings)
  settings["map_data"] = map_data
  return sock, settings

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


Question:
View a single invoice

@param  \stdClass $oInvoice The invoice object

@return void

protected function view($oInvoice)
    {
        //  Business details
        $this->data['business'] = (object) [
            'name'       => appSetting('business_name', 'nails/module-invoice'),
            'address'    => appSetting('business_address', 'nails/module-invoice'),
            'telephone'  => appSetting('business_telephone', 'nails/module-invoice'),
            'email'      => appSetting('business_email', 'nails/module-invoice'),
            'vat_number' => appSetting('business_vat_number', 'nails/module-invoice'),
        ];

        $oInvoiceSkinService   = Factory::service('InvoiceSkin', 'nails/module-invoice');
        $sEnabledSkin          = $oInvoiceSkinService->getEnabledSlug() ?: self::DEFAULT_INVOICE_SKIN;
        $this->data['invoice'] = $oInvoice;
        $this->data['isPdf']   = false;

        $oInvoiceSkinService->view($sEnabledSkin, 'render', $this->data);
    }

public function package()
    {
        $package = [];
        $package['id'] = $this->id;
        $package['instructions'] = $this->instructions;
        $package['filterQuery'] = $this->filterQuery;
        $package['type'] = $this->type;
        $package['typeOptions'] = $this->typeOptions;
        $package['total'] = $this->total;
        $package['bundle'] = false;
        $package['bundle'] = ['offset' => $this->offset, 'size' => count($this->_items), 'items' => []];
        foreach ($this->_items as $item) {
            $package['bundle']['items'][$item->id] = $item->package();
        }

        return $package;
    }

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


Question:
Run the application.

@return mixed
@throws \Parable\Console\Exception

public function run()
    {
        $defaultCommand = null;
        $command        = null;

        if ($this->defaultCommand) {
            $defaultCommand = $this->getCommand($this->defaultCommand);
        }
        if (!$this->shouldOnlyUseDefaultCommand()) {
            $commandName = $this->parameter->getCommandName();
            if ($commandName) {
                $command = $this->getCommand($commandName);
            }
            $this->parameter->enableCommandName();
        } else {
            $this->parameter->disableCommandName();
        }

        // Use $command or $defaultCommand, since they're mutually exclusive
        $command = $command ?: $defaultCommand;

        if (!$command) {
            throw new \Parable\Console\Exception('No valid commands found.');
        }

        $this->activeCommand = $command;

        $this->parameter->setCommandArguments($command->getArguments());
        $this->parameter->checkCommandArguments();

        $this->parameter->setCommandOptions($command->getOptions());
        $this->parameter->checkCommandOptions();

        return $command->run();
    }

func (c *RolesController) List(ctx *app.ListRolesContext) error {
	if ctx.ResourceType == nil { // todo: check for empty string too?
		return jsonapi.JSONErrorResponse(ctx, errors.NewBadParameterError("resource_type", "nil"))
	}

	var roleScopes []role.RoleDescriptor

	_, err := c.app.ResourceTypeRepository().Lookup(ctx, *ctx.ResourceType)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting roles for the resource type")
		// if not found, then NotFoundError would be returned,
		// hence returning the error as is.
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	roleScopes, err = c.app.RoleManagementService().ListAvailableRolesByResourceType(ctx, *ctx.ResourceType)

	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting available roles for the resource")
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	respRoles := convertRoleScopeToAppRoles(roleScopes)
	res := &app.Roles{
		Data: respRoles,
	}
	return ctx.OK(res)
}

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


Question:
Fast CMDS using random SVD

    Parameters
    ----------
    D : array-like, input data [n_samples, n_dimensions]

    ndim : int, number of dimensions in which to embed `D`

    Returns
    -------
    Y : array-like, embedded data [n_sample, ndim]

def cmdscale_fast(D, ndim):

    tasklogger.log_debug("Performing classic MDS on {} of shape {}...".format(
        type(D).__name__, D.shape))
    D = D**2
    D = D - D.mean(axis=0)[None, :]
    D = D - D.mean(axis=1)[:, None]
    pca = PCA(n_components=ndim, svd_solver='randomized')
    Y = pca.fit_transform(D)
    return Y

func (in *NodeDaemonEndpoints) DeepCopy() *NodeDaemonEndpoints {
	if in == nil {
		return nil
	}
	out := new(NodeDaemonEndpoints)
	in.DeepCopyInto(out)
	return out
}

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


Question: ----- private methods -----

private void init() {

		factories.put(NotEmptyQuery.class,     new NotEmptyQueryFactory(this));
		factories.put(FulltextQuery.class,     new KeywordQueryFactory(this));
		factories.put(SpatialQuery.class,      new SpatialQueryFactory(this));
		factories.put(GroupQuery.class,        new GroupQueryFactory(this));
		factories.put(RangeQuery.class,        new RangeQueryFactory(this));
		factories.put(ExactQuery.class,        new KeywordQueryFactory(this));
		factories.put(ArrayQuery.class,        new ArrayQueryFactory(this));
		factories.put(EmptyQuery.class,        new EmptyQueryFactory(this));
		factories.put(TypeQuery.class,         new TypeQueryFactory(this));
		factories.put(UuidQuery.class,         new UuidQueryFactory(this));
		factories.put(RelationshipQuery.class, new RelationshipQueryFactory(this));
		factories.put(ComparisonQuery.class,   new ComparisonQueryFactory(this));

		converters.put(Boolean.class, new BooleanTypeConverter());
		converters.put(String.class,  new StringTypeConverter());
		converters.put(Date.class,    new DateTypeConverter());
		converters.put(Long.class,    new LongTypeConverter());
		converters.put(Short.class,   new ShortTypeConverter());
		converters.put(Integer.class, new IntTypeConverter());
		converters.put(Float.class,   new FloatTypeConverter());
		converters.put(Double.class,  new DoubleTypeConverter());
		converters.put(byte.class,    new ByteTypeConverter());
	}

Set<ProjectMethod> findProjectMethods(final List<Instruction> instructions) {
        final Set<ProjectMethod> projectMethods = new HashSet<>();

        addProjectMethods(instructions, projectMethods);

        return projectMethods;
    }

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


Question:
Format columns for a table schema.

@param \Titon\Db\Driver\Schema $schema
@return string

public function formatColumns(Schema $schema) {
        $columns = [];

        foreach ($schema->getColumns() as $column => $options) {
            $dataType = $this->getDriver()->getType($options['type']);

            $options = $options + $dataType->getDefaultOptions();
            $type = $options['type'];

            if (!empty($options['length'])) {
                $type .= '(' . $options['length'] . ')';
            }

            $output = [$this->quote($column), strtoupper($type)];

            // Integers
            if (!empty($options['unsigned'])) {
                $output[] = $this->getKeyword(self::UNSIGNED);
            }

            if (!empty($options['zerofill'])) {
                $output[] = $this->getKeyword(self::ZEROFILL);
            }

            // Strings
            if (!empty($options['charset'])) {
                $output[] = sprintf($this->getClause(self::CHARACTER_SET), $options['charset']);
            }

            if (!empty($options['collate'])) {
                $output[] = sprintf($this->getClause(self::COLLATE), $options['collate']);
            }

            // Primary and uniques can't be null
            if (!empty($options['primary']) || !empty($options['unique'])) {
                $output[] = $this->getKeyword(self::NOT_NULL);
            } else {
                $output[] = $this->getKeyword(empty($options['null']) ? self::NOT_NULL : self::NULL);
            }

            if (array_key_exists('default', $options)) {
                $output[] = $this->formatDefault($options['default']);
            }

            if (!empty($options['ai'])) {
                $output[] = $this->getKeyword(self::AUTO_INCREMENT);
            }

            if (!empty($options['comment'])) {
                $output[] = sprintf($this->getClause(self::COMMENT), $this->getDriver()->escape(substr($options['comment'], 0, 255)));
            }

            $columns[] = trim(implode(' ', $output));
        }

        return implode(",\n", $columns);
    }

static public HsqlName getAutoColumnName(int i) {

        if (i < autoColumnNames.length) {
            return autoColumnNames[i];
        }

        return new HsqlName(staticManager, makeAutoColumnName("C_", i), 0, false);
    }

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


Question: We will generate Form.

private function generateForm()
    {
        // Generate Form Component class
        $controllerInstance = Controller::instance($this->columns, null, $this);

        $formTemplateDir =
            dirname(dirname(__FILE__)).DS.'src'.DS.'Apps'.DS.'Form'.DS;

        $form = new Form($controllerInstance, $this);
        $form->setFormTemplatePath($formTemplateDir);

        $form->generate();
    }

public function setFormLength($labelLength, $gapLength, $offsetLength = null)
    {
        $command = new Command\Stored\SetFormLengthCommand($labelLength, $gapLength, $offsetLength);
        $this->getComposite()->addCommand($command);
        return $this;
    }

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


Question: // SetEtherbase sets the mining reward address.

func (s *Ethereum) SetEtherbase(etherbase common.Address) {
	s.lock.Lock()
	s.etherbase = etherbase
	s.lock.Unlock()

	s.miner.SetEtherbase(etherbase)
}

def declare_consuming(self, exchange_name, routing_key, queue_name, callback):

        self.bind_topic_exchange(exchange_name, routing_key, queue_name)
        self.declare_basic_consuming(
            queue_name=queue_name,
            callback=callback
        )

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


Question: // Listen returns the address's TCP listener.

func (a *Addr) Listen() (net.Listener, error) {
	// Start the listener now, if there's a default
	// and nothing's called Set yet.
	if a.err == nil && a.ln == nil && a.s != "" {
		if err := a.Set(a.s); err != nil {
			return nil, err
		}
	}
	if a.err != nil {
		return nil, a.err
	}
	if a.ln != nil {
		return a.ln, nil
	}
	return nil, errors.New("listen: no error or listener")
}

def __read(self):

        # Set the socket as non-blocking
        self._socket.setblocking(0)

        while not self._stop_event.is_set():
            # Watch for content
            ready = select.select([self._socket], [], [], 1)
            if ready[0]:
                # Socket is ready
                data, sender = self._socket.recvfrom(1024)
                try:
                    self._handle_heartbeat(sender, data)
                except Exception as ex:
                    _logger.exception("Error handling the heart beat: %s", ex)

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


Question:
格式化导出数组
@param $data
@param string $sp
@return string

public static function export($data, $sp = '')
    {
        $tabs[] = '[';
        foreach ($data as $key => $item) {
            if (is_array($item)) {
                $tabs[] = $sp . '    ' . var_export($key, true) . ' => ' . self::export($item, $sp . '    ') . ',';
            } else {
                $tabs[] = $sp . '    ' . var_export($key, true) . ' => ' . var_export($item, true) . ',';
            }
        }
        $tabs[] = $sp . ']';
        return join("\n", $tabs);
    }

@Override
    public void executeQuery(
            final ObjectClass objClass,
            final Operand query,
            final ResultsHandler handler,
            final OperationOptions options) {

        if (LOG.isOk()) {
            LOG.ok("Execute query: " + query);
        }

        // check objectclass
        if (objClass == null || (!objClass.equals(ObjectClass.ACCOUNT))) {
            throw new IllegalArgumentException("Invalid objectclass");
        }

        // check handler
        if (handler == null) {
            throw new IllegalArgumentException("Invalid handler");
        }

        // get web service client
        final Provisioning provisioning = connection.getProvisioning();
        if (provisioning == null) {
            throw new IllegalStateException("Web Service client not found");
        }

        try {
            final List<WSUser> resultSet = provisioning.query(query);
            if (resultSet == null) {
                return;
            }

            boolean handle = true;
            for (final Iterator<WSUser> i = resultSet.iterator(); i.hasNext() && handle;) {
                final WSUser user = i.next();

                if (LOG.isOk()) {
                    LOG.ok("Found user: {0}", user);
                }

                try {
                    handle = handler.handle(buildConnectorObject(user.getAttributes()).build());
                    LOG.ok("Handle: {0}", handle);
                } catch (Exception e) {
                    LOG.error(e, "Error building connector object for {0}", user);
                }
            }
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    }

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


Question:
获取显示“上一页”的代码
@return string

protected function pre_page()
	{
        $style = @$this->span_class['previous'];
        if ($this->page > 1)
        {
            return $this->_get_link($this->_get_url($this->page - 1), $this->pre_page, $style);
        }

        return '' . $this->pre_page . '';
	}

protected function debug_query($sql, $params = null) {
        echo '
 (', $this->get_dbtype(), '): ',  htmlentities($sql, ENT_QUOTES, 'UTF-8');
        if($params) {
            echo ' (parameters ';
            print_r($params);
            echo ')';
        }
        echo '
';
    }

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


Question:
Calculate the row echelon form (REF) of the matrix. Return the matrix
and the number of swaps in a tuple.

@return array

public function ref() : array
    {
        try {
            $ref = $this->gaussianElimination();
        } catch (RuntimeException $e) {
            $ref = $this->rowReductionMethod();
        }

        return $ref;
    }

def _supervised_evaluation_error_checking(targets, predictions):

    _raise_error_if_not_sarray(targets, "targets")
    _raise_error_if_not_sarray(predictions, "predictions")
    if (len(targets) != len(predictions)):
        raise _ToolkitError(
         "Input SArrays 'targets' and 'predictions' must be of the same length.")

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


Question:
@param array              $expression
@param Call               $call
@param CompilationContext $context

@throws CompilerException

@return bool|CompiledExpression|mixed

public function optimize(array $expression, Call $call, CompilationContext $context)
    {
        if (!isset($expression['parameters'])) {
            return false;
        }

        if (1 != \count($expression['parameters'])) {
            throw new CompilerException("'globals_get' only accepts one parameter", $expression);
        }

        if ('string' != $expression['parameters'][0]['parameter']['type']) {
            throw new CompilerException("A string parameter is required for 'globals_get'", $expression);
        }

        $globalName = $expression['parameters'][0]['parameter']['value'];

        if (!$context->compiler->isExtensionGlobal($globalName)) {
            throw new CompilerException("Global '".$globalName."' cannot be read because it isn't defined", $expression);
        }

        $globalDefinition = $context->compiler->getExtensionGlobal($globalName);

        if (false !== strpos($globalName, '.')) {
            $parts = explode('.', $globalName);

            return new CompiledExpression($globalDefinition['type'], 'ZEPHIR_GLOBAL('.$parts[0].').'.$parts[1], $expression);
        }

        return new CompiledExpression($globalDefinition['type'], 'ZEPHIR_GLOBAL('.$globalName.')', $expression);
    }

function(container_config, x) {

		var i,
			count,
			name;

		if ('event' in x) {

			if (typeof(x.event) != 'object') Lava.t("Malformed x:event attribute");

			container_config.events = {};

			for (name in x.event) {

				container_config.events[name] = Lava.parsers.Common.parseTargets(x.event[name]);

			}

		}

		// Attribute binding. Example: x:bind:src="<any_valid_expression>"
		if ('bind' in x) {

			if (typeof(x.bind) != 'object') Lava.t("Malformed x:bind attribute");

			container_config.property_bindings = this._parseBindingsHash(x.bind);

		}

		if ('style' in x) {

			if (typeof(x.style) != 'object') Lava.t("Malformed x:style attribute");

			container_config.style_bindings = this._parseBindingsHash(x.style);

		}

		if ('classes' in x) {

			var arguments = Lava.ExpressionParser.parse(x.classes, Lava.ExpressionParser.SEPARATORS.SEMICOLON),
				class_bindings = {};

			for (i = 0, count = arguments.length; i < count; i++) {

				class_bindings[i] = arguments[i];

			}

			container_config.class_bindings = class_bindings;

		}

		if ('container_class' in x) {

			container_config['class'] = x.container_class;

		}

	}

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