query
stringlengths
16
255
pos
list
neg
list
task
stringclasses
1 value
instruction
dict
Gets the list of <em>instances</em> associated to a virtual host name. @param virtualHostName the virtual hostname for which the instances need to be returned. @return list of <em>instances</em>.
[ "public List<InstanceInfo> getInstancesByVirtualHostName(String virtualHostName) {\n return Optional.ofNullable(this.virtualHostNameAppMap.get(virtualHostName.toUpperCase(Locale.ROOT)))\n .map(VipIndexSupport::getVipList)\n .map(AtomicReference::get)\n .orElseGet(Collections::emptyList); \n }" ]
[ "func (c *NetworkGetCommand) Info() *cmd.Info {\n\targs := \"<binding-name> [--ingress-address] [--bind-address] [--egress-subnets]\"\n\tdoc := `\nnetwork-get returns the network config for a given binding name. By default\nit returns the list of interfaces and associated addresses in the space for\nthe binding, as well as the ingress address for the binding. If defined, any\negress subnets are also returned.\nIf one of the following flags are specified, just that value is returned.\nIf more than one flag is specified, a map of values is returned.\n --bind-address: the address the local unit should listen on to serve connections, as well\n as the address that should be advertised to its peers.\n --ingress-address: the address the local unit should advertise as being used for incoming connections.\n --egress_subnets: subnets (in CIDR notation) from which traffic on this relation will originate.\n`\n\treturn jujucmd.Info(&cmd.Info{\n\t\tName: \"network-get\",\n\t\tArgs: args,\n\t\tPurpose: \"get network config\",\n\t\tDoc: doc,\n\t})\n}" ]
codesearchnet
{ "query": "Represent the text about programming:", "pos": "Represent the code about programming:", "neg": "Represent the code about programming:" }
Handle the deleted event for the Ban model. @param \Cog\Contracts\Ban\Ban $ban @return void
[ "public function deleted(BanContract $ban): void\n {\n $bannable = $ban->bannable()->withBanned()->first();\n if ($bannable->bans->count() === 0) {\n $bannable->unsetBannedFlag()->save();\n\n event(new ModelWasUnbanned($bannable));\n }\n }" ]
[ "public function handle(PublishThePost $event) {\n $this->sendEmailsFromList->sendEmails($event->data['id']['listID'], $event->data['id']);\n \\Log::info('Lasallecms\\Lasallecmsapi\\Listeners\\TriggerLaSalleCRMList listener completed');\n }" ]
codesearchnet
{ "query": "Represent the Github post about Software Development:", "pos": "Represent the Github code about Software Development:", "neg": "Represent the Github code about Software development:" }
Clear sequence numbers in column 1-6 and anything beyond column 72. @param line the line of code @return a line of code without sequence numbers
[ "public String cleanFixedLine(final String line) {\n\n StringBuilder cleanedLine = new StringBuilder();\n int length = line.length();\n\n /* Clear sequence numbering */\n for (int i = 0; i < _startColumn - 1; i++) {\n cleanedLine.append(\" \");\n }\n\n /* Trim anything beyond end column */\n if (length > _startColumn - 1) {\n String areaA = line.substring(_startColumn - 1,\n (length > _endColumn) ? _endColumn : length);\n\n cleanedLine.append(areaA);\n }\n return cleanedLine.toString();\n }" ]
[ "private static String keyToGoWithElementsString(String label, DuplicateGroupedAndTyped elements) {\n /*\n * elements.toString(), which the caller is going to use, includes the homogeneous type (if\n * any), so we don't want to include it here. (And it's better to have it in the value, rather\n * than in the key, so that it doesn't push the horizontally aligned values over too far.)\n */\n return lenientFormat(\"%s (%s)\", label, elements.totalCopies());\n }" ]
codesearchnet
{ "query": "Represent the instruction:", "pos": "Represent the code:", "neg": "Represent the code about programming:" }
// DisableVanityNameServers Vanity Name Servers for the given domain // // See https://developer.dnsimple.com/v2/vanity/#disable
[ "func (s *VanityNameServersService) DisableVanityNameServers(accountID string, domainIdentifier string) (*vanityNameServerResponse, error) {\n\tpath := versioned(vanityNameServerPath(accountID, domainIdentifier))\n\tvanityNameServerResponse := &vanityNameServerResponse{}\n\n\tresp, err := s.client.delete(path, nil, nil)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tvanityNameServerResponse.HttpResponse = resp\n\treturn vanityNameServerResponse, nil\n}" ]
[ "def delete_domain(self, domain, params=None):\n ''' \n '''\n params = update_params(params, {'domain': domain})\n return self.request('/v1/dns/delete_domain', params, 'POST')" ]
codesearchnet
{ "query": "Represent the Github text:", "pos": "Represent the Github code:", "neg": "Represent the Github code:" }
/* eslint-disable
[ "function adaptor(prompt) {\n prompt = { ...prompt }\n switch (prompt.type) {\n case 'confirm':\n prompt.type = 'checkbox'\n prompt.transformType = 'confirm'\n prompt.value = [prompt.value]\n prompt.choices = [\n { label: 'Yes?', value: true }\n ]\n break\n case 'list':\n prompt.type = 'radio'\n prompt.transformType = 'list'\n break\n }\n return prompt\n}" ]
[ "function printDebugWithCode(msg, code) {\n // eslint-disable-next-line no-console\n console.log(`\\n\\n${msg}:\\n`);\n // eslint-disable-next-line no-console\n console.log(`${highlightFn(code)}\\n`);\n}" ]
codesearchnet
{ "query": "Represent the Github sentence:", "pos": "Represent the Github code:", "neg": "Represent the Github code about Natural Language Processing:" }
Create new array <p>Stack: ..., count =&gt; ..., arrayref @param name @param aClass @param size @throws IOException
[ "public void addNewArray(String name, Class<?> aClass, int size) throws IOException\r\n {\r\n addNewArray(name, Typ.getTypeFor(aClass), size);\r\n }" ]
[ "def backward_word(self, e): # (M-b)\r\n \"\"\"\r\n self.l_buffer.backward_word(self.argument_reset)\r\n self.finalize()" ]
codesearchnet
{ "query": "Represent the instruction about programming:", "pos": "Represent the code about programming:", "neg": "Represent the code:" }
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
[ "@Override\n public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)\n {\n switch (featureID)\n {\n case SimpleAntlrPackage.OPTIONS__OPTION_VALUES:\n return ((InternalEList<?>)getOptionValues()).basicRemove(otherEnd, msgs);\n }\n return super.eInverseRemove(otherEnd, featureID, msgs);\n }" ]
[ "protected function _init($definition=null)\n {\n\n if (!is_null($definition)) {\n $this->_packageXml = simplexml_load_string($definition);\n } else {\n $packageXmlStub = <<<END\n<?xml version=\"1.0\"?>\n<package>\n <name />\n <version />\n <stability />\n <license />\n <channel />\n <extends />\n <summary />\n <description />\n <notes />\n <authors />\n <date />\n <time />\n <contents />\n <compatible />\n <dependencies />\n</package>\nEND;\n $this->_packageXml = simplexml_load_string($packageXmlStub);\n }\n return $this;\n }" ]
codesearchnet
{ "query": "Represent the Github instruction about Text generation:", "pos": "Represent the Github code about Text generation:", "neg": "Represent the Github code:" }
// IsValidOsArch checks if a OS-architecture combination is valid given a map // of valid OS-architectures
[ "func IsValidOSArch(labels map[ACIdentifier]string, validOSArch map[string][]string) error {\n\tif os, ok := labels[\"os\"]; ok {\n\t\tif validArchs, ok := validOSArch[os]; !ok {\n\t\t\t// Not a whitelisted OS. TODO: how to warn rather than fail?\n\t\t\tvalidOses := make([]string, 0, len(validOSArch))\n\t\t\tfor validOs := range validOSArch {\n\t\t\t\tvalidOses = append(validOses, validOs)\n\t\t\t}\n\t\t\tsort.Strings(validOses)\n\t\t\treturn fmt.Errorf(`bad os %#v (must be one of: %v)`, os, validOses)\n\t\t} else {\n\t\t\t// Whitelisted OS. We check arch here, as arch makes sense only\n\t\t\t// when os is defined.\n\t\t\tif arch, ok := labels[\"arch\"]; ok {\n\t\t\t\tfound := false\n\t\t\t\tfor _, validArch := range validArchs {\n\t\t\t\t\tif arch == validArch {\n\t\t\t\t\t\tfound = true\n\t\t\t\t\t\tbreak\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif !found {\n\t\t\t\t\treturn fmt.Errorf(`bad arch %#v for %v (must be one of: %v)`, arch, os, validArchs)\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}" ]
[ "function PbfSplicer(options) {\n // tag which will be auto-removed and auto-injected. Usually 'name'\n this.nameTag = options.nameTag;\n // tag that contains JSON initially, and which works as a prefix for multiple values\n this.multiTag = options.multiTag;\n\n // If options.namePicker is given, this class converts multiple language tags into one\n // Otherwise, it assumes that a single name_ tag exists with JSON content, and it will replace\n // it with multiple tags \"name_en\", \"name_fr\", ... depending on the JSON language codes\n this.namePicker = options.namePicker;\n\n // Flag to make requested_name (local_name) form\n this.combineName = options.combineName;\n}" ]
codesearchnet
{ "query": "Represent the Github description about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code about programming:" }
// ListEmailForwards lists the email forwards for a domain. // // See https://developer.dnsimple.com/v2/domains/email-forwards/#list
[ "func (s *DomainsService) ListEmailForwards(accountID string, domainIdentifier string, options *ListOptions) (*emailForwardsResponse, error) {\n\tpath := versioned(emailForwardPath(accountID, domainIdentifier, 0))\n\tforwardsResponse := &emailForwardsResponse{}\n\n\tpath, err := addURLQueryOptions(path, options)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tresp, err := s.client.get(path, forwardsResponse)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tforwardsResponse.HttpResponse = resp\n\treturn forwardsResponse, nil\n}" ]
[ "def _generate_api_gateway(self):\n \n self.tf_conf['resource']['aws_api_gateway_rest_api']['rest_api'] = {\n 'name': self.resource_name,\n 'description': self.description\n }\n self.tf_conf['output']['rest_api_id'] = {\n 'value': '${aws_api_gateway_rest_api.rest_api.id}'\n }\n # finally, the deployment\n \"\"\"\n @NOTE Currently, Terraform can't enable metrics collection,\n request logging or rate limiting on API Gateway services.\n\n @TODO update this when\n <https://github.com/hashicorp/terraform/issues/6612> is fixed.\n\n @see https://github.com/jantman/webhook2lambda2sqs/issues/7\n @see https://github.com/jantman/webhook2lambda2sqs/issues/16\n \"\"\"\n self.tf_conf['output']['base_url'] = {\n 'value': 'https://${aws_api_gateway_rest_api.rest_api.id}.'\n 'execute-api.%s.amazonaws.com/%s/' % (\n self.aws_region, self.config.stage_name)\n }\n # generate the endpoint configs\n endpoints = self.config.get('endpoints')\n for ep in sorted(endpoints.keys()):\n self._generate_endpoint(ep, endpoints[ep]['method'])" ]
codesearchnet
{ "query": "Represent the description:", "pos": "Represent the code:", "neg": "Represent the code:" }
// RoundDown will round tp down to next "full" d.
[ "func RoundDown(t time.Time, d TimeDelta) time.Time {\n\ttd := d.RoundDown(t)\n\tDebugLogger.Printf(\"RoundDown( %s, %s ) --> %s\", t.Format(\"2006-01-02 15:04:05 (Mon)\"), d.String(),\n\t\ttd.Format(\"2006-01-02 15:04:05 (Mon)\"))\n\treturn td\n}" ]
[ "def transform_cb(self, setting, value):\n \"\"\"\"\"\"\n self.make_callback('transform')\n\n # whence=0 because need to calculate new extents for proper\n # cutout for rotation (TODO: always make extents consider\n # room for rotation)\n whence = 0\n self.redraw(whence=whence)" ]
codesearchnet
{ "query": "Represent the Github description:", "pos": "Represent the Github code:", "neg": "Represent the Github code:" }
Add method info. @param methodInfoList the method info list @param classNameToClassInfo the map from class name to class info
[ "void addMethodInfo(final MethodInfoList methodInfoList, final Map<String, ClassInfo> classNameToClassInfo) {\n for (final MethodInfo mi : methodInfoList) {\n // Index method annotations\n addFieldOrMethodAnnotationInfo(mi.annotationInfo, /* isField = */ false, classNameToClassInfo);\n\n // Index method parameter annotations\n if (mi.parameterAnnotationInfo != null) {\n for (int i = 0; i < mi.parameterAnnotationInfo.length; i++) {\n final AnnotationInfo[] paramAnnotationInfoArr = mi.parameterAnnotationInfo[i];\n if (paramAnnotationInfoArr != null) {\n for (int j = 0; j < paramAnnotationInfoArr.length; j++) {\n final AnnotationInfo methodParamAnnotationInfo = paramAnnotationInfoArr[j];\n final ClassInfo annotationClassInfo = getOrCreateClassInfo(\n methodParamAnnotationInfo.getName(), ANNOTATION_CLASS_MODIFIER,\n classNameToClassInfo);\n annotationClassInfo.addRelatedClass(RelType.CLASSES_WITH_METHOD_PARAMETER_ANNOTATION,\n this);\n this.addRelatedClass(RelType.METHOD_PARAMETER_ANNOTATIONS, annotationClassInfo);\n }\n }\n }\n }\n }\n if (this.methodInfo == null) {\n this.methodInfo = methodInfoList;\n } else {\n this.methodInfo.addAll(methodInfoList);\n }\n }" ]
[ "@SuppressWarnings(\"unchecked\")\n public <T> Param<T> get(int index) {\n // TODO: Provide a more type safe API. E.g. make index a pojo typed on T which is aligned with the Param<T>\n return (Param<T>) params[index];\n }" ]
codesearchnet
{ "query": "Represent the comment about Software Development:", "pos": "Represent the code about Software Development:", "neg": "Represent the code about Software development:" }
send the transaction using the API @param string|array $signed @param string[] $paths @param bool $checkFee @return string the complete raw transaction @throws \Exception
[ "protected function sendTransaction($signed, $paths, $checkFee = false) {\n return $this->sdk->sendTransaction($this->identifier, $signed, $paths, $checkFee);\n }" ]
[ "public static function createNotMerged(Envelope $envelope, \\Exception $e = null)\n {\n $message = 'The given DigiDoc envelope must be merged with Api (using Api::merge) before calling this method.';\n\n return new static($message, null, $e);\n }" ]
codesearchnet
{ "query": "Represent the sentence about API documentation:", "pos": "Represent the code about API documentation:", "neg": "Represent the code about API documentation:" }
Register application provider Workaround for BC break in https://github.com/laravel/framework/pull/25028 @param string $providerName @param bool $force
[ "protected function appRegister($providerName, $force = false)\n {\n if (!$this->appRegisterParameters) {\n $method = new \\ReflectionMethod(get_class($this->app), 'register');\n $this->appRegisterParameters = count($method->getParameters());\n }\n\n if ($this->appRegisterParameters == 3) {\n $this->app->register($providerName, [], $force);\n } else {\n $this->app->register($providerName, $force);\n }\n }" ]
[ "private static function resource($resource)\n {\n exception_if(($resource != 'session' && $resource != 'cookie'), LogicException::class, 'The resource name of \\''.$resource.'\\' is not supported by Vinala, only session or cookie');\n\n return Hash::make(config('auth.'.$resource));\n\n // For more security, make for every user a resource name\n return Hash::make(config('auth.'.$resource).static::$user->rememberToken);\n }" ]
codesearchnet
{ "query": "Represent the summarization:", "pos": "Represent the code:", "neg": "Represent the code about Programming:" }
Sets or resets the order of the existing schemas in the current search path of the user. This is a PostgreSQL only function. @return void
[ "public function determineExistingSchemaSearchPaths()\n {\n $names = $this->getSchemaNames();\n $paths = $this->getSchemaSearchPaths();\n\n $this->existingSchemaPaths = array_filter($paths, static function ($v) use ($names) {\n return in_array($v, $names);\n });\n }" ]
[ "@Override\n protected List<SuperColumn> loadSuperColumns(String keyspace, String columnFamily, String rowId,\n String... superColumnNames) {\n throw new UnsupportedOperationException(\n \"Support for super columns is not available with DS java driver. Either use Thrift or pelops for the same\");\n }" ]
codesearchnet
{ "query": "Represent the Github summarization about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code about programming:" }
/* (non-Javadoc) @see javax.security.enterprise.authentication.mechanism.http.HttpMessageContext#forward(java.lang.String)
[ "@Override\n public AuthenticationStatus forward(String path) {\n try {\n RequestDispatcher requestDispatcher = request.getRequestDispatcher(path);\n requestDispatcher.forward(request, response);\n } catch (Exception e) {\n // TODO: Add serviceability message\n }\n return AuthenticationStatus.SEND_CONTINUE;\n }" ]
[ "@Override\n public void removeSSOCookieFromResponse(HttpServletResponse resp) {\n if (resp instanceof com.ibm.wsspi.webcontainer.servlet.IExtendedResponse) {\n ((com.ibm.wsspi.webcontainer.servlet.IExtendedResponse) resp).removeCookie(getSSOCookiename());\n removeJwtSSOCookies((com.ibm.wsspi.webcontainer.servlet.IExtendedResponse) resp);\n }\n }" ]
codesearchnet
{ "query": "Represent the summarization about Software development:", "pos": "Represent the code about Software development:", "neg": "Represent the code about Software development:" }
@param Shopgate_Model_XmlResultObject $itemNode @return Shopgate_Model_XmlResultObject
[ "public function asXml(Shopgate_Model_XmlResultObject $itemNode)\n {\n /**\n * @var Shopgate_Model_XmlResultObject $stockNode\n */\n $identifierNode = $itemNode->addChildWithCDATA('identifier', $this->getValue());\n $identifierNode->addAttribute('uid', $this->getUid());\n $identifierNode->addAttribute('type', $this->getType());\n\n return $itemNode;\n }" ]
[ "public function getFromId( $FileUploadId){\n $rest = $this->getService( self::API_UPLOAD . $FileUploadId);\n $rest->GET();\n\n return $rest->getResult( models\\FileSystem\\FileUpload::class);\n }" ]
codesearchnet
{ "query": "Represent the Github post about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code about Programming:" }
创建BeanCopier @param <T> 目标Bean类型 @param source 来源对象,可以是Bean或者Map @param dest 目标Bean对象 @param copyOptions 拷贝属性选项 @return BeanCopier
[ "public static <T> BeanCopier<T> create(Object source, T dest, CopyOptions copyOptions) {\r\n\t\treturn create(source, dest, dest.getClass(), copyOptions);\r\n\t}" ]
[ "public static XmlTypeConvert resolve(BeanUtils.CustomPropertyDescriptor filed) {\n XmlTypeConvert convert;\n if (filed.isGeneralType() || filed.isBasic()) {\n convert = XmlTypeConverterUtil.converters.get(filed.getTypeName());\n } else if (String.class.equals(filed.getRealType())) {\n convert = DEFAULT_CONVERTER;\n } else if (Collection.class.isAssignableFrom(filed.getRealType())) {\n //到这里的只有两种可能,一、用户没有指定converter;二、用户没有加注解XmlNode\n XmlNode xmlnode = filed.getAnnotation(XmlNode.class);\n if (xmlnode == null) {\n //用户没有添加xmlnode注解,使用默认converter\n convert = DEFAULT_CONVERTER;\n } else {\n //用户指定了xmlnode注解但是没有指定converter,使用general字段确定集合中的数据类型\n convert = (XmlConverter) xmlnode::general;\n }\n } else {\n //字段不是基本类型,假设是pojo,使用xml转换器\n convert = (XmlConverter) filed::getRealType;\n }\n return convert;\n }" ]
codesearchnet
{ "query": "Represent the Github sentence about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code about programming:" }
// SetCertificate sets the Certificate field's value.
[ "func (s *SslConfiguration) SetCertificate(v string) *SslConfiguration {\n\ts.Certificate = &v\n\treturn s\n}" ]
[ "private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {\n GetField fields = in.readFields();\n classLoaderIdentifier = (String) fields.get(CLASS_LOADER_IDENTIFIER, null);\n\n // Note that further processing is required in JEEMetadataContextProviderImpl.deserializeThreadContext\n // in order to re-establish the thread context based on the metadata identifier if not defaulted.\n }" ]
codesearchnet
{ "query": "Represent the Github post about Programming:", "pos": "Represent the Github code about Programming:", "neg": "Represent the Github code about programming:" }
/* (non-Javadoc) @see org.joml.Matrix4x3fc#rotateX(float, org.joml.Matrix4x3f)
[ "public Matrix4x3f rotateX(float ang, Matrix4x3f dest) {\n if ((properties & PROPERTY_IDENTITY) != 0)\n return dest.rotationX(ang);\n\n float sin, cos;\n if (ang == (float) Math.PI || ang == -(float) Math.PI) {\n cos = -1.0f;\n sin = 0.0f;\n } else if (ang == (float) Math.PI * 0.5f || ang == -(float) Math.PI * 1.5f) {\n cos = 0.0f;\n sin = 1.0f;\n } else if (ang == (float) -Math.PI * 0.5f || ang == (float) Math.PI * 1.5f) {\n cos = 0.0f;\n sin = -1.0f;\n } else {\n sin = (float) Math.sin(ang);\n cos = (float) Math.cosFromSin(sin, ang);\n }\n float rm11 = cos;\n float rm12 = sin;\n float rm21 = -sin;\n float rm22 = cos;\n\n // add temporaries for dependent values\n float nm10 = m10 * rm11 + m20 * rm12;\n float nm11 = m11 * rm11 + m21 * rm12;\n float nm12 = m12 * rm11 + m22 * rm12;\n // set non-dependent values directly\n dest.m20 = m10 * rm21 + m20 * rm22;\n dest.m21 = m11 * rm21 + m21 * rm22;\n dest.m22 = m12 * rm21 + m22 * rm22;\n // set other values\n dest.m10 = nm10;\n dest.m11 = nm11;\n dest.m12 = nm12;\n dest.m00 = m00;\n dest.m01 = m01;\n dest.m02 = m02;\n dest.m30 = m30;\n dest.m31 = m31;\n dest.m32 = m32;\n dest.properties = properties & ~(PROPERTY_IDENTITY | PROPERTY_TRANSLATION);\n return dest;\n }" ]
[ "public static double dot(@javax.annotation.Nonnull final List<double[]> a, @javax.annotation.Nonnull final List<double[]> b) {\n return com.simiacryptus.util.ArrayUtil.sum(com.simiacryptus.util.ArrayUtil.multiply(a, b));\n }" ]
codesearchnet
{ "query": "Represent the Github description about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code about Programming:" }
get the activity that is started by the first instruction, if exists; return null if the first instruction is a start-transition instruction
[ "protected ActivityImpl determineFirstActivity(ProcessDefinitionImpl processDefinition,\n ProcessInstanceModificationBuilderImpl modificationBuilder) {\n AbstractProcessInstanceModificationCommand firstInstruction = modificationBuilder.getModificationOperations().get(0);\n\n if (firstInstruction instanceof AbstractInstantiationCmd) {\n AbstractInstantiationCmd instantiationInstruction = (AbstractInstantiationCmd) firstInstruction;\n CoreModelElement targetElement = instantiationInstruction.getTargetElement(processDefinition);\n\n ensureNotNull(NotValidException.class,\n \"Element '\" + instantiationInstruction.getTargetElementId() + \"' does not exist in process \" + processDefinition.getId(),\n \"targetElement\",\n targetElement);\n\n if (targetElement instanceof ActivityImpl) {\n return (ActivityImpl) targetElement;\n }\n else if (targetElement instanceof TransitionImpl) {\n return (ActivityImpl) ((TransitionImpl) targetElement).getDestination();\n }\n\n }\n\n return null;\n }" ]
[ "def finish_parse(self, last_lineno_seen):\n \"\"\"\"\"\"\n if self.state == self.STATES['step_in_progress']:\n # We've reached the end of the log without seeing the final \"step finish\"\n # marker, which would normally have triggered updating the step. As such we\n # must manually close out the current step, so things like result, finish\n # time are set for it. This ensures that the error summary for Taskcluster\n # infra failures actually lists the error that occurs at the\n # end of the log.\n self.end_step(last_lineno_seen)" ]
codesearchnet
{ "query": "Represent the text:", "pos": "Represent the code:", "neg": "Represent the code about programming:" }
生成文件 @param template 模板 @param context 模板上下文 @param destPath 目标路径(绝对)
[ "public static void toFile(Template template, VelocityContext context, String destPath) {\r\n\t\tPrintWriter writer = null;\r\n\t\ttry {\r\n\t\t\twriter = FileUtil.getPrintWriter(destPath, Velocity.getProperty(Velocity.INPUT_ENCODING).toString(), false);\r\n\t\t\tmerge(template, context, writer);\r\n\t\t} catch (IORuntimeException e) {\r\n\t\t\tthrow new UtilException(e, \"Write Velocity content to [{}] error!\", destPath);\r\n\t\t} finally {\r\n\t\t\tIoUtil.close(writer);\r\n\t\t}\r\n\t}" ]
[ "private static function appRun(){\n // echo \"runing\";\n // 当有get参数传递时 获取get参数\n if(isset($_GET['s'])){\n // 更加\"/\"将get参数分割成数组\n $info = explode('/',$_GET['s']);\n\n // 获取模块名称 转换成小写\n $m = strtolower($info[0]);\n // 获取控制器名称 转换成小写\n $c = strtolower($info[1]);\n // 获取方法名称 转换成小写\n $a = strtolower($info[2]);\n\n }else{ // 当用户没有参数传递时设置默认参数\n\n // 模块名称 默认名称\n $m = 'home';\n // 默认控制器\n $c = 'entry';\n // 默认方法名称\n $a = 'index';\n }\n\n // 定义三个常量 将路由参照中的模块 控制器和方法定义成方法\n // 用于在view核心方法中能够访问到这些参数,凭借出模板的路径方便控制器载入模板\n\n // 模块常量\n define('MODULE',$m);\n // 控制器常量\n define('CONTROLLER',$c);\n // 方法名常量\n define('ACTION',$a);\n\n // 根据get参数的在自动执行对象类中的方法\n // 因为类名称首字母大写 为保持一致转换成大写\n $controller = ucfirst($c);\n\n // 拼接对应类的命名 ,实现不同参数调用不同的类,文件以及通过composer自动加载了\n // 路径如:\\app\\home\\controller\\Entry()\n // 其中上面路径中 app controller是固定不变的 ,\n // home:对应的模块\n // Entry: 方法名称\n // 拼接路径是需要将home 和Entry用变量替换\n $class = \"\\app\\\\{$m}\\controller\\\\{$controller}\";\n\n // 执行对应的方法 实现路由的分配\n // 通过echo 触发view 中Base类中的__toString 方法\n\n echo call_user_func_array([new $class,$a],[]);\n\n }" ]
codesearchnet
{ "query": "Represent the Github instruction about text processing:", "pos": "Represent the Github code about text processing:", "neg": "Represent the Github code:" }
Read cookie data from the request's cookie data. @param string $key The key you want to read. @return null|string Either the cookie value, or null if the value doesn't exist. @deprecated 3.4.0 Use getCookie() instead.
[ "public function cookie($key)\n {\n deprecationWarning(\n 'ServerRequest::cookie() is deprecated. ' .\n 'Use getCookie() instead.'\n );\n\n if (isset($this->cookies[$key])) {\n return $this->cookies[$key];\n }\n\n return null;\n }" ]
[ "function destroy()\n {\n /*\n * Cookies must be deleted with the same parameters as they were set with.\n * If the value argument is an empty string, or FALSE, and all other\n * arguments match a previous call to setcookie, then the cookie with the\n * specified name will be deleted from the remote client.\n * This is internally achieved by setting value to 'deleted' and expiration\n * time to one year in past.\n */\n foreach ($this as $k => $v)\n $this->_setCookieParam($k, null, -2628000);\n\n parent::destroy();\n }" ]
codesearchnet
{ "query": "Represent the Github comment:", "pos": "Represent the Github code:", "neg": "Represent the Github code about Database management:" }
Command line interface
[ "def main():\n \n parser = argparse.ArgumentParser(\n description='Extract the raw gps communication from an ULog file')\n parser.add_argument('filename', metavar='file.ulg', help='ULog input file')\n\n def is_valid_directory(parser, arg):\n \"\"\"Check if valid directory\"\"\"\n if not os.path.isdir(arg):\n parser.error('The directory {} does not exist'.format(arg))\n # File exists so return the directory\n return arg\n parser.add_argument('-o', '--output', dest='output', action='store',\n help='Output directory (default is CWD)',\n metavar='DIR', type=lambda x: is_valid_directory(parser, x))\n\n args = parser.parse_args()\n ulog_file_name = args.filename\n\n msg_filter = ['gps_dump']\n ulog = ULog(ulog_file_name, msg_filter)\n data = ulog.data_list\n\n output_file_prefix = os.path.basename(ulog_file_name)\n # strip '.ulg'\n if output_file_prefix.lower().endswith('.ulg'):\n output_file_prefix = output_file_prefix[:-4]\n\n # write to different output path?\n if args.output is not None:\n output_file_prefix = os.path.join(args.output, output_file_prefix)\n\n to_dev_filename = output_file_prefix+'_to_device.dat'\n from_dev_filename = output_file_prefix+'_from_device.dat'\n\n\n if len(data) == 0:\n print(\"File {0} does not contain gps_dump messages!\".format(ulog_file_name))\n exit(0)\n\n gps_dump_data = data[0]\n\n # message format check\n field_names = [f.field_name for f in gps_dump_data.field_data]\n if not 'len' in field_names or not 'data[0]' in field_names:\n print('Error: gps_dump message has wrong format')\n exit(-1)\n\n if len(ulog.dropouts) > 0:\n print(\"Warning: file contains {0} dropouts\".format(len(ulog.dropouts)))\n\n print(\"Creating files {0} and {1}\".format(to_dev_filename, from_dev_filename))\n\n with open(to_dev_filename, 'wb') as to_dev_file:\n with open(from_dev_filename, 'wb') as from_dev_file:\n msg_lens = gps_dump_data.data['len']\n for i in range(len(gps_dump_data.data['timestamp'])):\n msg_len = msg_lens[i]\n if msg_len & (1<<7):\n msg_len = msg_len & ~(1<<7)\n file_handle = to_dev_file\n else:\n file_handle = from_dev_file\n for k in range(msg_len):\n file_handle.write(gps_dump_data.data['data['+str(k)+']'][i])" ]
[ "@Override\n public void generatePluginConfig(String serverName, File writeDirectory) {\n // Pass true to utilityRequest since this method will be called from the pluginUtility\n // or by the GeneratePluginConfigListener not by a call to the mbean.\n generatePluginConfig(null,serverName,true,writeDirectory);\n \n }" ]
codesearchnet
{ "query": "Represent the Github instruction:", "pos": "Represent the Github code:", "neg": "Represent the Github code about programming:" }
Write the extension to the OutputStream. @param out the OutputStream to write the extension to @exception IOException on encoding errors
[ "public void encode(OutputStream out) throws IOException {\n DerOutputStream tmp = new DerOutputStream();\n if (extensionValue == null) {\n extensionId = PKIXExtensions.CertificateIssuer_Id;\n critical = true;\n encodeThis();\n }\n super.encode(tmp);\n out.write(tmp.toByteArray());\n }" ]
[ "@Override\n public XMLStreamReader2 createXMLStreamReader(File f)\n throws XMLStreamException\n {\n /* true for auto-close, since caller has no access to the underlying\n * input stream created from the File\n */\n return createSR(f, false, true);\n }" ]
codesearchnet
{ "query": "Represent the text about Programming:", "pos": "Represent the code about Programming:", "neg": "Represent the code about programming:" }
Expires the given session.
[ "private void expireSession(RaftSession session) {\n if (expiring.add(session.sessionId())) {\n log.debug(\"Expiring session due to heartbeat failure: {}\", session);\n appendAndCompact(new CloseSessionEntry(raft.getTerm(), System.currentTimeMillis(), session.sessionId().id(), true, false))\n .whenCompleteAsync((entry, error) -> {\n if (error != null) {\n expiring.remove(session.sessionId());\n return;\n }\n\n appender.appendEntries(entry.index()).whenComplete((commitIndex, commitError) -> {\n raft.checkThread();\n if (isRunning()) {\n if (commitError == null) {\n raft.getServiceManager().<Long>apply(entry.index())\n .whenCompleteAsync((r, e) -> expiring.remove(session.sessionId()), raft.getThreadContext());\n } else {\n expiring.remove(session.sessionId());\n }\n }\n });\n }, raft.getThreadContext());\n }\n }" ]
[ "def post_build(self, p, pay):\n \n p += pay\n if self.auxdlen != 0:\n print(\"NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).\")\n print(\" Subsequent Group Records are lost!\")\n return p" ]
codesearchnet
{ "query": "Represent the post about Technology:", "pos": "Represent the code about Technology:", "neg": "Represent the code:" }
Unserializes in instance from an ASCII safe string representation produced by __toString. @param string $string String representation @return BloomFilter Unserialized instance
[ "public static function unserializeFromStringRepresentation($string)\n {\n if (!preg_match('~k:(?P<k>\\d+)/m:(?P<m>\\d+)\\((?P<bitfield>[0-9a-zA-Z+/=]+)\\)~', $string, $matches)) {\n throw new InvalidArgumentException('Invalid string representation');\n }\n $bf = new self((int) $matches['m'], (int) $matches['k']);\n $bf->bitField = base64_decode($matches['bitfield']);\n return $bf;\n }" ]
[ "public function toFieldDefinition(StorageFieldDefinition $storageDef, FieldDefinition $fieldDef)\n {\n // @todo: Is it possible to store a default value in the DB?\n $fieldDef->defaultValue = new FieldValue();\n $fieldDef->defaultValue->data = array('text' => null);\n }" ]
codesearchnet
{ "query": "Represent the Github comment about Programming:", "pos": "Represent the Github code about Programming:", "neg": "Represent the Github code:" }
{@inheritDoc} @see \rocket\ei\manage\gui\GuiFieldEditable::createMag($propertyName)
[ "public function getMag(): Mag {\r\n\t\t$this->contentItemMag = new ContentItemMag($this->label, $this->panelConfigs,\r\n\t\t\t\t$this->targetReadEiFrame, $this->targetEditEiFrame);\r\n\t\t$this->contentItemMag->setNewMappingFormUrl($this->newMappingFormUrl);\r\n\t\t$this->contentItemMag->setValue($this->toManyEiField->getValue());\r\n\t\t$this->contentItemMag->setReduced($this->reduced);\r\n\t\treturn $this->contentItemMag;\r\n\t}" ]
[ "protected final function AddCssClassField()\n {\n $name = 'CssClass';\n $this->AddField(Input::Text($name, $this->Content()->GetCssClass()), false, Trans(\"Core.ContentForm.$name\"));\n }" ]
codesearchnet
{ "query": "Represent the Github comment:", "pos": "Represent the Github code:", "neg": "Represent the Github code:" }
Convert a string to a byte array, no encoding is used. String must only contain characters <256.
[ "public static byte[] str2bytes(String str) throws IOException {\r\n\t\tbyte[] b=new byte[str.length()];\r\n\t\tfor(int i=0; i<str.length(); ++i) {\r\n\t\t\tchar c=str.charAt(i);\t\r\n\t\t\tif(c>255) throw new UnsupportedEncodingException(\"string contained a char > 255, cannot convert to bytes\");\r\n\t\t\tb[i]=(byte)c;\r\n\t\t}\r\n\t\treturn b;\r\n\t}" ]
[ "public static String pathEncode(String path, Charset charset) {\n return encodeReserved(path, FragmentType.PATH_SEGMENT, charset);\n\n /*\n * path encoding is not equivalent to query encoding, there are few differences, namely dealing\n * with spaces, !, ', (, ), and ~ characters. we will need to manually process those values.\n */\n // return encoded.replaceAll(\"\\\\+\", \"%20\");\n }" ]
codesearchnet
{ "query": "Represent the text about Programming:", "pos": "Represent the code about Programming:", "neg": "Represent the code about Programming:" }
Convenient Method for the vibrato effekt @param aktMemo
[ "protected void doVibratoEffekt(ChannelMemory aktMemo)\n\t{\n\t\tint periodAdd;\n\t\tswitch (aktMemo.vibratoType & 0x03)\n\t\t{\n\t\t\tcase 1: periodAdd = (Helpers.ModRampDownTable[aktMemo.vibratoTablePos]);\t// Sawtooth\n\t\t\t\t\tbreak;\n\t\t\tcase 2: periodAdd = (Helpers.ModSquareTable [aktMemo.vibratoTablePos]);\t// Squarewave\n\t\t\t\t\tbreak;\n\t\t\tcase 3:\tperiodAdd = (Helpers.ModRandomTable [aktMemo.vibratoTablePos]);\t// Random.\n\t\t\t\t\tbreak;\n\t\t\tdefault:periodAdd = (Helpers.ModSinusTable [aktMemo.vibratoTablePos]);\t// Sinus\n\t\t\t\t\tbreak;\n\t\t}\n\t\t\n\t\tperiodAdd = ((periodAdd<<4)*aktMemo.vibratoAmplitude) >> 7;\n\t\tsetNewPlayerTuningFor(aktMemo, aktMemo.currentNotePeriod + periodAdd);\n\t\t\n\t\taktMemo.vibratoTablePos = (aktMemo.vibratoTablePos + aktMemo.vibratoStep) & 0x3F;\n\t}" ]
[ "def :\n \"\"\"\"\"\"\n CheckParent(self)\n\n return _fitz.Annot_" ]
codesearchnet
{ "query": "Represent the text:", "pos": "Represent the code:", "neg": "Represent the code:" }
Get the value of a cookie. @param $name @param null $default @return null|string
[ "public static function get($name, $default = null)\n {\n if (isset(static::$jar[$name])) {\n return static::parse(static::$jar[$name]['value']);\n }\n\n $cookie = Request::$cookieData;\n\n if (!is_null($value = $cookie->get($name))) {\n return static::parse($value);\n }\n\n return $default;\n }" ]
[ "private function getFormOptionsDeclaration()\n {\n\n // we got a max instances allowed in normality tags\n $formOptions = json_encode( $this->formOptions );\n $formOptions = Php::varExport( $formOptions, true );\n\n $this->class->classComponents[] = new VariableDeclaration(\n 'formOptions',\n new SFormatf( <<<'PHP'\n /**\n * Form options from relation\n * @var array\n */\n protected $formOptions = %s;\nPHP\n , $formOptions\n )\n );\n\n }" ]
codesearchnet
{ "query": "Represent the Github text about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code about programming:" }
Rails controller stuff ========================
[ "def setup\n set_descriptor :default \n\n get_mxit_info\n\n @_mxit = descriptor\n @_mxit_validated = true\n @_mxit_validation_types = []\n @_mxit_validation_messages = []\n @_mxit_emulator = request.headers['X-Mxit-UserId-R'].nil?\n\n clean_session\n\n # Tidy multi-select if needed\n if params.include? :_mxit_rails_multi_select\n input = params[:_mxit_rails_multi_select].to_sym\n params.delete :_mxit_rails_multi_select\n\n array = mxit_form_session[input] || []\n array.map! {|item| item.to_sym}\n set = Set.new array\n\n if params.include? :_mxit_rails_multi_select_value\n value = params[:_mxit_rails_multi_select_value].to_sym\n params.delete :_mxit_rails_multi_select_value\n if set.include? value\n set.delete value\n else\n set.add value\n end\n end\n\n params[input] = set.to_a.map {|item| item.to_s}\n mxit_form_session[input] = set.to_a.map {|item| item.to_sym}\n end\n end" ]
[ "public static function ws()\n {\n if (!isset(self::core()->soap)) {\n //====================================================================//\n // WEBSERVICE INITIALISATION\n //====================================================================//\n // Initialize SOAP WebServices Class\n self::core()->soap = new Webservice();\n\n //====================================================================//\n // Initialize WebService Configuration Array\n self::core()->soap->setup();\n\n //====================================================================//\n // Load Translation File\n self::translator()->load('ws');\n }\n\n return self::core()->soap;\n }" ]
codesearchnet
{ "query": "Represent the Github description:", "pos": "Represent the Github code:", "neg": "Represent the Github code:" }
@param \Spryker\Yves\Kernel\Container $container @return \Spryker\Yves\Kernel\Container
[ "public function provideDependencies(Container $container)\n {\n $container[self::CLIENT_PAYONE] = function (Container $container) {\n return $container->getLocator()->payone()->client();\n };\n\n $container[self::CLIENT_CUSTOMER] = function (Container $container) {\n return new PayoneToCustomerBridge($container->getLocator()->customer()->client());\n };\n\n $container[self::CLIENT_CART] = function (Container $container) {\n return new PayoneToCartBridge($container->getLocator()->cart()->client());\n };\n\n $container[self::CLIENT_SHIPMENT] = function (Container $container) {\n return new PayoneToShipmentBridge($container->getLocator()->shipment()->client());\n };\n\n $container[self::CLIENT_CALCULATION] = function (Container $container) {\n return new PayoneToCalculationBridge($container->getLocator()->calculation()->client());\n };\n\n return $container;\n }" ]
[ "public function boot(\\Neos\\Flow\\Core\\Bootstrap $bootstrap)\n {\n $bootstrap->registerRequestHandler(new \\Neos\\Setup\\Core\\RequestHandler($bootstrap));\n }" ]
codesearchnet
{ "query": "Represent the Github post about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code about Software development:" }
State for handling dateto:foo constructs. Potentially emits a token.
[ "function indateto($content){\n if (strlen($content) < 8) { // State exit or missing parameter.\n return true;\n }\n // Strip off the dateto: part and add the reminder to the parsed token array\n $param = trim(substr($content,7));\n $this->tokens[] = new search_token(TOKEN_DATETO,$param);\n return true;\n }" ]
[ "def star_sep_check(self, original, loc, tokens):\n \"\"\"\"\"\"\n return self.check_py(\"3\", \"keyword-only argument separator (add 'match' to front to produce universal code)\", original, loc, tokens)" ]
codesearchnet
{ "query": "Represent the post about programming:", "pos": "Represent the code about programming:", "neg": "Represent the code:" }
// WithAnnotations appends or replaces the annotations on the spec with the // provided annotations
[ "func WithAnnotations(annotations map[string]string) SpecOpts {\n\treturn func(_ context.Context, _ Client, _ *containers.Container, s *Spec) error {\n\t\tif s.Annotations == nil {\n\t\t\ts.Annotations = make(map[string]string)\n\t\t}\n\t\tfor k, v := range annotations {\n\t\t\ts.Annotations[k] = v\n\t\t}\n\t\treturn nil\n\t}\n}" ]
[ "@Override\n public void addElement(Map<String, Object> e, Map<String, AggregatorFactory> a)\n {\n // since we return a constant, no need to read from the event\n }" ]
codesearchnet
{ "query": "Represent the Github sentence:", "pos": "Represent the Github code:", "neg": "Represent the Github code:" }
Array to mapper criteria @param array $values @param boolean $qmMode force question mark placeholder @return string
[ "public static function buildCriteria(array $values, $qmMode = false)\n {\n reset($values);\n $qmMode = $qmMode ?: is_numeric(key($values));\n\n if ($qmMode) {\n $result = array_values($values);\n array_unshift($result, str_repeat('?,', count($values)-1).'?');\n\n return $result;\n }\n\n $result = [''];\n foreach ($values as $key => $value) {\n $key = \":$key\";\n $result[0] .= ($result[0]?',':'').$key;\n $result[$key] = $value;\n }\n\n return $result;\n }" ]
[ "def build(self):\n \"\"\"\"\"\"\n from ambry.orm.config import BuildConfigGroupAccessor\n\n # It is a lightweight object, so no need to cache\n return BuildConfigGroupAccessor(self.dataset, 'buildstate', self._session)" ]
codesearchnet
{ "query": "Represent the Github summarization about Software development:", "pos": "Represent the Github code about Software development:", "neg": "Represent the Github code:" }
// NewKey returns a new key that can be used to encrypt and decrypt messages.
[ "func NewKey() (*[SecretKeyLength]byte, error) {\n\t// get 32-bytes of random from /dev/urandom\n\tbytes, err := randomProvider.Bytes(SecretKeyLength)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"unable to generate random: %v\", err)\n\t}\n\n\treturn KeySliceToArray(bytes)\n}" ]
[ "func (h Handler) GetE(cmd common.GetRequest) (<-chan common.GetEResponse, <-chan error) {\n\t// Being minimalist, not lazy. The chunked handler is not meant to be used with a\n\t// backing store that supports the GetE protocol extension. It would be a waste of\n\t// time and effort to support it here if it would \"never\" be used. It will be added\n\t// as soon as a case for it exists.\n\t//\n\t// The GetE extension is an addition that only rend supports. This chunked handler\n\t// is pretty explicitly for talking to memcached since it is a complex workaround\n\t// for pathological behavior when data size rapidly changes that only happens in\n\t// memcached. The chunked handler will not work well with the L2 the EVCache team\n\t// uses.\n\tpanic(\"GetE not supported in Rend chunked mode\")\n}" ]
codesearchnet
{ "query": "Represent the post about Programming:", "pos": "Represent the code about Programming:", "neg": "Represent the code about Software development:" }
Write data to the connection @param string $data
[ "protected function write(string $data)\n {\n $this->clearTimeout();\n $this->conn->write($data . static::NEW_LINE);\n $this->log('<-' . $data);\n $this->setTimeout();\n }" ]
[ "def getKeySequenceCounter(self):\n \"\"\"\"\"\"\n print '%s call getKeySequenceCounter' % self.port\n keySequence = ''\n keySequence = self.__sendCommand(WPANCTL_CMD + 'getprop -v Network:KeyIndex')[0]\n return keySequence" ]
codesearchnet
{ "query": "Represent the text about programming:", "pos": "Represent the code about programming:", "neg": "Represent the code:" }
Drops the user into an interactive Python session with the ``sess`` variable set to the current session instance. If keyword arguments are supplied, these names will also be available within the session.
[ "def interact(self, **local):\n \n import code\n code.interact(local=dict(sess=self, **local))" ]
[ "def resolveEntryPoint(entryPoint):\n \n if inVirtualEnv():\n path = os.path.join(os.path.dirname(sys.executable), entryPoint)\n # Inside a virtualenv we try to use absolute paths to the entrypoints.\n if os.path.isfile(path):\n # If the entrypoint is present, Toil must have been installed into the virtualenv (as\n # opposed to being included via --system-site-packages). For clusters this means that\n # if Toil is installed in a virtualenv on the leader, it must be installed in\n # a virtualenv located at the same path on each worker as well.\n assert os.access(path, os.X_OK)\n return path\n else:\n # For virtualenv's that have the toil package directory on their sys.path but whose\n # bin directory lacks the Toil entrypoints, i.e. where Toil is included via\n # --system-site-packages, we rely on PATH just as if we weren't in a virtualenv.\n return entryPoint\n else:\n # Outside a virtualenv it is hard to predict where the entry points got installed. It is\n # the responsibility of the user to ensure that they are present on PATH and point to the\n # correct version of Toil. This is still better than an absolute path because it gives\n # the user control over Toil's location on both leader and workers.\n return entryPoint" ]
codesearchnet
{ "query": "Represent the summarization:", "pos": "Represent the code:", "neg": "Represent the code about Software development:" }
Set a new state to the underlying object @param string $state @throws SMException
[ "protected function setState($state)\n {\n if (!in_array($state, $this->config['states'])) {\n throw new SMException(sprintf(\n 'Cannot set the state to \"%s\" to object \"%s\" with graph %s because it is not pre-defined.',\n $state,\n get_class($this->object),\n $this->config['graph']\n ));\n }\n\n $accessor = new PropertyAccessor();\n $accessor->setValue($this->object, $this->config['property_path'], $state);\n }" ]
[ "def :\n \"\"\"\"\"\"\n CheckParent(self)\n\n return _fitz.Annot_" ]
codesearchnet
{ "query": "Represent the Github instruction about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code:" }
EVENTS Event handler for a touch start event. Stops the default click event from triggering and stores where we touched @inner @param {object} jqEvent The normalised jQuery event object.
[ "function touchStart(jqEvent) {\n\t\t\t//If we already in a touch event (a finger already in use) then ignore subsequent ones..\n\t\t\tif( getTouchInProgress() )\n\t\t\t\treturn;\n\t\t\t\n\t\t\t//Check if this element matches any in the excluded elements selectors, or its parent is excluded, if so, DON'T swipe\n\t\t\tif( $(jqEvent.target).closest( options.excludedElements, $element ).length>0 ) \n\t\t\t\treturn;\n\t\t\t\t\n\t\t\t//As we use Jquery bind for events, we need to target the original event object\n\t\t\t//If these events are being programmatically triggered, we don't have an original event object, so use the Jq one.\n\t\t\tvar event = jqEvent.originalEvent ? jqEvent.originalEvent : jqEvent;\n\t\t\t\n\t\t\tvar ret,\n\t\t\t\ttouches = event.touches,\n\t\t\t\tevt = touches ? touches[0] : event;\n\n\t\t\tphase = PHASE_START;\n\n\t\t\t//If we support touches, get the finger count\n\t\t\tif (touches) {\n\t\t\t\t// get the total number of fingers touching the screen\n\t\t\t\tfingerCount = touches.length;\n\t\t\t}\n\t\t\t//Else this is the desktop, so stop the browser from dragging content\n\t\t\telse {\n\t\t\t\tjqEvent.preventDefault(); //call this on jq event so we are cross browser\n\t\t\t}\n\n\t\t\t//clear vars..\n\t\t\tdistance = 0;\n\t\t\tdirection = null;\n\t\t\tpinchDirection=null;\n\t\t\tduration = 0;\n\t\t\tstartTouchesDistance=0;\n\t\t\tendTouchesDistance=0;\n\t\t\tpinchZoom = 1;\n\t\t\tpinchDistance = 0;\n\t\t\tfingerData=createAllFingerData();\n\t\t\tmaximumsMap=createMaximumsData();\n\t\t\tcancelMultiFingerRelease();\n\n\t\t\t\n\t\t\t// check the number of fingers is what we are looking for, or we are capturing pinches\n\t\t\tif (!touches || (fingerCount === options.fingers || options.fingers === ALL_FINGERS) || hasPinches()) {\n\t\t\t\t// get the coordinates of the touch\n\t\t\t\tcreateFingerData( 0, evt );\n\t\t\t\tstartTime = getTimeStamp();\n\t\t\t\t\n\t\t\t\tif(fingerCount==2) {\n\t\t\t\t\t//Keep track of the initial pinch distance, so we can calculate the diff later\n\t\t\t\t\t//Store second finger data as start\n\t\t\t\t\tcreateFingerData( 1, touches[1] );\n\t\t\t\t\tstartTouchesDistance = endTouchesDistance = calculateTouchesDistance(fingerData[0].start, fingerData[1].start);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tif (options.swipeStatus || options.pinchStatus) {\n\t\t\t\t\tret = triggerHandler(event, phase);\n\t\t\t\t}\n\t\t\t}\n\t\t\telse {\n\t\t\t\t//A touch with more or less than the fingers we are looking for, so cancel\n\t\t\t\tret = false; \n\t\t\t}\n\n\t\t\t//If we have a return value from the users handler, then return and cancel\n\t\t\tif (ret === false) {\n\t\t\t\tphase = PHASE_CANCEL;\n\t\t\t\ttriggerHandler(event, phase);\n\t\t\t\treturn ret;\n\t\t\t}\n\t\t\telse {\n\t\t\t\tif (options.hold) {\n\t\t\t\t\tholdTimeout = setTimeout($.proxy(function() {\n\t\t\t\t\t\t//Trigger the event\n\t\t\t\t\t\t$element.trigger('hold', [event.target]);\n\t\t\t\t\t\t//Fire the callback\n\t\t\t\t\t\tif(options.hold) {\n\t\t\t\t\t\t\tret = options.hold.call($element, event, event.target);\n\t\t\t\t\t\t}\n\t\t\t\t\t}, this), options.longTapThreshold );\n\t\t\t\t}\n\n\t\t\t\tsetTouchInProgress(true);\n\t\t\t}\n\n return null;\n\t\t}" ]
[ "function() {\n var events = this.eventDelegates;\n log.events && (Object.keys(events).length > 0) && console.log('[%s] addHostListeners:', this.localName, events);\n // NOTE: host events look like bindings but really are not;\n // (1) we don't want the attribute to be set and (2) we want to support\n // multiple event listeners ('host' and 'instance') and Node.bind\n // by default supports 1 thing being bound.\n for (var type in events) {\n var methodName = events[type];\n PolymerGestures.addEventListener(this, type, this.element.getEventHandler(this, this, methodName));\n }\n }" ]
codesearchnet
{ "query": "Represent the summarization:", "pos": "Represent the code:", "neg": "Represent the code:" }
// SetTagList sets the TagList field's value.
[ "func (s *TagListMessage) SetTagList(v []*Tag) *TagListMessage {\n\ts.TagList = v\n\treturn s\n}" ]
[ "private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {\n GetField fields = in.readFields();\n beginDefaultContext = fields.get(BEGIN_DEFAULT, true);\n\n // Note that further processing is required in JEEMetadataContextProviderImpl.deserializeThreadContext\n // in order to re-establish the thread context based on the metadata identity if not defaulted.\n }" ]
codesearchnet
{ "query": "Represent the sentence about programming:", "pos": "Represent the code about programming:", "neg": "Represent the code about programming:" }
// 修改默认或者说全局 appname(应用名)
[ "func (l *Live) SetAppName(appname string) *Live {\n\tl.liveReq.AppName = appname\n\treturn l\n}" ]
[ "private static function appRun(){\n // echo \"runing\";\n // 当有get参数传递时 获取get参数\n if(isset($_GET['s'])){\n // 更加\"/\"将get参数分割成数组\n $info = explode('/',$_GET['s']);\n\n // 获取模块名称 转换成小写\n $m = strtolower($info[0]);\n // 获取控制器名称 转换成小写\n $c = strtolower($info[1]);\n // 获取方法名称 转换成小写\n $a = strtolower($info[2]);\n\n }else{ // 当用户没有参数传递时设置默认参数\n\n // 模块名称 默认名称\n $m = 'home';\n // 默认控制器\n $c = 'entry';\n // 默认方法名称\n $a = 'index';\n }\n\n // 定义三个常量 将路由参照中的模块 控制器和方法定义成方法\n // 用于在view核心方法中能够访问到这些参数,凭借出模板的路径方便控制器载入模板\n\n // 模块常量\n define('MODULE',$m);\n // 控制器常量\n define('CONTROLLER',$c);\n // 方法名常量\n define('ACTION',$a);\n\n // 根据get参数的在自动执行对象类中的方法\n // 因为类名称首字母大写 为保持一致转换成大写\n $controller = ucfirst($c);\n\n // 拼接对应类的命名 ,实现不同参数调用不同的类,文件以及通过composer自动加载了\n // 路径如:\\app\\home\\controller\\Entry()\n // 其中上面路径中 app controller是固定不变的 ,\n // home:对应的模块\n // Entry: 方法名称\n // 拼接路径是需要将home 和Entry用变量替换\n $class = \"\\app\\\\{$m}\\controller\\\\{$controller}\";\n\n // 执行对应的方法 实现路由的分配\n // 通过echo 触发view 中Base类中的__toString 方法\n\n echo call_user_func_array([new $class,$a],[]);\n\n }" ]
codesearchnet
{ "query": "Represent the instruction:", "pos": "Represent the code:", "neg": "Represent the code:" }
/*[deutsch] <p>Rollt dieses zyklische Jahr um den angegebenen Betrag. </p> @param amount determines how many years/units this instance should be rolled @return changed copy of this instance
[ "public CyclicYear roll(int amount) {\n\n if (amount == 0) {\n return this;\n }\n\n return CyclicYear.of(MathUtils.floorModulo(MathUtils.safeAdd(this.year - 1, amount), 60) + 1);\n\n }" ]
[ "protected function processEntityFormRequest(Entity $entity, FormData $requestData, $revision) {\n $dataName = 'layoutManager';\n \n if (isset($requestData->$dataName) && count($requestData->$dataName) > 0) {\n $serialized = $requestData->$dataName;\n } /*else {\n throw $this->err->validationError($dataName, NULL, new \\Psc\\Exception('Das Layout muss mindestens 1 Element enthalten'));\n }*/\n \n // da wir keine unique constraints haben und neu sortieren müssen , nehmen wir die holzhammer methode:\n // delete all\n foreach ($entity->getEntries() as $entry) {\n // den entry selbst löschen\n $this->repository->remove($entry);\n }\n // auch aus dem CS löschen, weil der sonst automatisch persisted und das remove oben keinen effect hat\n $entity->getEntries()->clear();\n\n /*\n PS: im Moment werden Entries von ContentStreams innerhalb des ContentStreams nicht mit delete all gelöscht\n d.h. hier bleiben relativ viele leichen übrig (auch contentstreams selbst). Bei unserialize wird im \n sub-ContentStream einfach eine neue instanz erzeugt die dann automatisch persisted wird\n */\n \n if (isset($serialized)) {\n // persist new\n $this->getContentStreamConverter()->convertUnserialized($requestData->$dataName, $entity);\n }\n }" ]
codesearchnet
{ "query": "Represent the comment about Programming:", "pos": "Represent the code about Programming:", "neg": "Represent the code:" }
Add a task to the executor, it is expected that this method is called on the ResultReceiver thread.
[ "public void addTask (ExecutorTask task)\n {\n for (int ii=0, nn=_queue.size(); ii < nn; ii++) {\n ExecutorTask taskOnQueue = _queue.get(ii);\n if (taskOnQueue.merge(task)) {\n return;\n }\n }\n\n // otherwise, add it on\n _queue.add(task);\n\n // and perhaps start it going now\n if (!_executingNow) {\n checkNext();\n }\n }" ]
[ "def start(self, timeout=None):\n \n\n started = super(Node, self).start(timeout=timeout)\n if started:\n # TODO : return something produced in the context manager passed\n return self._svc_address # returning the zmp url as a way to connect to the node\n # CAREFUL : doesnt make sense if this node only run a one-time task...\n # TODO: futures and ThreadPoolExecutor (so we dont need to manage the pool ourselves)\n else:\n return False" ]
codesearchnet
{ "query": "Represent the summarization about Software development:", "pos": "Represent the code about Software development:", "neg": "Represent the code about programming:" }
// List lists the buildclient using the OpenShift client.
[ "func (c *ClientBuildConfigLister) List(label labels.Selector) ([]*buildv1.BuildConfig, error) {\n\tlist, err := c.client.BuildConfigs(metav1.NamespaceAll).List(metav1.ListOptions{LabelSelector: label.String()})\n\treturn buildConfigListToPointerArray(list), err\n}" ]
[ "@Override\n public void generatePluginConfig(String serverName, File writeDirectory) {\n // Pass true to utilityRequest since this method will be called from the pluginUtility\n // or by the GeneratePluginConfigListener not by a call to the mbean.\n generatePluginConfig(null,serverName,true,writeDirectory);\n \n }" ]
codesearchnet
{ "query": "Represent the Github description:", "pos": "Represent the Github code:", "neg": "Represent the Github code about programming:" }
Return True if the media type is a valid form media type.
[ "def is_form_media_type(media_type):\n \n base_media_type, params = parse_header(media_type.encode(HTTP_HEADER_ENCODING))\n return (base_media_type == 'application/x-www-form-urlencoded' or\n base_media_type == 'multipart/form-data')" ]
[ "def initialize(self, id=None, text=None):\n self.id = none_or(id, int)\n \n\n self.text = none_or(text, str)\n \"\"\"\n Username or IP address of the user at the time of the edit : str | None\n \"\"\"" ]
codesearchnet
{ "query": "Represent the Github description about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code about programming:" }
Saves relation between optimizer and search container @param \Magento\Framework\Model\AbstractModel $object Optimizer to save @return void
[ "private function saveSearchContainerRelation(\\Magento\\Framework\\Model\\AbstractModel $object)\n {\n $searchContainers = $object->getSearchContainer();\n\n if (is_array($searchContainers) && (count($searchContainers) > 0)) {\n $searchContainerLinks = [];\n $deleteCondition = OptimizerInterface::OPTIMIZER_ID . \" = \" . $object->getId();\n\n foreach ($searchContainers as $searchContainer) {\n $searchContainerName = (string) $searchContainer;\n // Treat autocomplete apply_to like the quick search.\n if ($searchContainerName === 'catalog_product_autocomplete') {\n $searchContainerName = 'quick_search_container';\n }\n $searchContainerData = $object->getData($searchContainerName);\n $applyTo = is_array($searchContainerData) ? ((bool) $searchContainerData['apply_to'] ?? false) : false;\n $searchContainerLinks[(string) $searchContainer] = [\n OptimizerInterface::OPTIMIZER_ID => (int) $object->getId(),\n OptimizerInterface::SEARCH_CONTAINER => (string) $searchContainer,\n 'apply_to' => (int) $applyTo,\n ];\n }\n\n $this->getConnection()->delete($this->getTable(OptimizerInterface::TABLE_NAME_SEARCH_CONTAINER), $deleteCondition);\n $this->getConnection()->insertOnDuplicate(\n $this->getTable(OptimizerInterface::TABLE_NAME_SEARCH_CONTAINER),\n $searchContainerLinks\n );\n }\n }" ]
[ "protected function process()\n {\n\n // add the SKU => entity ID/store view code mapping\n $this->addSkuEntityIdMapping($sku = $this->getValue(ColumnKeys::SKU));\n $this->addSkuStoreViewCodeMapping($sku, $this->getSubject()->getStoreViewCode(StoreViewCodes::ADMIN));\n\n // clean-up the repositories etc. to free memory\n $this->getProductBunchProcessor()->cleanUp();\n\n // temporary persist the SKU\n $this->setLastSku($sku);\n }" ]
codesearchnet
{ "query": "Represent the Github sentence:", "pos": "Represent the Github code:", "neg": "Represent the Github code about Software development:" }
// SetProcessingConfiguration sets the ProcessingConfiguration field's value.
[ "func (s *ExtendedS3DestinationUpdate) SetProcessingConfiguration(v *ProcessingConfiguration) *ExtendedS3DestinationUpdate {\n\ts.ProcessingConfiguration = v\n\treturn s\n}" ]
[ "private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {\n GetField fields = in.readFields();\n beginDefaultContext = fields.get(BEGIN_DEFAULT, true);\n\n // Note that further processing is required in JEEMetadataContextProviderImpl.deserializeThreadContext\n // in order to re-establish the thread context based on the metadata identity if not defaulted.\n }" ]
codesearchnet
{ "query": "Represent the Github description about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code about programming:" }
Pass through to provider CommentLookupSession.use_federated_book_view
[ "def use_federated_book_view(self):\n \"\"\"\"\"\"\n self._book_view = FEDERATED\n # self._get_provider_session('comment_lookup_session') # To make sure the session is tracked\n for session in self._get_provider_sessions():\n try:\n session.use_federated_book_view()\n except AttributeError:\n pass" ]
[ "def includeme(config):\n \n root = config.get_root_resource()\n root.add('nef_polymorphic', '{collections:.+,.+}',\n view=PolymorphicESView,\n factory=PolymorphicACL)" ]
codesearchnet
{ "query": "Represent the sentence:", "pos": "Represent the code:", "neg": "Represent the code:" }
/*JWTBearerInterface
[ "public function getClientKey($client_id, $subject)\n {\n if (isset($this->jwt[$client_id])) {\n $jwt = $this->jwt[$client_id];\n if ($jwt) {\n if ($jwt[\"subject\"] == $subject) {\n return $jwt[\"key\"];\n }\n }\n }\n\n return false;\n }" ]
[ "public Descriptor withExceptionSerializer(ExceptionSerializer exceptionSerializer) {\n return new Descriptor(name, calls, pathParamSerializers, messageSerializers, serializerFactory, exceptionSerializer, autoAcl, acls, headerFilter, locatableService, circuitBreaker, topicCalls);\n }" ]
codesearchnet
{ "query": "Represent the instruction:", "pos": "Represent the code:", "neg": "Represent the code about programming:" }
Return URL string of Atom link element under parent element. Link with no rel attribute is considered to be rel="alternate" @param parent Consider only children of this parent element @param rel Consider only links with this relationship
[ "private String findAtomLink(final Element parent, final String rel) {\n String ret = null;\n final List<Element> linksList = parent.getChildren(\"link\", ATOM_10_NS);\n if (linksList != null) {\n for (final Element element : linksList) {\n final Element link = element;\n final Attribute relAtt = getAttribute(link, \"rel\");\n final Attribute hrefAtt = getAttribute(link, \"href\");\n if (relAtt == null && \"alternate\".equals(rel) || relAtt != null && relAtt.getValue().equals(rel)) {\n ret = hrefAtt.getValue();\n break;\n }\n }\n }\n return ret;\n }" ]
[ "def reset(self):\n \n\n # Use first matching element as title (0 or more xpath expressions)\n self.title = OrderedSet()\n\n # Use first matching element as body (0 or more xpath expressions)\n self.body = OrderedSet()\n\n # Use first matching element as author (0 or more xpath expressions)\n self.author = OrderedSet()\n\n # Use first matching element as date (0 or more xpath expressions)\n self.date = OrderedSet()\n\n # Put language here. It's not supported in siteconfig syntax,\n # but having it here allows more generic handling in extractor.\n self.language = (\n '//html[@lang]/@lang',\n '//meta[@name=\"DC.language\"]/@content',\n )\n\n # Strip elements matching these xpath expressions (0 or more)\n self.strip = OrderedSet()\n\n # Strip 0 or more elements which contain these\n # strings in the id or class attribute.\n self.strip_id_or_class = OrderedSet()\n\n # Strip 0 or more images which contain\n # these strings in the src attribute.\n self.strip_image_src = OrderedSet()\n\n # Additional HTTP headers to send\n # NOT YET USED\n self.http_header = OrderedSet()\n\n # For those 3, None means that default will be used. But we need\n # None to distinguish from False during multiple configurations\n # merges.\n self.tidy = None\n self.prune = None\n self.autodetect_on_failure = None\n\n # Test URL - if present, can be used to test the config above\n self.test_url = OrderedSet()\n self.test_contains = OrderedSet()\n\n # Single-page link should identify a link element or URL pointing\n # to the page holding the entire article.\n #\n # This is useful for sites which split their articles across\n # multiple pages. Links to such pages tend to display the first\n # page with links to the other pages at the bottom.\n #\n # Often there is also a link to a page which displays the entire\n # article on one page (e.g. 'print view').\n #\n # `single_page_link` should be an XPath expression identifying the\n # link to that single page. If present and we find a match, we will\n # retrieve that page and the rest of the options in this config will\n # be applied to the new page.\n self.single_page_link = OrderedSet()\n\n self.next_page_link = OrderedSet()\n\n # Single-page link in feed? - same as above, but patterns applied\n # to item description HTML taken from feed. XXX\n self.single_page_link_in_feed = OrderedSet()\n\n # Which parser to use for turning raw HTML into a DOMDocument,\n # either `libxml` (PHP) / `lxml` (Python) or `html5lib`. Defaults\n # to `lxml` if None.\n self.parser = None\n\n # Strings to search for in HTML before processing begins. Goes by\n # pairs with `replace_string`. Not a set because we can have more\n # than one of the same, to be replaced by different values.\n self.find_string = []\n\n # Strings to replace those found in `find_string` before HTML\n # processing begins.\n self.replace_string = []" ]
codesearchnet
{ "query": "Represent the Github post about text processing:", "pos": "Represent the Github code about text processing:", "neg": "Represent the Github code about programming:" }
Render page with assessment(s) result. @throws \common_exception_Error @throws \common_exception_MissingParameter @throws \oat\oatbox\service\ServiceNotFoundException
[ "public function printReport()\n {\n if (!$this->hasRequestParameter('id')) {\n throw new \\common_exception_MissingParameter('id');\n }\n $idList = $this->getRequestParameter('id');\n $context = $this->getRequestParameter('context');\n if (!is_array($idList)) {\n $idList = [$idList];\n }\n $result = [];\n\n /** @var ProctorService $deliveryService */\n $deliveryService = ServiceManager::getServiceManager()->get(ProctorService::SERVICE_ID);\n $currentUser = \\common_session_SessionManager::getSession()->getUser();\n $deliveries = $deliveryService->getProctorableDeliveries($currentUser, $context);\n\n /** @var $assessmentResultsService AssessmentResultsService */\n $assessmentResultsService = $this->getServiceManager()->get(AssessmentResultsService::SERVICE_ID);\n\n foreach ($idList as $deliveryExecutionId) {\n $deliveryExecution = ServiceProxy::singleton()->getDeliveryExecution($deliveryExecutionId);\n $delivery = $deliveryExecution->getDelivery();\n if (!isset($deliveries[$delivery->getUri()])) {\n \\common_Logger::i('Attempt to print assessment results for which the proctor ' . $currentUser->getIdentifier() . ' has no access.');\n continue;\n }\n $deliveryData = $assessmentResultsService->getDeliveryData($deliveryExecution);\n if (!$deliveryData['end']) {\n continue;\n }\n $result[] = [\n 'testTakerData' => $assessmentResultsService->getTestTakerData($deliveryExecution),\n 'testData' => $assessmentResultsService->getTestData($deliveryExecution),\n 'resultsData' => $assessmentResultsService->getResultsData($deliveryExecution),\n 'deliveryData' => $deliveryData,\n ];\n }\n\n $this->setData('reports', $result);\n $this->setData('content-template', 'Reporting/print_report.tpl');\n $this->setView('Reporting/layout.tpl');\n }" ]
[ "public static function init(common_ext_Extension $extension, $langCode)\n {\n \t// if the langCode is empty do nothing\n \tif (empty($langCode)){\n \t\tthrow new Exception(\"Language is not defined\");\n \t}\n \t\n\t\t//init the ClearFw l10n tools\n $translations = tao_models_classes_LanguageService::singleton()->getServerBundle($langCode);\n l10n::init($translations);\n\n $serviceManager = \\oat\\oatbox\\service\\ServiceManager::getServiceManager();\n $extraPoService = $serviceManager->get(\\oat\\tao\\model\\i18n\\ExtraPoService::SERVICE_ID);\n $extraPoCount = $extraPoService->requirePos();\n }" ]
codesearchnet
{ "query": "Represent the sentence about Software development:", "pos": "Represent the code about Software development:", "neg": "Represent the code about Software development:" }
// Provide returns the result of executing the constructor with argument values resolved from a dependency graph
[ "func (p provider) Provide(g Graph) reflect.Value {\n\tfnType := reflect.TypeOf(p.constructor)\n\n\targCount := fnType.NumIn()\n\tif fnType.IsVariadic() {\n\t\targCount = len(p.argPtrs)\n\t}\n\n\targs := make([]reflect.Value, argCount, argCount)\n\tvar inType reflect.Type\n\tfor i := 0; i < argCount; i++ {\n\t\targ := g.Resolve(p.argPtrs[i])\n\t\targType := arg.Type()\n\n\t\tif i < fnType.NumIn() {\n\t\t\tinType = fnType.In(i)\n\t\t} else {\n\t\t\tinType = fnType.In(fnType.NumIn() - 1)\n\t\t}\n\n\t\tif inType.Kind() == reflect.Slice {\n\t\t\tinType = inType.Elem()\n\t\t}\n\n\t\tif !argType.AssignableTo(inType) {\n\t\t\tif !argType.ConvertibleTo(inType) {\n\t\t\t\tpanic(fmt.Sprintf(\n\t\t\t\t\t\"arg %d of type %q cannot be assigned or converted to type %q for provider constructor (%s)\",\n\t\t\t\t\ti, argType, inType, p.constructor,\n\t\t\t\t))\n\t\t\t}\n\t\t\targ = arg.Convert(inType)\n\t\t}\n\t\targs[i] = arg\n\t}\n\n\treturn reflect.ValueOf(p.constructor).Call(args)[0]\n}" ]
[ "NameAndType nameType(Symbol sym) {\n return new NameAndType(sym.name, sym.externalType(types), types);\n // the NameAndType is generated from a symbol reference, and the\n // adjustment of adding an additional this$n parameter needs to be made.\n }" ]
codesearchnet
{ "query": "Represent the Github comment about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code about programming:" }
@param Request $request @param integer $id @return \Symfony\Component\HttpFoundation\JsonResponse @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException
[ "public function updateAction(Request $request, $id)\n {\n $this->checkCsrf();\n\n $transUnit = $this->get('lexik_translation.data_grid.request_handler')->updateFromRequest($id, $request);\n\n return $this->get('lexik_translation.data_grid.formatter')->createSingleResponse($transUnit);\n }" ]
[ "protected function redefineErrorHandlers(&$container)\n {\n // Redefine - errors\n $container['errorHandler'] = BuilderJsonErrorResponses::jsonError();\n $container['phpErrorHandler'] = BuilderJsonErrorResponses::jsonPhpError();\n $container['notFoundHandler'] = BuilderJsonErrorResponses::jsonNotFound();\n $container['notAllowedHandler'] = BuilderJsonErrorResponses::jsonNotAllowed();\n }" ]
codesearchnet
{ "query": "Represent the Github text about Symfony:", "pos": "Represent the Github code about Symfony:", "neg": "Represent the Github code about programming:" }
// Ensure the directory exists or create it if needed.
[ "func EnsureDir(dir string, mode os.FileMode) error {\n\tif fileOptions, err := os.Stat(dir); os.IsNotExist(err) {\n\t\tif errMake := os.MkdirAll(dir, mode); errMake != nil {\n\t\t\treturn fmt.Errorf(\"Could not create directory %s. %v\", dir, err)\n\t\t}\n\t} else if err != nil {\n\t\treturn fmt.Errorf(\"Error asserting directory %s: %v\", dir, err)\n\t} else if !fileOptions.IsDir() {\n\t\treturn fmt.Errorf(\"Path already exists as a file: %s\", dir)\n\t}\n\treturn nil\n}" ]
[ "def resolveEntryPoint(entryPoint):\n \n if inVirtualEnv():\n path = os.path.join(os.path.dirname(sys.executable), entryPoint)\n # Inside a virtualenv we try to use absolute paths to the entrypoints.\n if os.path.isfile(path):\n # If the entrypoint is present, Toil must have been installed into the virtualenv (as\n # opposed to being included via --system-site-packages). For clusters this means that\n # if Toil is installed in a virtualenv on the leader, it must be installed in\n # a virtualenv located at the same path on each worker as well.\n assert os.access(path, os.X_OK)\n return path\n else:\n # For virtualenv's that have the toil package directory on their sys.path but whose\n # bin directory lacks the Toil entrypoints, i.e. where Toil is included via\n # --system-site-packages, we rely on PATH just as if we weren't in a virtualenv.\n return entryPoint\n else:\n # Outside a virtualenv it is hard to predict where the entry points got installed. It is\n # the responsibility of the user to ensure that they are present on PATH and point to the\n # correct version of Toil. This is still better than an absolute path because it gives\n # the user control over Toil's location on both leader and workers.\n return entryPoint" ]
codesearchnet
{ "query": "Represent the Github summarization about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code about Software development:" }
Update the given MySQL User. @param array $data @return MysqlUser
[ "public function update(array $data)\n {\n return $this->forge->updateMysqlUser($this->serverId, $this->id, $data);\n }" ]
[ "final protected function c() {return dfc($this, function() {/** @var int|null $id $id */return\n\t\t!($id = $this->o()->getCustomerId()) ? null : df_customer($id)\n\t;});}" ]
codesearchnet
{ "query": "Represent the sentence about programming:", "pos": "Represent the code about programming:", "neg": "Represent the code about programming:" }
// SetActivityFailedEventDetails sets the ActivityFailedEventDetails field's value.
[ "func (s *HistoryEvent) SetActivityFailedEventDetails(v *ActivityFailedEventDetails) *HistoryEvent {\n\ts.ActivityFailedEventDetails = v\n\treturn s\n}" ]
[ "private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {\n GetField fields = in.readFields();\n beginDefaultContext = fields.get(BEGIN_DEFAULT, true);\n\n // Note that further processing is required in JEEMetadataContextProviderImpl.deserializeThreadContext\n // in order to re-establish the thread context based on the metadata identity if not defaulted.\n }" ]
codesearchnet
{ "query": "Represent the text about programming:", "pos": "Represent the code about programming:", "neg": "Represent the code about programming:" }
Flushes the data buffers to disk. @param force force a synchronous flush (otherwise if the environment has the MDB_NOSYNC flag set the flushes will be omitted, and with MDB_MAPASYNC they will be asynchronous)
[ "public void sync(final boolean force) {\n if (closed) {\n throw new AlreadyClosedException();\n }\n final int f = force ? 1 : 0;\n checkRc(LIB.mdb_env_sync(ptr, f));\n }" ]
[ "def connect(self, host, port):\n '''\n \n '''\n # Clear the connect state immediately since we're no longer connected\n # at this point.\n self._connected = False\n\n # Only after the socket has connected do we clear this state; closed\n # must be False so that writes can be buffered in writePacket(). The\n # closed state might have been set to True due to a socket error or a\n # redirect.\n self._host = \"%s:%d\" % (host, port)\n self._closed = False\n self._close_info = {\n 'reply_code': 0,\n 'reply_text': 'failed to connect to %s' % (self._host),\n 'class_id': 0,\n 'method_id': 0\n }\n\n self._transport.connect((host, port))\n self._transport.write(PROTOCOL_HEADER)\n\n self._last_octet_time = time.time()\n\n if self._synchronous_connect:\n # Have to queue this callback just after connect, it can't go\n # into the constructor because the channel needs to be\n # \"always there\" for frame processing, but the synchronous\n # callback can't be added until after the protocol header has\n # been written. This SHOULD be registered before the protocol\n # header is written, in the case where the header bytes are\n # written, but this thread/greenlet/context does not return until\n # after another thread/greenlet/context has read and processed the\n # recv_start frame. Without more re-write to add_sync_cb though,\n # it will block on reading responses that will never arrive\n # because the protocol header isn't written yet. TBD if needs\n # refactoring. Could encapsulate entirely here, wherein\n # read_frames exits if protocol header not yet written. Like other\n # synchronous behaviors, adding this callback will result in a\n # blocking frame read and process loop until _recv_start and any\n # subsequent synchronous callbacks have been processed. In the\n # event that this is /not/ a synchronous transport, but the\n # caller wants the connect to be synchronous so as to ensure that\n # the connection is ready, then do a read frame loop here.\n self._channels[0].add_synchronous_cb(self._channels[0]._recv_start)\n while not self._connected:\n self.read_frames()" ]
codesearchnet
{ "query": "Represent the Github sentence:", "pos": "Represent the Github code:", "neg": "Represent the Github code:" }
Handle the command. @var string
[ "public function handle()\n {\n $indexConfigurator = $this->getIndexConfigurator();\n\n if ($indexConfigurator && ! $this->alreadyExists($indexConfigurator)) {\n $this->call('make:index-configurator', [\n 'name' => $indexConfigurator,\n ]);\n }\n\n $searchRule = $this->getSearchRule();\n\n if ($searchRule && ! $this->alreadyExists($searchRule)) {\n $this->call('make:search-rule', [\n 'name' => $searchRule,\n ]);\n }\n\n parent::handle();\n }" ]
[ "def :\n \"\"\"\"\"\"\n CheckParent(self)\n\n return _fitz.Annot_" ]
codesearchnet
{ "query": "Represent the summarization:", "pos": "Represent the code:", "neg": "Represent the code:" }
Performs a search and returns the match, or null if no match was found or more than one match was found. @since 1.527
[ "public static SuggestedItem find(SearchIndex index, String query, SearchableModelObject searchContext) {\n List<SuggestedItem> r = find(Mode.FIND, index, query, searchContext);\n if(r.isEmpty()){ \n return null;\n }\n else if(1==r.size()){\n return r.get(0);\n }\n else {\n // we have more than one suggested item, so return the item who's url\n // contains the query as this is probably the job's name\n return findClosestSuggestedItem(r, query);\n }\n \n }" ]
[ "function Rule(rules) {\n this.rules = rules;\n // Identifies individual rule\n this.name = \"\";\n // Identifies the grammar that this rule belongs to \n this.grammarName = \"\";\n // Identifies types of rules. Rules can have \"types\" that are different than the class name\n this.type = \"\";\n // Used to provide access to the name of the class \n this.className = \"Rule\";\n // Indicates whether generated nodes should be added to the abstract syntax tree\n this._createAstNode = false;\n // A parser function, computed in a rule's constructor. If successful returns either the original or a new \n // ParseState object. If it fails it returns null.\n this.parser = null;\n // A lexer function, computed in a rule's constructor. The lexer may update the ParseState if successful.\n // If it fails it is required that the lexer restore the ParseState index to the previous state. \n // Lexers should only update the index. \n this.lexer = null;\n }" ]
codesearchnet
{ "query": "Represent the Github sentence about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code:" }
r""" Initialize the solution vector (self.petsc_x), which is a dense matrix (1D vector) and defines the rhs vector (self.petsc_b) from the existing data.
[ "def _initialize_b_x(self):\n \n \"\"\"\n # Get vector(s) compatible with the matrix,\n # i.e., with the same parallel layout.\n self.petsc_x, self.petsc_b = self.petsc_A.getVecs()\n\n # Set the solution vector to zeros.\n self.petsc_x.set(0)\n\n # Define the petsc rhs vector from the numpy one.\n # If the rhs is defined by blocks, use this:\n PETSc.Vec.setValuesBlocked(self.petsc_b, [sp.arange(self.m)], self.b)" ]
[ "def uinit(self, ushape):\n \"\"\"\"\"\"\n\n if self.opt['Y0'] is None:\n return np.zeros(ushape, dtype=self.dtype)\n else:\n # If initial Y is non-zero, initial U is chosen so that\n # the relevant dual optimality criterion (see (3.10) in\n # boyd-2010-distributed) is satisfied.\n return self.Y" ]
codesearchnet
{ "query": "Represent the comment about Mathematics:", "pos": "Represent the code about Mathematics:", "neg": "Represent the code about programming:" }
Handles the creating or updating of a stack in CloudFormation. Also makes sure that we don't try to create or update a stack while it is already updating or creating.
[ "def _launch_stack(self, stack, **kwargs):\n \n old_status = kwargs.get(\"status\")\n wait_time = 0 if old_status is PENDING else STACK_POLL_TIME\n if self.cancel.wait(wait_time):\n return INTERRUPTED\n\n if not should_submit(stack):\n return NotSubmittedStatus()\n\n provider = self.build_provider(stack)\n\n try:\n provider_stack = provider.get_stack(stack.fqn)\n except StackDoesNotExist:\n provider_stack = None\n\n if provider_stack and not should_update(stack):\n stack.set_outputs(\n self.provider.get_output_dict(provider_stack))\n return NotUpdatedStatus()\n\n recreate = False\n if provider_stack and old_status == SUBMITTED:\n logger.debug(\n \"Stack %s provider status: %s\",\n stack.fqn,\n provider.get_stack_status(provider_stack),\n )\n\n if provider.is_stack_rolling_back(provider_stack):\n if 'rolling back' in old_status.reason:\n return old_status\n\n logger.debug(\"Stack %s entered a roll back\", stack.fqn)\n if 'updating' in old_status.reason:\n reason = 'rolling back update'\n else:\n reason = 'rolling back new stack'\n\n return SubmittedStatus(reason)\n elif provider.is_stack_in_progress(provider_stack):\n logger.debug(\"Stack %s in progress.\", stack.fqn)\n return old_status\n elif provider.is_stack_destroyed(provider_stack):\n logger.debug(\"Stack %s finished deleting\", stack.fqn)\n recreate = True\n # Continue with creation afterwards\n # Failure must be checked *before* completion, as both will be true\n # when completing a rollback, and we don't want to consider it as\n # a successful update.\n elif provider.is_stack_failed(provider_stack):\n reason = old_status.reason\n if 'rolling' in reason:\n reason = reason.replace('rolling', 'rolled')\n status_reason = provider.get_rollback_status_reason(stack.fqn)\n logger.info(\n \"%s Stack Roll Back Reason: \" + status_reason, stack.fqn)\n return FailedStatus(reason)\n\n elif provider.is_stack_completed(provider_stack):\n stack.set_outputs(\n provider.get_output_dict(provider_stack))\n return CompleteStatus(old_status.reason)\n else:\n return old_status\n\n logger.debug(\"Resolving stack %s\", stack.fqn)\n stack.resolve(self.context, self.provider)\n\n logger.debug(\"Launching stack %s now.\", stack.fqn)\n template = self._template(stack.blueprint)\n stack_policy = self._stack_policy(stack)\n tags = build_stack_tags(stack)\n parameters = self.build_parameters(stack, provider_stack)\n force_change_set = stack.blueprint.requires_change_set\n\n if recreate:\n logger.debug(\"Re-creating stack: %s\", stack.fqn)\n provider.create_stack(stack.fqn, template, parameters,\n tags, stack_policy=stack_policy)\n return SubmittedStatus(\"re-creating stack\")\n elif not provider_stack:\n logger.debug(\"Creating new stack: %s\", stack.fqn)\n provider.create_stack(stack.fqn, template, parameters, tags,\n force_change_set,\n stack_policy=stack_policy)\n return SubmittedStatus(\"creating new stack\")\n\n try:\n wait = stack.in_progress_behavior == \"wait\"\n if wait and provider.is_stack_in_progress(provider_stack):\n return WAITING\n if provider.prepare_stack_for_update(provider_stack, tags):\n existing_params = provider_stack.get('Parameters', [])\n provider.update_stack(\n stack.fqn,\n template,\n existing_params,\n parameters,\n tags,\n force_interactive=stack.protected,\n force_change_set=force_change_set,\n stack_policy=stack_policy,\n )\n\n logger.debug(\"Updating existing stack: %s\", stack.fqn)\n return SubmittedStatus(\"updating existing stack\")\n else:\n return SubmittedStatus(\"destroying stack for re-creation\")\n except CancelExecution:\n stack.set_outputs(provider.get_output_dict(provider_stack))\n return SkippedStatus(reason=\"canceled execution\")\n except StackDidNotChange:\n stack.set_outputs(provider.get_output_dict(provider_stack))\n return DidNotChangeStatus()" ]
[ "func (r *controller) Update(ctx context.Context, t *api.Task) error {\n\t// TODO(stevvooe): While assignment of tasks is idempotent, we do allow\n\t// updates of metadata, such as labelling, as well as any other properties\n\t// that make sense.\n\treturn nil\n}" ]
codesearchnet
{ "query": "Represent the Github description:", "pos": "Represent the Github code:", "neg": "Represent the Github code about Software development:" }
Convert to EEML. Optional parameter describes the version of EEML to generate. Default (and currently only version implemented) is version 5.
[ "def to_eeml(version = nil)\n if version.nil? || version == 5\n # Check that we have some data items\n if size < 1\n raise EEML::NoData.new('EEML requires at least one data item')\n end\n # Create EEML\n eeml = Builder::XmlMarkup.new\n eeml.instruct!\n eeml_options = {:xmlns => \"http://www.eeml.org/xsd/005\",\n :'xmlns:xsi' => \"http://www.w3.org/2001/XMLSchema-instance\",\n :'xsi:schemaLocation' => \"http://www.eeml.org/xsd/005 http://www.eeml.org/xsd/005/005.xsd\"}\n eeml_options[:version] = version if version\n eeml.eeml(eeml_options) do\n env_options = {}\n env_options[:updated] = @updated_at.xmlschema if @updated_at\n env_options[:creator] = @creator if @creator\n env_options[:id] = @id if @id\n eeml.environment(env_options) do |env|\n env.title @title if @title\n env.feed @feed if @feed\n env.status @status.to_s if @status\n env.description @description if @description\n env.icon @icon if @icon\n env.website @website if @website\n env.email @email if @email\n if @location\n loc_options = {}\n loc_options[:domain] = @location.domain\n loc_options[:exposure] = @location.exposure if @location.exposure\n loc_options[:disposition] = @location.disposition if @location.disposition\n env.location(loc_options) do |loc|\n loc.name @location.name if @location.name\n loc.lat @location.lat if @location.lat\n loc.lon @location.lon if @location.lon\n loc.ele @location.ele if @location.ele\n end\n end\n @data_items.each_index do |i|\n env.data(:id => @data_items[i].id || i) do |data|\n @data_items[i].tags.each do |tag|\n data.tag tag\n end\n value_options = {}\n value_options[:maxValue] = @data_items[i].max_value if @data_items[i].max_value\n value_options[:minValue] = @data_items[i].min_value if @data_items[i].min_value\n data.value @data_items[i].value, value_options\n if @data_items[i].unit\n unit_options = {}\n unit_options[:symbol] = @data_items[i].unit.symbol if @data_items[i].unit.symbol\n unit_options[:type] = @data_items[i].unit.type if @data_items[i].unit.type\n data.unit @data_items[i].unit.name, unit_options\n end\n end\n end\n end\n end\n end\n end" ]
[ "public static String getDefaultMediaType(ResultType expectedType) {\n ResponseFormat format = (expectedType != null) ? defaultTypeFormats.get(expectedType) : null;\n \n // If the expected type is unknown, we should let the server decide, otherwise we could\n // wind up requesting a response type that doesn't match the actual resuts (e.g. xml with CONSTRUCT).\n // TODO: We could include multiple media types in the Accept: field, but that assumes that the\n // server has proper support for content negotiation. Many servers only look at the first value.\n return (format != null) ? format.mimeText : null;\n }" ]
codesearchnet
{ "query": "Represent the post:", "pos": "Represent the code:", "neg": "Represent the code about programming:" }
Returns the calculated age the time of event. @param int $age The age from the database record @return string
[ "private function calculateAge(int $age): string\n {\n if ((int) ($age / 365.25) > 0) {\n $result = (int) ($age / 365.25) . 'y';\n } elseif ((int) ($age / 30.4375) > 0) {\n $result = (int) ($age / 30.4375) . 'm';\n } else {\n $result = $age . 'd';\n }\n\n return FunctionsDate::getAgeAtEvent($result);\n }" ]
[ "def normalize(self, timestamp, steps=0):\n '''\n \n '''\n # So far, the only commonality with RelativeTime\n return self.from_bucket( self.to_bucket(timestamp, steps) )" ]
codesearchnet
{ "query": "Represent the Github comment about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code:" }
Option for the user to revert the changes made since it was last published
[ "public function revert() {\n\t\tif ($this->data()->IsModifiedOnStage) {\n\t\t\t$this->data()->doRevertToLive();\n\t\t}\n\t\treturn $this->redirect($this->data()->Link() . '?stage=Live');\n\t}" ]
[ "public static function get_contexts_for_userid(int $userid) : \\core_privacy\\local\\request\\contextlist {\n // We cannot associate files with a particular user as it would require to know all the details about\n // the source file, which only the component owning it knows about. And, the 'usermodified' attribute\n // of the conversion class is not an identifier of data ownership, merely that this user was logged in\n // when the conversion was requested. As such, as the owning component should declare the source file,\n // and we can't make sense of 'usermodified', we will not be reporting anything here. Also note that\n // the clean up task will ensure that whenever a source file is delete, its conversions also are.\n return new \\core_privacy\\local\\request\\contextlist();\n }" ]
codesearchnet
{ "query": "Represent the post:", "pos": "Represent the code:", "neg": "Represent the code about Software development:" }
// SetOperation sets the Operation field's value.
[ "func (s *DynamoDBAction) SetOperation(v string) *DynamoDBAction {\n\ts.Operation = &v\n\treturn s\n}" ]
[ "@Override\n public void addElement(Map<String, Object> e, Map<String, AggregatorFactory> a)\n {\n // since we return a constant, no need to read from the event\n }" ]
codesearchnet
{ "query": "Represent the Github sentence about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code:" }
Queue an "event" to be run on the GL rendering thread. @param r the runnable to be run on the GL rendering thread.
[ "public void queueEvent(Runnable r) {\n synchronized (this) {\n mEventQueue.add(r);\n synchronized (sGLThreadManager) {\n mEventsWaiting = true;\n sGLThreadManager.notifyAll();\n }\n }\n }" ]
[ "public final T execute(ComThread t) {\n if(Thread.currentThread()==t)\n // if invoked from within ComThread, execute it at once\n return call();\n else\n // otherwise schedule the execution and block\n return t.execute(this);\n }" ]
codesearchnet
{ "query": "Represent the Github comment:", "pos": "Represent the Github code:", "neg": "Represent the Github code about Software development:" }
path doesnt handle ~ resolution, fallback to env variables, solution taken from https://github.com/nodejs/node-v0.x-archive/issues/2857
[ "function tilda(cwd) {\n if (cwd.substring(0, 1) === '~') {\n cwd = (process.env.HOME || process.env.HOMEPATH || process.env.HOMEDIR || process.cwd()) + cwd.substr(1);\n }\n return path.resolve(cwd);\n}" ]
[ "function ParsePath(u) {\n //Parse the url\n let p = url.parse(u);\n //Get the path name\n let pname = p.pathname;\n //Check for Windows\n if( process.platform === \"win32\") {\n //Remove the first / from the path\n //https://github.com/jmjuanes/electron-ejs/pull/4#issuecomment-219254028\n pname = pname.substr(1);\n }\n //Sanitize URL. Spaces turn into `%20` symbols in the path and\n //throws a `File Not Found Event`. This fix allows folder paths to have\n //spaces in the folder name.\n //https://github.com/jmjuanes/electron-ejs/pull/9\n return pname.replace(/\\s/g, \" \").replace(/%20/g, \" \");\n}" ]
codesearchnet
{ "query": "Represent the comment:", "pos": "Represent the code:", "neg": "Represent the code about programming:" }
This method finds the first parent class which is within the buildbot namespace it prepends the name with as many ">" as the class is subclassed
[ "def getName(obj):\n \n # elastic search does not like '.' in dict keys, so we replace by /\n def sanitize(name):\n return name.replace(\".\", \"/\")\n if isinstance(obj, _BuildStepFactory):\n klass = obj.factory\n else:\n klass = type(obj)\n name = \"\"\n klasses = (klass, ) + inspect.getmro(klass)\n for klass in klasses:\n if hasattr(klass, \"__module__\") and klass.__module__.startswith(\"buildbot.\"):\n return sanitize(name + klass.__module__ + \".\" + klass.__name__)\n else:\n name += \">\"\n return sanitize(type(obj).__name__)" ]
[ "def register (g):\n \n assert isinstance(g, Generator)\n id = g.id()\n\n __generators [id] = g\n\n # A generator can produce several targets of the\n # same type. We want unique occurence of that generator\n # in .generators.$(t) in that case, otherwise, it will\n # be tried twice and we'll get false ambiguity.\n for t in sequence.unique(g.target_types()):\n __type_to_generators.setdefault(t, []).append(g)\n\n # Update the set of generators for toolset\n\n # TODO: should we check that generator with this id\n # is not already registered. For example, the fop.jam\n # module intentionally declared two generators with the\n # same id, so such check will break it.\n\n # Some generators have multiple periods in their name, so the\n # normal $(id:S=) won't generate the right toolset name.\n # e.g. if id = gcc.compile.c++, then\n # .generators-for-toolset.$(id:S=) will append to\n # .generators-for-toolset.gcc.compile, which is a separate\n # value from .generators-for-toolset.gcc. Correcting this\n # makes generator inheritance work properly.\n # See also inherit-generators in module toolset\n base = id.split ('.', 100) [0]\n\n __generators_for_toolset.setdefault(base, []).append(g)\n\n # After adding a new generator that can construct new target types, we need\n # to clear the related cached viable source target type information for\n # constructing a specific target type or using a specific generator. Cached\n # viable source target type lists affected by this are those containing any\n # of the target types constructed by the new generator or any of their base\n # target types.\n #\n # A more advanced alternative to clearing that cached viable source target\n # type information would be to expand it with additional source types or\n # even better - mark it as needing to be expanded on next use.\n #\n # For now we just clear all the cached viable source target type information\n # that does not simply state 'all types' and may implement a more detailed\n # algorithm later on if it becomes needed.\n\n invalidate_extendable_viable_source_target_type_cache()" ]
codesearchnet
{ "query": "Represent the description about Programming:", "pos": "Represent the code about Programming:", "neg": "Represent the code:" }
Returns "a mark" to the current position of this node Cassandra log. This is for use with the from_mark parameter of watch_log_for_* methods, allowing to watch the log from the position when this method was called.
[ "def mark_log(self, filename='system.log'):\n \n log_file = os.path.join(self.get_path(), 'logs', filename)\n if not os.path.exists(log_file):\n return 0\n with open(log_file) as f:\n f.seek(0, os.SEEK_END)\n return f.tell()" ]
[ "function onChunk(count) {\n // If chunk read has no bytes than there is nothing left, so end a\n // collection.\n if (count === 0) return next(end)\n\n // Move a offset `position` with `count` towards the end unless\n // position was a `null` in which case we just keep it (`null` means\n // from a current position).\n position = position === null ? position : position + count\n // Read chunk is forwarded to a consumer that will return\n // a promise which is delivered once write is complete.\n // In a future we may switch to an approach similar to new\n // streams in node, where buffering watermarks are specified\n // via options and reads can buffer up up to that point in\n // parallel to write.\n when(next(buffer.slice(0, count), state), onDrain, onError)\n }" ]
codesearchnet
{ "query": "Represent the text about Software development:", "pos": "Represent the code about Software development:", "neg": "Represent the code about File management:" }
A safe function for creating a directory tree.
[ "def safe_makedirs(path):\n \"\"\"\"\"\"\n try:\n os.makedirs(path)\n except OSError as err:\n if err.errno == errno.EEXIST:\n if not os.path.isdir(path):\n raise\n else:\n raise" ]
[ "public FunctionHandle resolveFunction(Session session, QualifiedName name, List<TypeSignatureProvider> parameterTypes)\n {\n // TODO Actually use session\n // Session will be used to provide information about the order of function namespaces to through resolving the function.\n // This is likely to be in terms of SQL path. Currently we still don't have support multiple function namespaces, nor\n // SQL path. As a result, session is not used here. We still add this to distinguish the two versions of resolveFunction\n // while the refactoring is on-going.\n return staticFunctionNamespace.resolveFunction(name, parameterTypes);\n }" ]
codesearchnet
{ "query": "Represent the Github summarization:", "pos": "Represent the Github code:", "neg": "Represent the Github code about Software development:" }
It's kind of redundant to have the server return the foreign keys corresponding to the belongs_to associations (since they'll be in the URL anyway), so we'll try to inject them based on the attributes of the object we just used.
[ "def load(attributes, remove_root=false)\n attributes = attributes ? attributes.stringify_keys : {}\n self.class.belongs_to_with_parents.each do |belongs_to_param|\n attributes[\"#{belongs_to_param}_id\"] ||= prefix_options[\"#{belongs_to_param}_id\".intern]\n\n # also set prefix attributes as real attributes. Otherwise,\n # belongs_to attributes will be stripped out of the response\n # even if we aren't actually using the association.\n @attributes[\"#{belongs_to_param}_id\"] = attributes[\"#{belongs_to_param}_id\"]\n end\n super(attributes, remove_root)\n end" ]
[ "def new_collection(query, resources = nil, &block)\n if loaded?\n resources ||= filter(query)\n end\n\n # TOOD: figure out a way to pass not-yet-saved Resources to this newly\n # created Collection. If the new resource matches the conditions, then\n # it should be added to the collection (keep in mind limit/offset too)\n\n self.class.new(query, resources, &block)\n end" ]
codesearchnet
{ "query": "Represent the Github post:", "pos": "Represent the Github code:", "neg": "Represent the Github code about Software development:" }
Count records of model. @param string $alias Optional alias of count result @return int
[ "public function count($alias = null)\n {\n if ($this->controller && $this->controller->hasMethod('count')) {\n return $this->controller->count($this, $alias);\n }\n throw $this->exception('The controller doesn\\'t support count', 'NotImplemented')\n ->addMoreInfo('controller', $this->controller ? $this->controller->short_name : 'none');\n }" ]
[ "def build(self):\n \"\"\"\"\"\"\n from ambry.orm.config import BuildConfigGroupAccessor\n\n # It is a lightweight object, so no need to cache\n return BuildConfigGroupAccessor(self.dataset, 'buildstate', self._session)" ]
codesearchnet
{ "query": "Represent the Github text about Software Development:", "pos": "Represent the Github code about Software Development:", "neg": "Represent the Github code:" }
Sets the StructTypeInfo that declares the total schema of the file in the configuration
[ "public static void setSchemaTypeInfo(Configuration conf, StructTypeInfo schemaTypeInfo) {\n if (schemaTypeInfo != null) {\n conf.set(SCHEMA_TYPE_INFO, schemaTypeInfo.getTypeName());\n LOG.debug(\"Set schema typeInfo on conf: {}\", schemaTypeInfo);\n }\n }" ]
[ "@Override\n public void addElement(Map<String, Object> e, Map<String, AggregatorFactory> a)\n {\n // since we return a constant, no need to read from the event\n }" ]
codesearchnet
{ "query": "Represent the description about Software Development:", "pos": "Represent the code about Software Development:", "neg": "Represent the code:" }
where 语法见 @see WhereRule @param array|string|callable|null $conditions @param string $_ @return \PhpBoot\DB\rules\select\WhereRule
[ "public function findWhere($conditions=null, $_=null)\n {\n $query = $this->db->select($this->getColumns())\n ->from($this->entity->getTable());\n $query->context->resultHandler = function ($result){\n foreach ($result as &$i){\n $i = $this->entity->make($i, false);\n }\n return $result;\n };\n return call_user_func_array([$query, 'where'], func_get_args());\n }" ]
[ "public function handleManipulateAST(ManipulateAST $ManipulateAST): void\n {\n $ManipulateAST->documentAST = ASTHelper::attachDirectiveToObjectTypeFields(\n $ManipulateAST->documentAST,\n PartialParser::directive('@deferrable')\n );\n\n $ManipulateAST->documentAST->setDefinition(\n PartialParser::directiveDefinition('directive @defer(if: Boolean) on FIELD')\n );\n }" ]
codesearchnet
{ "query": "Represent the comment about Software Development:", "pos": "Represent the code about Software Development:", "neg": "Represent the code about programming:" }
Source configuration file.
[ "def source_file(pymux, variables):\n \n filename = os.path.expanduser(variables['<filename>'])\n try:\n with open(filename, 'rb') as f:\n for line in f:\n line = line.decode('utf-8')\n handle_command(pymux, line)\n except IOError as e:\n raise CommandException('IOError: %s' % (e, ))" ]
[ "function writeTimeBound(type, prmname, boundType, outputType) {\n return utils.parts(type, {\n B : prmname,\n // TODO: is this correct?\n C : boundType+'_'+(type === 'QU' ? 'UBT' : 'LBT')+'(KAF)',\n E : '1MON'\n }, outputType);\n //A=HEXT2014 B=SR-CMN_SR-CMN C=STOR_UBT(KAF) E=1MON F=CAMANCHE R FLOOD CAP\n}" ]
codesearchnet
{ "query": "Represent the Github summarization:", "pos": "Represent the Github code:", "neg": "Represent the Github code:" }
Modifies the result of each promise from a scalar value to a object containing its fieldname
[ "function wrap(fieldName, promise, args) {\n return promise(args).then((result) => ({\n [fieldName]: result,\n }));\n}" ]
[ "function onChunk(count) {\n // If chunk read has no bytes than there is nothing left, so end a\n // collection.\n if (count === 0) return next(end)\n\n // Move a offset `position` with `count` towards the end unless\n // position was a `null` in which case we just keep it (`null` means\n // from a current position).\n position = position === null ? position : position + count\n // Read chunk is forwarded to a consumer that will return\n // a promise which is delivered once write is complete.\n // In a future we may switch to an approach similar to new\n // streams in node, where buffering watermarks are specified\n // via options and reads can buffer up up to that point in\n // parallel to write.\n when(next(buffer.slice(0, count), state), onDrain, onError)\n }" ]
codesearchnet
{ "query": "Represent the Github post:", "pos": "Represent the Github code:", "neg": "Represent the Github code about File management:" }
Send `post_dict` to the :attr:`.ALEPH_EXPORT_URL`. Args: post_dict (dict): dictionary from :class:`PostData.get_POST_data()` Returns: str: Reponse from webform.
[ "def _sendPostDict(post_dict):\n \n downer = Downloader()\n downer.headers[\"Referer\"] = settings.EDEPOSIT_EXPORT_REFERER\n data = downer.download(settings.ALEPH_EXPORT_URL, post=post_dict)\n rheaders = downer.response_headers\n\n error_msg = rheaders.get(\"aleph-info\", \"\").lower().strip()\n if \"aleph-info\" in rheaders and error_msg.startswith(\"error\"):\n raise ExportRejectedException(\n \"Export request was rejected by import webform: %s\" %\n rheaders[\"aleph-info\"]\n )\n\n return data" ]
[ "def get_driver_config(driver): # noqa: E501\n \n\n response = errorIfUnauthorized(role='admin')\n if response:\n return response\n else:\n response = ApitaxResponse()\n\n # TODO: This needs an implementation, but likely requires a change to configs in apitaxcore\n\n return Response(status=200, body=response.getResponseBody())" ]
codesearchnet
{ "query": "Represent the Github sentence about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code about Technical documentation:" }
// buildKubeletConfig is responsible for creating the kubelet configuration
[ "func (b *KubeletBuilder) buildKubeletConfig() (*kops.KubeletConfigSpec, error) {\n\tif b.InstanceGroup == nil {\n\t\tglog.Fatalf(\"InstanceGroup was not set\")\n\t}\n\n\tkubeletConfigSpec, err := b.buildKubeletConfigSpec()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"error building kubelet config: %v\", err)\n\t}\n\n\t// TODO: Memoize if we reuse this\n\treturn kubeletConfigSpec, nil\n}" ]
[ "func (c *agentConf) AddFlags(f *gnuflag.FlagSet) {\n\t// TODO(dimitern) 2014-02-19 bug 1282025\n\t// We need to pass a config location here instead and\n\t// use it to locate the conf and the infer the data-dir\n\t// from there instead of passing it like that.\n\tf.StringVar(&c.dataDir, \"data-dir\", util.DataDir, \"directory for juju data\")\n}" ]
codesearchnet
{ "query": "Represent the sentence about Software Development:", "pos": "Represent the code about Software Development:", "neg": "Represent the code about programming:" }
Verify credentials
[ "def login(self, request):\n \n try:\n user = authenticate(request)\n\n if not user:\n raise AuthenticationFailed(\"User not authenticated.\")\n\n if not user.is_active:\n raise AuthenticationFailed(\"This user has been disabled.\")\n\n login(request, user)\n\n return Response(UserSerializer(user).data)\n except AuthError as ex:\n # This indicates an error that may require attention by the\n # Treeherder or Taskcluster teams. Logging this to New Relic to\n # increase visibility.\n newrelic.agent.record_exception()\n logger.exception(\"Error\", exc_info=ex)\n raise AuthenticationFailed(str(ex))" ]
[ "def post_build(self, p, pay):\n \n p += pay\n if self.auxdlen != 0:\n print(\"NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).\")\n print(\" Subsequent Group Records are lost!\")\n return p" ]
codesearchnet
{ "query": "Represent the Github comment:", "pos": "Represent the Github code:", "neg": "Represent the Github code:" }
Removes a key by adding a remove entry to the row. The remove is represented as a delta entry so checkpoints can be written asynchronously. @return false if the new record cannot fit into the block.
[ "boolean remove(RowCursor cursor)\n {\n int rowHead = _rowHead;\n int blobTail = _blobTail;\n \n rowHead -= cursor.removeLength();\n\n if (rowHead < blobTail) {\n return false;\n }\n \n byte []buffer = _buffer;\n \n // buffer[rowHead] = REMOVE;\n \n cursor.getRemove(buffer, rowHead);\n // cursor.getKey(buffer, rowHead + ColumnState.LENGTH);\n \n rowHead(rowHead);\n \n validateBlock(cursor.row()); \n \n return true;\n }" ]
[ "boolean setReplica( H2ONode h2o ) {\n assert _key.home(); // Only the HOME node for a key tracks replicas\n assert h2o != H2O.SELF; // Do not track self as a replica\n if( !read_lock() ) return false; // Write-locked; no new replications. Read fails to read *this* value\n // Narrow non-race here. Here is a time window where the rwlock count went\n // up, but the replica list does not account for the new replica. However,\n // the rwlock cannot go down until an ACKACK is received, and the ACK\n // (hence ACKACK) doesn't go out until after this function returns.\n replicas()[h2o._unique_idx] = 1;\n // Both rwlock taken, and replica count is up now.\n return true;\n }" ]
codesearchnet
{ "query": "Represent the comment about Software development:", "pos": "Represent the code about Software development:", "neg": "Represent the code about programming:" }
Retrieve model for route model binding @param mixed $value @return \Illuminate\Database\Eloquent\Model|null
[ "public function resolveRouteBinding($value)\n {\n if (! (ctype_digit($value) || is_int($value))) {\n return null;\n }\n\n try {\n $value = App::make('fakeid')->decode((int) $value);\n } catch (Exception $e) {\n return null;\n }\n\n return $this->where($this->getRouteKeyName(), $value)->first();\n }" ]
[ "public function register()\n {\n $this->registerFileConfig();\n $this->registerDatabaseConfig();\n\n // Bind the concrete types\n $this->app->bind('Concrete\\Core\\Config\\Repository\\Repository', 'config');\n $this->app->bind('Illuminate\\Config\\Repository', 'Concrete\\Core\\Config\\Repository\\Repository');\n }" ]
codesearchnet
{ "query": "Represent the text:", "pos": "Represent the code:", "neg": "Represent the code:" }
// NewGrip takes the name for a logging instance and creates a new // Grip instance with configured with a local, standard output logging. // The default level is "Notice" and the threshold level is "info."
[ "func NewGrip(name string) *Grip {\n\tsender, _ := send.NewNativeLogger(name,\n\t\tsend.LevelInfo{\n\t\t\tThreshold: level.Trace,\n\t\t\tDefault: level.Trace,\n\t\t})\n\n\treturn &Grip{impl: sender}\n}" ]
[ "func (logger *Logger) Log(level Level, v ...interface{}) {\n\t// Don't delete this calling. The calling is used to keep the same\n\t// calldepth for all the logging functions. The calldepth is used to\n\t// get runtime information such as line number, function name, etc.\n\tlogger.log(level, v...)\n}" ]
codesearchnet
{ "query": "Represent the Github description about Software development:", "pos": "Represent the Github code about Software development:", "neg": "Represent the Github code about Computer Science:" }
Set the state of the BFD session.
[ "def _set_state(self, new_state, diag=None):\n \n old_state = self._session_state\n\n LOG.info(\"[BFD][%s][STATE] State changed from %s to %s.\",\n hex(self._local_discr),\n bfd.BFD_STATE_NAME[old_state],\n bfd.BFD_STATE_NAME[new_state])\n self._session_state = new_state\n\n if new_state == bfd.BFD_STATE_DOWN:\n if diag is not None:\n self._local_diag = diag\n self._desired_min_tx_interval = 1000000\n self._is_polling = True\n self._update_xmit_period()\n elif new_state == bfd.BFD_STATE_UP:\n self._desired_min_tx_interval = self._cfg_desired_min_tx_interval\n self._is_polling = True\n self._update_xmit_period()\n\n self.app.send_event_to_observers(\n EventBFDSessionStateChanged(self, old_state, new_state))" ]
[ "@Override\n public void init(TCPWriteRequestContext x, H2MuxTCPWriteCallback c) {\n writeReqContext = x;\n muxCallback = c;\n\n // callback will need to know how to get back to this write queue.\n // This means one and only one H2WriteTree per H2InboundLink which has just one true TCP Channel facing write callback\n muxCallback.setH2WorkQ(this);\n\n tree = new Tree();\n\n }" ]
codesearchnet
{ "query": "Represent the summarization:", "pos": "Represent the code:", "neg": "Represent the code:" }
/* TODO: Too general; this should be split into overloaded methods. Is that possible?
[ "XmlNode.QName toNodeQName(Context cx, Object nameValue, boolean attribute) {\n if (nameValue instanceof XMLName) {\n return ((XMLName)nameValue).toQname();\n } else if (nameValue instanceof QName) {\n QName qname = (QName)nameValue;\n return qname.getDelegate();\n } else if (\n nameValue instanceof Boolean\n || nameValue instanceof Number\n || nameValue == Undefined.instance\n || nameValue == null\n ) {\n throw badXMLName(nameValue);\n } else {\n String local = null;\n if (nameValue instanceof String) {\n local = (String)nameValue;\n } else {\n local = ScriptRuntime.toString(nameValue);\n }\n return toNodeQName(cx, local, attribute);\n }\n }" ]
[ "public FunctionHandle resolveFunction(Session session, QualifiedName name, List<TypeSignatureProvider> parameterTypes)\n {\n // TODO Actually use session\n // Session will be used to provide information about the order of function namespaces to through resolving the function.\n // This is likely to be in terms of SQL path. Currently we still don't have support multiple function namespaces, nor\n // SQL path. As a result, session is not used here. We still add this to distinguish the two versions of resolveFunction\n // while the refactoring is on-going.\n return staticFunctionNamespace.resolveFunction(name, parameterTypes);\n }" ]
codesearchnet
{ "query": "Represent the comment about programming:", "pos": "Represent the code about programming:", "neg": "Represent the code about Software development:" }
Check whether order is cancelled. $param boolean $strict @return boolean
[ "public function isCancelled( $strict = true ) {\n\n\t\tif( $strict ) {\n\n\t\t\treturn $this->status == self::STATUS_CANCELLED;\n\t\t}\n\n\t\treturn $this->status >= self::STATUS_CANCELLED;\n\t}" ]
[ "final protected function c() {return dfc($this, function() {/** @var int|null $id $id */return\n\t\t!($id = $this->o()->getCustomerId()) ? null : df_customer($id)\n\t;});}" ]
codesearchnet
{ "query": "Represent the text about programming:", "pos": "Represent the code about programming:", "neg": "Represent the code about programming:" }
Internally called to reallocate the indexes. This method should be called when the filtered model changes its element size
[ "protected void reallocateIndexes() {\n if (this.indexes == null || this.indexes.length != getFilteredModel().getSize()) {\n this.indexes = new int[getFilteredModel().getSize()];\n }\n applyConstraint();\n }" ]
[ "@Override\n public void addElement(Map<String, Object> e, Map<String, AggregatorFactory> a)\n {\n // since we return a constant, no need to read from the event\n }" ]
codesearchnet
{ "query": "Represent the instruction:", "pos": "Represent the code:", "neg": "Represent the code:" }
Convenience method, calls {@link #view(String, Object)} internally. The keys in the map are converted to String values. @param values map with values to pass to view.
[ "protected void view(Map<String, Object> values){\n for(String key:values.keySet() ){\n view(key, values.get(key));\n }\n }" ]
[ "@SuppressWarnings(\"unchecked\")\n public <T> Param<T> get(int index) {\n // TODO: Provide a more type safe API. E.g. make index a pojo typed on T which is aligned with the Param<T>\n return (Param<T>) params[index];\n }" ]
codesearchnet
{ "query": "Represent the post about programming:", "pos": "Represent the code about programming:", "neg": "Represent the code about Software development:" }
handle commands from user
[ "def process_stdin(line):\n ''''''\n if line is None:\n sys.exit(0)\n\n line = line.strip()\n if not line:\n return\n\n args = shlex.split(line)\n cmd = args[0]\n if cmd == 'help':\n k = command_map.keys()\n k.sort()\n for cmd in k:\n (fn, help) = command_map[cmd]\n print(\"%-15s : %s\" % (cmd, help))\n return\n if cmd == 'exit':\n mestate.exit = True\n return\n\n if not cmd in command_map:\n print(\"Unknown command '%s'\" % line)\n return\n (fn, help) = command_map[cmd]\n try:\n fn(args[1:])\n except Exception as e:\n print(\"ERROR in command %s: %s\" % (args[1:], str(e)))" ]
[ "def start(self, timeout=None):\n \n\n started = super(Node, self).start(timeout=timeout)\n if started:\n # TODO : return something produced in the context manager passed\n return self._svc_address # returning the zmp url as a way to connect to the node\n # CAREFUL : doesnt make sense if this node only run a one-time task...\n # TODO: futures and ThreadPoolExecutor (so we dont need to manage the pool ourselves)\n else:\n return False" ]
codesearchnet
{ "query": "Represent the Github description:", "pos": "Represent the Github code:", "neg": "Represent the Github code about programming:" }
List all active quotes on an account
[ "def cli(env):\n \"\"\"\"\"\"\n table = formatting.Table([\n 'Id', 'Name', 'Created', 'Expiration', 'Status', 'Package Name', 'Package Id'\n ])\n table.align['Name'] = 'l'\n table.align['Package Name'] = 'r'\n table.align['Package Id'] = 'l'\n\n manager = ordering.OrderingManager(env.client)\n items = manager.get_quotes()\n\n for item in items:\n package = item['order']['items'][0]['package']\n table.add_row([\n item.get('id'),\n item.get('name'),\n clean_time(item.get('createDate')),\n clean_time(item.get('modifyDate')),\n item.get('status'),\n package.get('keyName'),\n package.get('id')\n ])\n env.fout(table)" ]
[ "def post_build(self, p, pay):\n \n p += pay\n if self.auxdlen != 0:\n print(\"NOTICE: A properly formatted and complaint V3 Group Record should have an Auxiliary Data length of zero (0).\")\n print(\" Subsequent Group Records are lost!\")\n return p" ]
codesearchnet
{ "query": "Represent the text:", "pos": "Represent the code:", "neg": "Represent the code:" }
/* Check if reduced-form input >= 2^255-19
[ "private static final boolean is_overflow(long10 x) {\n\t\treturn (\n\t\t\t((x._0 > P26-19)) &&\n\t\t\t((x._1 & x._3 & x._5 & x._7 & x._9) == P25) &&\n\t\t\t((x._2 & x._4 & x._6 & x._8) == P26)\n\t\t\t) || (x._9 > P25);\n\t}" ]
[ "def rs_calc_syndromes(msg, nsym, fcr=0, generator=2):\n '''\n '''\n # Note the \"[0] +\" : we add a 0 coefficient for the lowest degree (the constant). This effectively shifts the syndrome, and will shift every computations depending on the syndromes (such as the errors locator polynomial, errors evaluator polynomial, etc. but not the errors positions).\n # This is not necessary as anyway syndromes are defined such as there are only non-zero coefficients (the only 0 is the shift of the constant here) and subsequent computations will/must account for the shift by skipping the first iteration (eg, the often seen range(1, n-k+1)), but you can also avoid prepending the 0 coeff and adapt every subsequent computations to start from 0 instead of 1.\n return [0] + [gf_poly_eval(msg, gf_pow(generator, i+fcr)) for i in xrange(nsym)]" ]
codesearchnet
{ "query": "Represent the comment about Natural Language Processing:", "pos": "Represent the code about Natural Language Processing:", "neg": "Represent the code about Natural Language Processing:" }
put @param key @param value @return V
[ "public V put(K key, V value) {\n if (isHighPrioEnabled) {\n return highPrioMap.put(key, value);\n } else {\n return lowPrioMap.put(key, value);\n }\n }" ]
[ "def :\n \"\"\"\"\"\"\n CheckParent(self)\n\n return _fitz.Annot_" ]
codesearchnet
{ "query": "Represent the Github text about Programming:", "pos": "Represent the Github code about Programming:", "neg": "Represent the Github code:" }
////////////////////////////////////////////////// Converts a single value into its Postgres format.
[ "function formatValue(value, fm, cc) {\n\n if (typeof value === 'function') {\n return formatValue(resolveFunc(value, cc), fm, cc);\n }\n\n const ctf = getCTF(value); // Custom Type Formatting\n if (ctf) {\n fm |= ctf.rawType ? fmFlags.raw : 0;\n return formatValue(resolveFunc(ctf.toPostgres, value), fm, cc);\n }\n\n const isRaw = !!(fm & fmFlags.raw);\n fm &= ~fmFlags.raw;\n\n switch (fm) {\n case fmFlags.alias:\n return $as.alias(value);\n case fmFlags.name:\n return $as.name(value);\n case fmFlags.json:\n return $as.json(value, isRaw);\n case fmFlags.csv:\n return $as.csv(value);\n case fmFlags.value:\n return $as.value(value);\n default:\n break;\n }\n\n if (isNull(value)) {\n throwIfRaw(isRaw);\n return 'null';\n }\n\n switch (typeof value) {\n case 'string':\n return $to.text(value, isRaw);\n case 'boolean':\n return $to.bool(value);\n case 'number':\n return $to.number(value);\n case 'symbol':\n throw new TypeError('Type Symbol has no meaning for PostgreSQL: ' + value.toString());\n default:\n if (value instanceof Date) {\n return $to.date(value, isRaw);\n }\n if (value instanceof Array) {\n return $to.array(value);\n }\n if (value instanceof Buffer) {\n return $to.buffer(value, isRaw);\n }\n return $to.json(value, isRaw);\n }\n}" ]
[ "public String filePath(int index, String savePath) {\n // not calling the corresponding swig function because internally,\n // the use of the function GetStringUTFChars does not consider the case of\n // a copy not made\n return savePath + File.separator + fs.file_path(index);\n }" ]
codesearchnet
{ "query": "Represent the Github description about Database Management:", "pos": "Represent the Github code about Database Management:", "neg": "Represent the Github code about programming:" }
Парсит элемент и извлекает из него аргументы @param DOMElement $element @return void
[ "protected function parseArgs(DOMElement $element)\n {\n $args = XmlUtil::getChildElements($element, 'arg');\n foreach ($args as $arg) {\n $name = XmlUtil::getRequiredAttributeValue($arg, 'name');\n $this->args[$name] = XmlUtil::getText($arg);\n }\n }" ]
[ "final protected function v($name = null) {return dfak($this, function() {\n\t\t$result = dfa($this->_data, 'value', []);\n\t\t/**\n\t\t * 2016-06-29\n\t\t * Что интересно, при смене области действия настроек с глобальной на другую (сайт или магазин)\n\t\t * поле «value» может почему-то содержать не массив,\n\t\t * а строку JSON, соответствующую запакованному в JSON массиву:\n\t\t * https://code.dmitry-fedyuk.com/m2e/currency-format/issues/1\n\t\t * Заметил это только для модуля «Price Format».\n\t\t */\n\t\treturn is_array($result) ? $result : df_json_decode($result);\n\t}, $name);}" ]
codesearchnet
{ "query": "Represent the Github sentence about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code about programming:" }
Returns a line formatted as comment. @param string $text @param array $style @return string
[ "public function error(string $text, array $style = []): string\n {\n return $this->line($text, ['fg' => static::RED] + $style);\n }" ]
[ "protected static function parsePrintableString(&$data, &$result)\n {\n // Printable string type\n $data = self::parseCommon($data, $stringData);\n $result[] = [\n 'Printable String (' . self::$len . ')',\n $stringData, ];\n }" ]
codesearchnet
{ "query": "Represent the Github comment about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code about Programming:" }
Returns the current paths unique ID. @return string|null
[ "public function getId()\n {\n if ($output = $this->execute('fsutil file queryfileid', $this->path)) {\n if ((bool) preg_match('/(\\d{1}[x].*)/', $output[0], $matches)) {\n return $matches[0];\n }\n }\n }" ]
[ "def getKeySequenceCounter(self):\n \"\"\"\"\"\"\n print '%s call getKeySequenceCounter' % self.port\n keySequence = ''\n keySequence = self.__sendCommand(WPANCTL_CMD + 'getprop -v Network:KeyIndex')[0]\n return keySequence" ]
codesearchnet
{ "query": "Represent the Github text about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code:" }
Register a new model (models)
[ "def post(self):\n \"\"\"\"\"\"\n self.set_header(\"Content-Type\", \"application/json\")\n key = uuid.uuid4().hex\n metadata = json.loads(self.request.body.decode())\n metadata[\"uuid\"] = key\n self.database[key] = metadata\n result = json.dumps({\"uuid\": key})\n self.write(result)" ]
[ "def create(self, **kwargs):\n \n raise exceptions.MethodNotImplemented(method=self.create, url=self.url, details='GUID cannot be duplicated, to create a new GUID use the relationship resource')" ]
codesearchnet
{ "query": "Represent the description about Natural Language Processing:", "pos": "Represent the code about Natural Language Processing:", "neg": "Represent the code about Natural Language Processing:" }
// SetName sets the Name field's value.
[ "func (s *CreateRemoteAccessSessionInput) SetName(v string) *CreateRemoteAccessSessionInput {\n\ts.Name = &v\n\treturn s\n}" ]
[ "function Rule(rules) {\n this.rules = rules;\n // Identifies individual rule\n this.name = \"\";\n // Identifies the grammar that this rule belongs to \n this.grammarName = \"\";\n // Identifies types of rules. Rules can have \"types\" that are different than the class name\n this.type = \"\";\n // Used to provide access to the name of the class \n this.className = \"Rule\";\n // Indicates whether generated nodes should be added to the abstract syntax tree\n this._createAstNode = false;\n // A parser function, computed in a rule's constructor. If successful returns either the original or a new \n // ParseState object. If it fails it returns null.\n this.parser = null;\n // A lexer function, computed in a rule's constructor. The lexer may update the ParseState if successful.\n // If it fails it is required that the lexer restore the ParseState index to the previous state. \n // Lexers should only update the index. \n this.lexer = null;\n }" ]
codesearchnet
{ "query": "Represent the Github sentence about programming:", "pos": "Represent the Github code about programming:", "neg": "Represent the Github code:" }
// Metadata returns meta data about the overlay driver such as // LowerDir, UpperDir, WorkDir and MergeDir used to store data.
[ "func (d *Driver) Metadata(id string) (map[string]string, error) {\n\tdir := d.dir(id)\n\tif _, err := os.Stat(dir); err != nil {\n\t\treturn nil, err\n\t}\n\n\tmetadata := map[string]string{\n\t\t\"WorkDir\": path.Join(dir, \"work\"),\n\t\t\"MergedDir\": path.Join(dir, \"merged\"),\n\t\t\"UpperDir\": path.Join(dir, \"diff\"),\n\t}\n\n\tlowerDirs, err := d.getLowerDirs(id)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(lowerDirs) > 0 {\n\t\tmetadata[\"LowerDir\"] = strings.Join(lowerDirs, \":\")\n\t}\n\n\treturn metadata, nil\n}" ]
[ "@Override\n public void addElement(Map<String, Object> e, Map<String, AggregatorFactory> a)\n {\n // since we return a constant, no need to read from the event\n }" ]
codesearchnet
{ "query": "Represent the Github summarization about File management:", "pos": "Represent the Github code about File management:", "neg": "Represent the Github code:" }
@param WKBBuffer $buffer @param int $srid @return Geometry @throws GeometryIOException
[ "protected function readGeometry(WKBBuffer $buffer, int $srid) : Geometry\n {\n $buffer->readByteOrder();\n\n $this->readGeometryHeader($buffer, $geometryType, $hasZ, $hasM, $srid);\n\n $cs = new CoordinateSystem($hasZ, $hasM, $srid);\n\n switch ($geometryType) {\n case Geometry::POINT:\n return $this->readPoint($buffer, $cs);\n\n case Geometry::LINESTRING:\n return $this->readLineString($buffer, $cs);\n\n case Geometry::CIRCULARSTRING:\n return $this->readCircularString($buffer, $cs);\n\n case Geometry::COMPOUNDCURVE:\n return $this->readCompoundCurve($buffer, $cs);\n\n case Geometry::POLYGON:\n return $this->readPolygon($buffer, $cs);\n\n case Geometry::CURVEPOLYGON:\n return $this->readCurvePolygon($buffer, $cs);\n\n case Geometry::MULTIPOINT:\n return $this->readMultiPoint($buffer, $cs);\n\n case Geometry::MULTILINESTRING:\n return $this->readMultiLineString($buffer, $cs);\n\n case Geometry::MULTIPOLYGON:\n return $this->readMultiPolygon($buffer, $cs);\n\n case Geometry::GEOMETRYCOLLECTION:\n return $this->readGeometryCollection($buffer, $cs);\n\n case Geometry::POLYHEDRALSURFACE:\n return $this->readPolyhedralSurface($buffer, $cs);\n\n case Geometry::TIN:\n return $this->readTIN($buffer, $cs);\n\n case Geometry::TRIANGLE:\n return $this->readTriangle($buffer, $cs);\n }\n\n throw GeometryIOException::unsupportedWKBType($geometryType);\n }" ]
[ "protected function processDetails(Buffer &$buffer, Result &$result)\n {\n parent::processDetails($buffer, $result);\n\n // Add in map\n $result->add('mapname', 'Panau');\n $result->add('dedicated', 'true');\n }" ]
codesearchnet
{ "query": "Represent the description about Software development:", "pos": "Represent the code about Software development:", "neg": "Represent the code about Software development:" }