query
stringlengths 16
255
| pos
list | neg
list | task
stringclasses 1
value | instruction
dict |
|---|---|---|---|---|
Returns the next $fact value or FALSE if there are no more facts.
{@inheritDoc}
@see Iterator::next()
|
[
"public function next()\r\n\t{\r\n\t\tif ( is_null( $this->facts ) )\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\t$this->yieldedFact = null;\r\n\r\n\t\t$success = $this->facts->next();\r\n\r\n\t\treturn $success;\r\n\t}"
] |
[
"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 post about programming:",
"pos": "Represent the code about programming:",
"neg": "Represent the code:"
}
|
Compare the structures of two databases.
Analysis's and compares the column definitions of each table
in both databases's. Identifies differences in column names,
data types and keys.
|
[
"def compare_schemas(self, db_x, db_y, show=True):\n \n # TODO: Improve method\n self._printer(\"\\tComparing database schema's {0} and {1}\".format(db_x, db_y))\n\n # Run compare_dbs_getter to get row counts\n x = self._schema_getter(db_x)\n y = self._schema_getter(db_y)\n x_count = len(x)\n y_count = len(y)\n\n # Check that database does not have zero tables\n if x_count == 0:\n self._printer('\\tThe database {0} has no tables'.format(db_x))\n self._printer('\\tDatabase differencing was not run')\n return None\n elif y_count == 0:\n self._printer('\\tThe database {0} has no tables'.format(db_y))\n self._printer('\\tDatabase differencing was not run')\n return None\n\n # Print comparisons\n if show:\n uniques_x = diff(x, y, x_only=True)\n if len(uniques_x) > 0:\n self._printer('\\nUnique keys from {0} ({1} of {2}):'.format(db_x, len(uniques_x), x_count))\n self._printer('------------------------------')\n # print(uniques)\n for k, v in sorted(uniques_x):\n self._printer('{0:25} {1}'.format(k, v))\n self._printer('\\n')\n\n uniques_y = diff(x, y, y_only=True)\n if len(uniques_y) > 0:\n self._printer('Unique keys from {0} ({1} of {2}):'.format(db_y, len(uniques_y), y_count))\n self._printer('------------------------------')\n for k, v in sorted(uniques_y):\n self._printer('{0:25} {1}'.format(k, v))\n self._printer('\\n')\n\n if len(uniques_y) == 0 and len(uniques_y) == 0:\n self._printer(\"Databases's {0} and {1} are identical:\".format(db_x, db_y))\n self._printer('------------------------------')\n\n return diff(x, y)"
] |
[
"def reset ():\n \n global __prefixes_suffixes, __suffixes_to_types, __types, __rule_names_to_types, __target_suffixes_cache\n\n __register_features ()\n\n # Stores suffixes for generated targets.\n __prefixes_suffixes = [property.PropertyMap(), property.PropertyMap()]\n\n # Maps suffixes to types\n __suffixes_to_types = {}\n\n # A map with all the registered types, indexed by the type name\n # Each entry is a dictionary with following values:\n # 'base': the name of base type or None if type has no base\n # 'derived': a list of names of type which derive from this one\n # 'scanner': the scanner class registered for this type, if any\n __types = {}\n\n # Caches suffixes for targets with certain properties.\n __target_suffixes_cache = {}"
] |
codesearchnet
|
{
"query": "Represent the Github post:",
"pos": "Represent the Github code:",
"neg": "Represent the Github code:"
}
|
Display a listing of the resource.
@param $type
@param Request $request
@return Response
|
[
"public function index($type, Request $request)\n {\n try {\n $resultColumns = [];\n $query = $request->get('q');\n $column = $request->get('c');\n\n $model = app()->make(config('mentions.' . $type));\n\n $records = $model->where($column, 'LIKE', \"%$query%\")\n ->get([$column]);\n\n foreach ($records as $record) {\n $resultColumns[] = $record->$column;\n }\n\n return response()->json($resultColumns);\n } catch (\\ReflectionException $e) {\n return response()->json('Not Found', 404);\n }\n }"
] |
[
"public function LinkingMode()\n {\n /** @var Page_Controller $controller */\n $controller = Controller::curr();\n $params = $controller->getURLParams();\n\n return $params['ID'] === $this->URLSegment ? 'current' : 'link';\n }"
] |
codesearchnet
|
{
"query": "Represent the Github comment about Programming:",
"pos": "Represent the Github code about Programming:",
"neg": "Represent the Github code about text processing:"
}
|
// NewRocR100ForStreamWithSrcLen creates a Rate of Change Ratio 100 Scale Indicator (RocR100) for offline usage with a source data stream
|
[
"func NewRocR100ForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *RocR100, err error) {\n\tind, err := NewRocR100WithSrcLen(sourceLength, timePeriod, selectData)\n\tpriceStream.AddTickSubscription(ind)\n\treturn ind, err\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 text about Signal Processing:",
"pos": "Represent the code about Signal Processing:",
"neg": "Represent the code:"
}
|
/* ------------------------------------------------------------
|
[
"public void reset()\n {\n try{\n out=IO.getNullWriter();\n super.flush();\n out=new OutputStreamWriter(os,encoding);\n written=false;\n }\n catch(UnsupportedEncodingException e)\n {\n log.fatal(e); System.exit(1);\n }\n }"
] |
[
"public function description()\n {\n //====================================================================//\n // Stack Trace\n Splash::log()->trace();\n\n //====================================================================//\n // Build & Return Widget Description Array\n return array(\n //====================================================================//\n // General Object definition\n \"type\" => $this->getType(), // Widget Type Name\n \"name\" => $this->getName(), // Widget Display Neme\n \"description\" => $this->getDesc(), // Widget Descritioon\n \"icon\" => $this->getIcon(), // Widget Icon\n \"disabled\" => $this->getIsDisabled(), // Is This Widget Enabled or Not?\n //====================================================================//\n // Widget Default Options\n \"options\" => $this->getOptions(), // Widget Default Options Array\n //====================================================================//\n // Widget Parameters\n \"parameters\" => $this->getParameters(), // Widget Default Options Array\n );\n }"
] |
codesearchnet
|
{
"query": "Represent the Github instruction about N/A:",
"pos": "Represent the Github code about N/A:",
"neg": "Represent the Github code about Software Development:"
}
|
When an error status the payload is holding an AsyncException that
is converted to a serializable dict.
|
[
"def _payload_to_dict(self):\n \n if self.status != self.ERROR or not self.payload:\n return self.payload\n\n import traceback\n\n return {\n \"error\": self.payload.error,\n \"args\": self.payload.args,\n \"traceback\": traceback.format_exception(*self.payload.traceback)\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 text about programming:",
"pos": "Represent the code about programming:",
"neg": "Represent the code about programming:"
}
|
// IsEmptyConfig returns true if the provided error indicates the provided configuration
// is empty.
|
[
"func IsEmptyConfig(err error) bool {\n\tswitch t := err.(type) {\n\tcase errConfigurationInvalid:\n\t\treturn len(t) == 1 && t[0] == ErrEmptyConfig\n\t}\n\treturn err == ErrEmptyConfig\n}"
] |
[
"function (err, collection) {\n if (err) {\n return callback(err);\n }\n\n // ensure that the collection option is present before starting a run\n if (!_.isObject(collection)) {\n return callback(new Error(COLLECTION_LOAD_ERROR_MESSAGE));\n }\n\n // ensure that the collection reference is an SDK instance\n // @todo - should this be handled by config loaders?\n collection = new Collection(Collection.isCollection(collection) ?\n // if the option contain an instance of collection, we simply clone it for future use\n // create a collection in case it is not one. user can send v2 JSON as a source and that will be\n // converted to a collection\n collection.toJSON() : collection);\n\n callback(null, collection);\n }"
] |
codesearchnet
|
{
"query": "Represent the Github comment about Software development:",
"pos": "Represent the Github code about Software development:",
"neg": "Represent the Github code about Software development:"
}
|
Generate file name.
@return the string
|
[
"public static String generatePreviousPreviousFileName() {\n\t\tStringBuffer name = new StringBuffer();\n\t\tname.append(\"Audit_Log-\").append(AuditUtil.dateToString(new Date(), \"yyyy-MM-dd\"))\n\t\t\t\t.append(CoreConstants.AUDIT_EXTENTION);\n\t\treturn name.toString();\n\t}"
] |
[
"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 sentence about programming:",
"pos": "Represent the Github code about programming:",
"neg": "Represent the Github code:"
}
|
// SetDeploymentStatusMessages sets the DeploymentStatusMessages field's value.
|
[
"func (s *DeploymentInfo) SetDeploymentStatusMessages(v []*string) *DeploymentInfo {\n\ts.DeploymentStatusMessages = 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:"
}
|
Load dependencies on demand.
@see \SimpleComplex\Config\EnvSectionedConfig
@return void
|
[
"protected function loadDependencies() /*: void*/\n {\n if (!$this->validate) {\n $this->validate = Validate::getInstance();\n\n if (!$this->config) {\n // Use enviroment variable wrapper config class if exists;\n // fall back on empty sectioned map.\n try {\n if (class_exists('\\\\SimpleComplex\\\\Config\\\\EnvSectionedConfig')) {\n $this->config = call_user_func('\\\\SimpleComplex\\\\Config\\\\EnvSectionedConfig::getInstance');\n } else {\n $this->config = new SectionedMap();\n }\n } catch (\\Throwable $ignore) {\n $this->config = new SectionedMap();\n }\n }\n if (!$this->unicode) {\n $this->unicode = Unicode::getInstance();\n }\n if (!$this->sanitize) {\n $this->sanitize = Sanitize::getInstance();\n }\n }\n }"
] |
[
"final public static function sinfo(array $params):string\n {\n return (\\iumioFramework\\Core\\Base\\Server\\GlobalServer::getServerInfo($params['name']));\n }"
] |
codesearchnet
|
{
"query": "Represent the comment about Software development:",
"pos": "Represent the code about Software development:",
"neg": "Represent the code about programming:"
}
|
Encode an arbitrary value
|
[
"private void encodeObject(StringBuffer result, Object value) {\n if (value != null) {\n if (value instanceof byte[]) {\n result.append(\"[]\");\n HexString.binToHex((byte[])value, 0, ((byte[])value).length, result);\n } else\n URLEncode(result, value.toString());\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 Github comment:",
"pos": "Represent the Github code:",
"neg": "Represent the Github code:"
}
|
Create a new UnboundNode representing a given class.
|
[
"def _createunbound(kls, **info):\n \"\"\"\"\"\"\n \n if issubclass(kls, Bitfield):\n nodetype = UnboundBitfieldNode\n elif hasattr(kls, '_fields_'):\n nodetype = UnboundStructureNode\n elif issubclass(kls, ctypes.Array):\n nodetype = UnboundArrayNode\n else:\n nodetype = UnboundSimpleNode \n return nodetype(type=kls, **info)"
] |
[
"@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 summarization:",
"pos": "Represent the code:",
"neg": "Represent the code:"
}
|
/*
Get singleton instance
@return Some\Class Object singleton instance
|
[
"public static function getInstance ()\n {\n // If this class is used for multiple singletons, we need to keep\n // track of multiple singleton objects, one for each class name\n static $instances = array();\n\n // Get class name to use. Use late static binding here,\n // if method is overriden by derived classes.\n $singletonClassName = static::_getInstanceClassName();\n\n // If already instantiated, use that\n if (isset($instances[$singletonClassName])) {\n return $instances[$singletonClassName];\n }\n\n // Otherwise create new instance\n $instances[$singletonClassName] = new $singletonClassName (static::_getInstanceFuseValue());\n\n return $instances[$singletonClassName];\n }"
] |
[
"protected Expression instantiate(Object oldInstance, Encoder out)\n {\n //\n // An implementation instance is actually constructed at decode time by calling\n // ControlBean.ensureControl on the parent bean. This will create a new impl\n // instance and run the impl initializer on it.\n //\n return new Expression(((XMLEncoder)out).getOwner(), \"ensureControl\", null);\n }"
] |
codesearchnet
|
{
"query": "Represent the Github comment about programming:",
"pos": "Represent the Github code about programming:",
"neg": "Represent the Github code:"
}
|
Compile an expression and return the corresponding executable
@param string $expression
@return \FormulaInterpreter\Executable
|
[
"function compile($expression) {\n $options = $this->parser->parse($expression);\n $command = $this->commandFactory->create($options);\n return new Executable($command, $this->variables);\n }"
] |
[
"def :\n \"\"\"\"\"\"\n CheckParent(self)\n\n return _fitz.Annot_"
] |
codesearchnet
|
{
"query": "Represent the Github text about Software Development:",
"pos": "Represent the Github code about Software Development:",
"neg": "Represent the Github code:"
}
|
Outputs the current progress string.
|
[
"public function display(): void\n {\n if (null === $this->format) {\n $this->format = self::DEFAULT_FORMAT;\n }\n\n $this->render($this->buildLine());\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 Github comment about programming:",
"pos": "Represent the Github code about programming:",
"neg": "Represent the Github code:"
}
|
Add field rules from either a Jpf.ValidationField or a Jpf.ValidationLocaleRules annotation.
|
[
"private void addFieldRules( AnnotationInstance rulesContainerAnnotation, RuleInfo ruleInfo,\n boolean applyToAllLocales )\n {\n //\n // First parse the locale from the wrapper annotation. This will apply to all rules inside.\n //\n Locale locale = null;\n\n if ( ! applyToAllLocales )\n {\n String language = CompilerUtils.getString( rulesContainerAnnotation, LANGUAGE_ATTR, true );\n\n //\n // If there's no language specified, then this rule will only apply for the default ruleset\n // (i.e., if there are explicit rules for the requested locale, this rule will not be run).\n //\n if ( language != null )\n {\n String country = CompilerUtils.getString( rulesContainerAnnotation, COUNTRY_ATTR, true );\n String variant = CompilerUtils.getString( rulesContainerAnnotation, VARIANT_ATTR, true );\n\n language = language.trim();\n if ( country != null ) country = country.trim();\n if ( variant != null ) variant = variant.trim();\n\n if ( country != null && variant != null ) locale = new Locale( language, country, variant );\n else if ( country != null ) locale = new Locale( language, country );\n else locale = new Locale( language );\n }\n }\n\n Map valuesPresent = rulesContainerAnnotation.getElementValues();\n\n for ( Iterator ii = valuesPresent.entrySet().iterator(); ii.hasNext(); )\n {\n Map.Entry entry = ( Map.Entry ) ii.next();\n AnnotationValue value = ( AnnotationValue ) entry.getValue();\n Object val = value.getValue();\n\n if ( val instanceof AnnotationInstance )\n {\n addFieldRuleFromAnnotation( ruleInfo, ( AnnotationInstance ) val, locale, applyToAllLocales );\n }\n else if ( val instanceof List )\n {\n List annotations = CompilerUtils.getAnnotationArray( value );\n\n for ( Iterator i3 = annotations.iterator(); i3.hasNext(); )\n {\n AnnotationInstance i = ( AnnotationInstance ) i3.next();\n addFieldRuleFromAnnotation( ruleInfo, i, locale, applyToAllLocales );\n }\n }\n }\n\n setEmpty( false ); // this ValidationModel is only \"empty\" if there are no rules.\n }"
] |
[
"@Override\n public void perform() throws PortalException {\n // push the change into the PLF\n if (nodeId.startsWith(Constants.FRAGMENT_ID_USER_PREFIX)) {\n // remove the parm edit\n ParameterEditManager.removeParmEditDirective(nodeId, name, person);\n }\n // push the fragment value into the ILF\n LPAChangeParameter.changeParameterChild(ilfNode, name, fragmentValue);\n }"
] |
codesearchnet
|
{
"query": "Represent the Github comment:",
"pos": "Represent the Github code:",
"neg": "Represent the Github code:"
}
|
Execute unpublishing documents
|
[
"private function manageDeleteDocument(&$params, &$dmsLoader, &$manageCategory, &$arrMessages, &$blnShowStart, $documentId)\n {\n $params->loadRootCategory = true; // get complete path to root, for checking inherited access rights\n $params->loadAccessRights = true;\n $params->loadDocuments = false;\n $category = $dmsLoader->loadCategory($manageCategory, $params);\n \n if (!$category->isDeletableForCurrentMember())\n {\n $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['manage_document_not_allowed'];\n $blnShowStart = true;\n }\n else\n {\n $document = $dmsLoader->loadDocument($documentId, $params);\n \n if ($document != null)\n {\n // delete the document in the database\n $dmsWriter = \\DmsWriter::getInstance();\n \n if ($dmsWriter->deleteDocument($document))\n {\n $arrMessages['successes'][] = $GLOBALS['TL_LANG']['DMS']['SUCCESS']['document_successfully_deleted'];\n \n // delete the file\n $filePath = \\DmsConfig::getDocumentFilePath($document->getFileNameVersioned());\n if (file_exists(TL_ROOT . '/' . $filePath))\n {\n unlink($filePath);\n \\Dbafs::deleteResource($filePath);\n \n $arrMessages['successes'][] = $GLOBALS['TL_LANG']['DMS']['SUCCESS']['document_file_successfully_deleted'];\n }\n else\n {\n $arrMessages['infos'][] = $GLOBALS['TL_LANG']['DMS']['INFO']['document_delete_file_not_exists'];\n }\n }\n else\n {\n $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['delete_document_failed'];\n }\n }\n else\n {\n $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['manage_document_not_found'];\n }\n $this->manageSelectDocument($params, $dmsLoader, $manageCategory, $arrMessages, $blnShowStart);\n }\n }"
] |
[
"def openCurrentItem(self):\n \n logger.debug(\"openCurrentItem\")\n _currentItem, currentIndex = self.getCurrentItem()\n if not currentIndex.isValid():\n return\n\n # Expanding the node will call indirectly call RepoTreeModel.fetchMore which will call\n # BaseRti.fetchChildren, which will call BaseRti.open and thus open the current RTI.\n # BaseRti.open will emit the self.model.sigItemChanged signal, which is connected to\n # RepoTreeView.onItemChanged.\n self.expand(currentIndex)"
] |
codesearchnet
|
{
"query": "Represent the sentence:",
"pos": "Represent the code:",
"neg": "Represent the code:"
}
|
Gets the value for the given key in the {@link Properties}; if this key is not found, a
RuntimeException is thrown.
@param key the key to get the value for
@param options options for getting configuration value
@return the value for the given key
|
[
"public static String get(PropertyKey key, ConfigurationValueOptions options) {\n return sConf.get(key, options);\n }"
] |
[
"function DataModelMigration() {\n /**\n * Gets an array that contains the definition of fields that are going to be added\n * @type {Array}\n */\n this.add = [];\n /**\n * Gets an array that contains a collection of constraints which are going to be added\n * @type {Array}\n */\n this.constraints = [];\n /**\n * Gets an array that contains a collection of indexes which are going to be added or updated\n * @type {Array}\n */\n this.indexes = [];\n /**\n * Gets an array that contains the definition of fields that are going to be deleted\n * @type {Array}\n */\n this.remove = [];\n /**\n * Gets an array that contains the definition of fields that are going to be changed\n * @type {Array}\n */\n this.change = [];\n /**\n * Gets or sets a string that contains the internal version of this migration. This property cannot be null.\n * @type {string}\n */\n this.version = '0.0';\n /**\n * Gets or sets a string that represents a short description of this migration\n * @type {string}\n */\n this.description = null;\n /**\n * Gets or sets a string that represents the adapter that is going to be migrated through this operation.\n * This property cannot be null.\n */\n this.appliesTo = null;\n /**\n * Gets or sets a string that represents the model that is going to be migrated through this operation.\n * This property may be null.\n */\n this.model = null;\n}"
] |
codesearchnet
|
{
"query": "Represent the summarization about text processing:",
"pos": "Represent the code about text processing:",
"neg": "Represent the code:"
}
|
Generate vendor directory
@param string $sVendor
|
[
"protected function _generateVendorDir($sVendor)\n {\n $sVendorDir = $this->_sModuleDir . $sVendor . DIRECTORY_SEPARATOR;\n if (!file_exists($sVendorDir)) {\n mkdir($sVendorDir);\n\n // Generate vendor metadata file\n file_put_contents($sVendorDir . 'vendormetadata.php', '<?php');\n }\n }"
] |
[
"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 Github sentence:",
"pos": "Represent the Github code:",
"neg": "Represent the Github code:"
}
|
Read a 32-bit little-endian integer from the internal buffer.
|
[
"public int readRawLittleEndian32() throws IOException\r\n {\r\n final byte[] buffer = this.buffer;\r\n int offset = this.offset;\r\n\r\n final byte b1 = buffer[offset++];\r\n final byte b2 = buffer[offset++];\r\n final byte b3 = buffer[offset++];\r\n final byte b4 = buffer[offset++];\r\n\r\n this.offset = offset;\r\n\r\n return (((int) b1 & 0xff)) |\r\n (((int) b2 & 0xff) << 8) |\r\n (((int) b3 & 0xff) << 16) |\r\n (((int) b4 & 0xff) << 24);\r\n }"
] |
[
"def write_tag(tag)\n # Group 0002 is always little endian, but the rest of the file may be little or big endian.\n # When we shift from group 0002 to another group we need to update our endian/explicitness variables:\n switch_syntax_on_write if tag.group != META_GROUP and @switched == false\n # Write to binary string:\n bin_tag = @stream.encode_tag(tag)\n add_encoded(bin_tag)\n end"
] |
codesearchnet
|
{
"query": "Represent the post about Computer Science:",
"pos": "Represent the code about Computer Science:",
"neg": "Represent the code about Programming:"
}
|
{@inheritdoc}
@param FlowQuery $flowQuery
@param array $arguments
@return void
@throws FizzleException
@throws \Neos\Eel\Exception
|
[
"public function evaluate(FlowQuery $flowQuery, array $arguments)\n {\n $subject = $arguments[0];\n if (!isset($subject) || empty($subject)) {\n $flowQuery->setContext([]);\n return;\n }\n\n $filteredContext = [];\n $context = $flowQuery->getContext();\n if (is_string($subject)) {\n foreach ($context as $contextElement) {\n $contextElementQuery = new FlowQuery([$contextElement]);\n $contextElementQuery->pushOperation('children', $arguments);\n if ($contextElementQuery->count() > 0) {\n $filteredContext[] = $contextElement;\n }\n }\n } else {\n if ($subject instanceof FlowQuery) {\n $elements = $subject->get();\n } elseif ($subject instanceof \\Traversable) {\n $elements = iterator_to_array($subject);\n } elseif (is_object($subject)) {\n $elements = [$subject];\n } elseif (is_array($subject)) {\n $elements = $subject;\n } else {\n throw new FizzleException('supplied argument for has operation not supported', 1332489625);\n }\n foreach ($elements as $element) {\n if ($element instanceof TraversableNodeInterface) {\n $parentsQuery = new FlowQuery([$element]);\n foreach ($parentsQuery->parents([])->get() as $parent) {\n /** @var TraversableNodeInterface $parent */\n foreach ($context as $contextElement) {\n /** @var TraversableNodeInterface $contextElement */\n if ($contextElement === $parent) {\n $filteredContext[] = $contextElement;\n }\n }\n }\n }\n }\n $filteredContext = array_unique($filteredContext);\n }\n\n $flowQuery->setContext($filteredContext);\n }"
] |
[
"public function boot(\\Neos\\Flow\\Core\\Bootstrap $bootstrap)\n {\n $bootstrap->registerRequestHandler(new \\Neos\\Setup\\Core\\RequestHandler($bootstrap));\n }"
] |
codesearchnet
|
{
"query": "Represent the description about API documentation:",
"pos": "Represent the code about API documentation:",
"neg": "Represent the code about Software development:"
}
|
ensureExists
@param string $dir
@return void
|
[
"private function ensureExists($dir)\n {\n if (!is_dir($dir)) {\n mkdir($dir, 0755, true);\n }\n\n return $this->validatePath($dir);\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 Software Development:",
"pos": "Represent the code about Software Development:",
"neg": "Represent the code about programming:"
}
|
// Error returns the JSONified version of this error which will
// trigger the appropriate integration mapping.
|
[
"func (apigError *Error) Error() string {\n\tbytes, bytesErr := json.Marshal(apigError)\n\tif bytesErr != nil {\n\t\tbytes = []byte(http.StatusText(http.StatusInternalServerError))\n\t}\n\treturn string(bytes)\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 comment about Natural Language Processing:",
"pos": "Represent the code about Natural Language Processing:",
"neg": "Represent the code about programming:"
}
|
Clean up, return key/value pairs
@param array $matched
@return array
@access protected
|
[
"protected function clearPairs(/*# array */ $matched)/*# : array */\n {\n $pairs = [];\n foreach ($matched as $m) {\n // source another env file\n if (isset($m[5])) {\n $file = trim($m[5]);\n $pairs[$file] = $this->source_marker;\n\n // value found\n } elseif (isset($m[3])) {\n $pairs[$m[1]] = $m[3];\n\n // no value defined\n } else {\n $pairs[$m[1]] = '';\n }\n }\n return $pairs;\n }"
] |
[
"def requests(self):\n ''''''\n path = pathjoin(self.path, self.name, Request.path)\n response = self.service.send(SRequest('GET', path))\n # a bin behaves as a push-down store --- better to return the requests\n # in order of appearance\n return list(reversed(Request.from_response(response, bin=self)))"
] |
codesearchnet
|
{
"query": "Represent the Github instruction about programming:",
"pos": "Represent the Github code about programming:",
"neg": "Represent the Github code:"
}
|
Connects to all the event listeners
@method startListening
@chainable
|
[
"function () {\n this.events.on('report:run:browser', this.runBrowser.bind(this));\n this.events.on('report:assertion', this.assertion.bind(this));\n this.events.on('report:test:started', this.testStarted.bind(this));\n this.events.on('report:test:finished', this.testFinished.bind(this));\n this.events.on('report:runner:finished', this.runnerFinished.bind(this));\n this.events.on('report:testsuite:started', this.testsuiteStarted.bind(this));\n //this.events.on('report:testsuite:finished', this.testsuiteFinished.bind(this));\n return this;\n }"
] |
[
"function onPatchesDerive() {\n\t\tvar patches = this.patches;\n\t\tthis.patches = [];\n\t\tqueues.enqueueByQueue(this.handlers.getNode([]), this.currentList, [patches, this.currentList], null,[\"Apply patches\", patches]);\n\t}"
] |
codesearchnet
|
{
"query": "Represent the Github instruction about Software development:",
"pos": "Represent the Github code about Software development:",
"neg": "Represent the Github code about software development:"
}
|
12.12 Labelled Statement
|
[
"private ParseTree parseLabelledStatement() {\n SourcePosition start = getTreeStartLocation();\n IdentifierToken name = eatId();\n eat(TokenType.COLON);\n return new LabelledStatementTree(getTreeLocation(start), name, parseStatement());\n }"
] |
[
"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 post:",
"pos": "Represent the code:",
"neg": "Represent the code:"
}
|
Browse Episodes of an remote application (with the keychain)
@Route("/remote/{keychain}", name="oktolab_media_remote_episodes")
@Method("GET")
@Template()
|
[
"public function listRemoteEpisodes(Keychain $keychain)\n {\n $episodes_url = $this->get('bprs_applink')->getApiUrlsForKey(\n $keychain,\n 'oktolab_media_api_list_episodes'\n );\n\n if ($episodes_url) {\n $client = new Client();\n $response = $client->request(\n 'GET',\n $episodes_url,\n ['auth' => [$keychain->getUser(), $keychain->getApiKey()]]\n );\n\n if ($response->getStatusCode() == 200) {\n $info = json_decode(\n html_entity_decode((string)$response->getBody()), true\n );\n\n return ['result' => $info, 'keychain' => $keychain];\n }\n }\n\n return new Response('', Response::HTTP_BAD_REQUEST);\n }"
] |
[
"def unregisterSds(self, sdsObj):\n \n self.conn.connection._check_login()\n response = self.conn.connection._do_post(\"{}/{}{}/{}\".format(self.conn.connection._api_url, \"instances/Sds::\", sdsObj.id, 'action/removeSds')) \n return response"
] |
codesearchnet
|
{
"query": "Represent the comment about Software development:",
"pos": "Represent the code about Software development:",
"neg": "Represent the code:"
}
|
Checks if a symbol is a special.
@param NumberPatternSymbol $symbol
@param array $is
An array of self::SYMBOL_* constants, one of which the symbol should
match.
@return boolean
|
[
"function symbolIsSpecial(NumberPatternSymbol $symbol, array $is) {\n return !$symbol->escaped && in_array($symbol->symbol, $is, TRUE);\n }"
] |
[
"public function initializeArguments()\n {\n $this->registerArgument('value', 'string', 'The input value. If not given, the evaluated child nodes will be used', false, null);\n $this->registerArgument('mode', 'string', 'The case to apply, must be one of this\\' CASE_* constants. Defaults to uppercase application', false, self::CASE_UPPER);\n }"
] |
codesearchnet
|
{
"query": "Represent the instruction about Software development:",
"pos": "Represent the code about Software development:",
"neg": "Represent the code about Programming:"
}
|
Invoke method, every class will have its own
returns true/false on completion, setting both
errormsg and output as necessary
|
[
"function invoke() {\n parent::invoke();\n\n $result = true;\n\n // Set own core attributes\n $this->does_generate = ACTION_NONE;\n\n // These are always here\n global $CFG, $XMLDB;\n\n // Do the job, setting result as needed\n\n // Get the dir containing the file\n $dirpath = required_param('dir', PARAM_PATH);\n $dirpath = $CFG->dirroot . $dirpath;\n\n // Get the original dir and delete some elements\n if (!empty($XMLDB->dbdirs)) {\n if (isset($XMLDB->dbdirs[$dirpath])) {\n $dbdir = $XMLDB->dbdirs[$dirpath];\n if ($dbdir) {\n unset($dbdir->xml_file);\n unset($dbdir->xml_loaded);\n unset($dbdir->xml_changed);\n unset($dbdir->xml_exists);\n unset($dbdir->xml_writeable);\n }\n }\n }\n // Get the edited dir and delete it completely\n if (!empty($XMLDB->editeddirs)) {\n if (isset($XMLDB->editeddirs[$dirpath])) {\n unset($XMLDB->editeddirs[$dirpath]);\n }\n }\n\n // Launch postaction if exists (leave this here!)\n if ($this->getPostAction() && $result) {\n return $this->launch($this->getPostAction());\n }\n\n // Return ok if arrived here\n return $result;\n }"
] |
[
"function run(booleanOrString, anyDataType, functionOrObject, aNumber, anArray) {\n /*\n * if expectations aren't met, args checker will throw appropriate exceptions\n * notifying the user regarding the errors of the arguments.\n * */\n \targs.expect(arguments, ['boolean|string', '*', 'function|object', 'number', 'array']);\n\n // do something here...\n console.log(\"\\n\\nfunction `run` arguments passed!\");\n }"
] |
codesearchnet
|
{
"query": "Represent the Github comment:",
"pos": "Represent the Github code:",
"neg": "Represent the Github code about programming:"
}
|
// Beep beeps the PC speaker (https://en.wikipedia.org/wiki/PC_speaker).
|
[
"func Beep(freq float64, duration int) error {\n\tif freq == 0 {\n\t\tfreq = DefaultFreq\n\t} else if freq > 32767 {\n\t\tfreq = 32767\n\t} else if freq < 37 {\n\t\tfreq = DefaultFreq\n\t}\n\n\tif duration == 0 {\n\t\tduration = DefaultDuration\n\t}\n\n\tkernel32, _ := syscall.LoadLibrary(\"kernel32.dll\")\n\tbeep32, _ := syscall.GetProcAddress(kernel32, \"Beep\")\n\n\tdefer syscall.FreeLibrary(kernel32)\n\n\t_, _, e := syscall.Syscall(uintptr(beep32), uintptr(2), uintptr(int(freq)), uintptr(duration), 0)\n\tif e != 0 {\n\t\treturn e\n\t}\n\n\treturn nil\n}"
] |
[
"def play(state):\n \n filename = None\n if state == SoundService.State.welcome:\n filename = \"pad_glow_welcome1.wav\"\n elif state == SoundService.State.goodbye:\n filename = \"pad_glow_power_off.wav\"\n elif state == SoundService.State.hotword_detected:\n filename = \"pad_soft_on.wav\"\n elif state == SoundService.State.asr_text_captured:\n filename = \"pad_soft_off.wav\"\n elif state == SoundService.State.error:\n filename = \"music_marimba_error_chord_2x.wav\"\n\n if filename is not None:\n AudioPlayer.play_async(\"{}/{}\".format(ABS_SOUND_DIR, filename))"
] |
codesearchnet
|
{
"query": "Represent the description:",
"pos": "Represent the code:",
"neg": "Represent the code about Software development:"
}
|
Returns the direct properties of this resource in a map.<p>
This is without "search", so it will not include inherited properties from the parent folders.<p>
@return the direct properties of this resource in a map
|
[
"public Map<String, String> getProperty() {\n\n if (m_properties == null) {\n try {\n List<CmsProperty> properties = m_cms.readPropertyObjects(this, false);\n m_properties = CmsProperty.toMap(properties);\n } catch (CmsException e) {\n if (LOG.isDebugEnabled()) {\n LOG.debug(e.getMessage(), e);\n }\n }\n }\n return m_properties;\n }"
] |
[
"function(loader) {\n // public\n this.maxRecursion = 5;\n this.loader = (typeof loader === 'function') ? loader : null;\n\n // internal\n this._schemaRegistry = new SchemaRegistry();\n this._customFormatHandlers = {};\n\n // _refsRequested is an object where the key is the normalized ID\n // of the schema ref that was requested, and the value is a\n // promise for the content of that schema.\n this._refsRequested = {};\n}"
] |
codesearchnet
|
{
"query": "Represent the sentence about Software development:",
"pos": "Represent the code about Software development:",
"neg": "Represent the code:"
}
|
Write mesage to tansport. msg should be a member of a valid `protobuf class <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_ with a SerializeToString() method.
|
[
"def write(self, msg):\n \n ser = msg.SerializeToString()\n header = struct.pack(\">HL\", mapping.get_type(msg), len(ser))\n self._write(b\"##\" + header + ser, msg)"
] |
[
"def requests(self):\n ''''''\n path = pathjoin(self.path, self.name, Request.path)\n response = self.service.send(SRequest('GET', path))\n # a bin behaves as a push-down store --- better to return the requests\n # in order of appearance\n return list(reversed(Request.from_response(response, bin=self)))"
] |
codesearchnet
|
{
"query": "Represent the description about Software development:",
"pos": "Represent the code about Software development:",
"neg": "Represent the code:"
}
|
@param CreditCard $card
@return CreditCard
|
[
"public function tokenizeCard(CreditCard $card)\n {\n $tokenizeCardRequest = new TokenizeCardRequest($this->merchant, $this->environment);\n\n return $tokenizeCardRequest->execute($card);\n }"
] |
[
"public function execute($request)\n {\n RequestNotSupportedException::assertSupports($this, $request);\n $this->logger->info(\"Ecommpay order #{$request->getFirstModel()->getOrder()->getNumber()} have paid\");\n throw new HttpResponse('OK');\n }"
] |
codesearchnet
|
{
"query": "Represent the Github summarization about programming:",
"pos": "Represent the Github code about programming:",
"neg": "Represent the Github code about Software development:"
}
|
Drop several tables at once
@param array $tables
@param boolean $fkChecks Whether to enabled Foreign Key checks
@return boolean
|
[
"final public function dropTables(array $tables, $fkChecks = false)\n {\n // Whether FK checks are enabled\n if ($fkChecks == false) {\n $this->db->raw('SET FOREIGN_KEY_CHECKS=0')\n ->execute();\n }\n\n foreach ($tables as $table) {\n if (!$this->dropTable($table)) {\n return false;\n }\n }\n\n // Whether FK checks are enabled\n if ($fkChecks == false) {\n $this->db->raw('SET FOREIGN_KEY_CHECKS=1')\n ->execute();\n }\n\n return true;\n }"
] |
[
"public function initialize() {\n $this->keepSnapshots(true);\n $this->setup(\n array(\n 'exceptionOnFailedSave' => true, //Throw an exception instead of returning false from saves\n 'notNullValidations' => false //Allow empty strings instead of the wtf new \\Phalcon\\Db\\RawValue('\"\"');\n )\n );\n //Sets to only update the fields that are changed\n $this->useDynamicUpdate(true);\n }"
] |
codesearchnet
|
{
"query": "Represent the comment:",
"pos": "Represent the code:",
"neg": "Represent the code about programming:"
}
|
Executes a detach operation on the given entity.
@param object $entity
@param array $visited
@param boolean $noCascade if true, don't cascade detach operation.
@return void
|
[
"private function doDetach($entity, array &$visited, $noCascade = false)\n {\n $oid = spl_object_hash($entity);\n\n if (isset($visited[$oid])) {\n return; // Prevent infinite recursion\n }\n\n $visited[$oid] = $entity; // mark visited\n\n switch ($this->getEntityState($entity, self::STATE_DETACHED)) {\n case self::STATE_MANAGED:\n if ($this->isInIdentityMap($entity)) {\n $this->removeFromIdentityMap($entity);\n }\n\n unset(\n $this->entityInsertions[$oid],\n $this->entityUpdates[$oid],\n $this->entityDeletions[$oid],\n $this->entityIdentifiers[$oid],\n $this->entityStates[$oid],\n $this->originalEntityData[$oid]\n );\n break;\n case self::STATE_NEW:\n case self::STATE_DETACHED:\n return;\n }\n\n if ( ! $noCascade) {\n $this->cascadeDetach($entity, $visited);\n }\n }"
] |
[
"protected function postStoreProcess()\n {\n $aggregate = $this->aggregate;\n\n // Create any related object that doesn't exist in the database.\n $foreignRelationships = $aggregate->getEntityMap()->getForeignRelationships();\n\n $this->createRelatedEntities($foreignRelationships);\n\n // Update any pivot tables that has been modified.\n $aggregate->updatePivotRecords();\n\n // Update any dirty relationship. This include relationships that already exists, have\n // dirty attributes / newly created related entities / dirty related entities.\n $dirtyRelatedAggregates = $aggregate->getDirtyRelationships();\n\n foreach ($dirtyRelatedAggregates as $related) {\n $this->createStoreCommand($related)->execute();\n }\n\n // Now we can sync the related collections\n //\n // TODO (note) : not sure this check is needed, as we can assume\n // the aggregate exists in the Post Store Process\n if ($this->aggregate->exists()) {\n $this->aggregate->syncRelationships($foreignRelationships);\n }\n\n // TODO be move it to the wrapper class\n // so it's the same code for the entity builder\n $aggregate->setProxies();\n\n // Update Entity Cache\n $aggregate->getMapper()->getEntityCache()->refresh($aggregate);\n }"
] |
codesearchnet
|
{
"query": "Represent the Github instruction about Software development:",
"pos": "Represent the Github code about Software development:",
"neg": "Represent the Github code about Software development:"
}
|
@param array $attributes
@param Assertion $assertion
@return array
|
[
"private function resolveAttributesFromAssertion(array $attributes, Assertion $assertion)\n {\n $attributeStatements = $assertion->getAllAttributeStatements();\n\n return array_reduce($attributeStatements, [$this, 'resolveAttributesFromAttributeStatement'], $attributes);\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 text about programming:",
"pos": "Represent the Github code about programming:",
"neg": "Represent the Github code:"
}
|
To date.
@param value the value
@return the date
|
[
"public static Date toDate(final Object value) {\r\n\t\tif (value instanceof Date) {\r\n\t\t\treturn (Date) value;\r\n\t\t}\r\n\t\tif (value == null || value.equals(\"null\")) {\r\n\t\t\treturn null;\r\n\t\t}\r\n\t\tif (value instanceof String) {\r\n\t\t\tthrow new IllegalStateException(\"fix me\");\r\n\t\t}\r\n\r\n\t\treturn null;\r\n\t}"
] |
[
"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 post about Software Development:",
"pos": "Represent the code about Software Development:",
"neg": "Represent the code about programming:"
}
|
Calculate the centre x position
|
[
"function (d, chart, series) {\n var returnCx = 0;\n if (series.x.measure !== null && series.x.measure !== undefined) {\n returnCx = series.x._scale(d.cx);\n } else if (series.x._hasCategories() && series.x.categoryFields.length >= 2) {\n returnCx = series.x._scale(d.cx) + dimple._helpers.xGap(chart, series) + ((d.xOffset + 0.5) * (((chart._widthPixels() / series.x._max) - 2 * dimple._helpers.xGap(chart, series)) * d.width));\n } else {\n returnCx = series.x._scale(d.cx) + ((chart._widthPixels() / series.x._max) / 2);\n }\n return returnCx;\n }"
] |
[
"def _calculate_index_of_coincidence(frequency_map, length):\n \n if length <= 1:\n return 0\n # We cannot error here as length can legitimiately be 1.\n # Imagine a ciphertext of length 3 and a key of length 2.\n # Spliting this text up and calculating the index of coincidence results in ['AC', 'B']\n # IOC of B will be calcuated for the 2nd column of the key. We could represent the same\n # encryption with a key of length 3 but then we encounter the same problem. This is also\n # legitimiate encryption scheme we cannot ignore. Hence we have to deal with this fact here\n # A value of 0 will impact the overall mean, however it does make some sense when you ask the question\n # How many ways to choose 2 letters from the text, if theres only 1 letter then the answer is 0.\n\n # Mathemtical combination, number of ways to choose 2 letters, no replacement, order doesnt matter\n combination_of_letters = sum(freq * (freq - 1) for freq in frequency_map.values())\n return combination_of_letters / (length * (length - 1))"
] |
codesearchnet
|
{
"query": "Represent the sentence:",
"pos": "Represent the code:",
"neg": "Represent the code:"
}
|
HTTP Method Patch
@param string $uri optional uri to use
@param string $payload data to send in body of request
@param string $mime MIME to use for Content-Type
@return Request
|
[
"public static function patch($uri, $payload = null, $mime = null)\n {\n return self::init(Http::PATCH)->uri($uri)->body($payload, $mime);\n }"
] |
[
"public function prepareResponse(): void\n {\n // change default HTTP status code\n $this->response->setStatusCode(200);\n\n // clear default response headers\n $this->response->resetHeaders();\n\n // add your response headers\n $this->response->setCharset('UTF-8');\n $this->response->setContentType('text/html');\n $this->response->addHeader(\n 'X-Some-Header-Example-Name: headerValueExample'\n ); // add some other headers by this example\n\n // call here your controller to get real response body\n $body = 'This is an example generated in Route <i>' . get_class($this) . '</i> with a fictive Controller.';\n\n // set body to response as response body\n $this->response->setBody($body);\n }"
] |
codesearchnet
|
{
"query": "Represent the Github instruction about Software development:",
"pos": "Represent the Github code about Software development:",
"neg": "Represent the Github code about Programming:"
}
|
@param Ability $ability
@param array $options
@return array
|
[
"public function serialize(Ability $ability, array $options = [])\n {\n $serialized = [\n 'id' => $ability->getUuid(),\n 'name' => $ability->getName(),\n 'minResourceCount' => $ability->getMinResourceCount(),\n 'minEvaluatedResourceCount' => $ability->getMinEvaluatedResourceCount(),\n ];\n\n return $serialized;\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 text about programming:",
"pos": "Represent the code about programming:",
"neg": "Represent the code:"
}
|
// NoAutoCondition disable generate SQL condition from beans
|
[
"func (session *Session) NoAutoCondition(no ...bool) *Session {\n\tsession.Statement.NoAutoCondition(no...)\n\treturn session\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 sentence:",
"pos": "Represent the Github code:",
"neg": "Represent the Github code:"
}
|
Make data filter definition consistent.
Create a tuple where first element is the row filter and the second element
is the column filter
|
[
"def _homogenize_data_filter(dfilter):\n \n if isinstance(dfilter, tuple) and (len(dfilter) == 1):\n dfilter = (dfilter[0], None)\n if (dfilter is None) or (dfilter == (None, None)) or (dfilter == (None,)):\n dfilter = (None, None)\n elif isinstance(dfilter, dict):\n dfilter = (dfilter, None)\n elif isinstance(dfilter, (list, str)) or (\n isinstance(dfilter, int) and (not isinstance(dfilter, bool))\n ):\n dfilter = (None, dfilter if isinstance(dfilter, list) else [dfilter])\n elif isinstance(dfilter[0], dict) or (\n (dfilter[0] is None) and (not isinstance(dfilter[1], dict))\n ):\n pass\n else:\n dfilter = (dfilter[1], dfilter[0])\n return dfilter"
] |
[
"def reset ():\n \n global __prefixes_suffixes, __suffixes_to_types, __types, __rule_names_to_types, __target_suffixes_cache\n\n __register_features ()\n\n # Stores suffixes for generated targets.\n __prefixes_suffixes = [property.PropertyMap(), property.PropertyMap()]\n\n # Maps suffixes to types\n __suffixes_to_types = {}\n\n # A map with all the registered types, indexed by the type name\n # Each entry is a dictionary with following values:\n # 'base': the name of base type or None if type has no base\n # 'derived': a list of names of type which derive from this one\n # 'scanner': the scanner class registered for this type, if any\n __types = {}\n\n # Caches suffixes for targets with certain properties.\n __target_suffixes_cache = {}"
] |
codesearchnet
|
{
"query": "Represent the Github sentence:",
"pos": "Represent the Github code:",
"neg": "Represent the Github code:"
}
|
Modifies a list of contacts.
Provide comma separated list of contact ids and desired paused state
Returns status message
|
[
"def modifyContacts(self, contactids, paused):\n \n\n response = self.request(\"PUT\", \"notification_contacts\", {'contactids': contactids,\n 'paused': paused})\n return response.json()['message']"
] |
[
"def _get_generic_schema(self):\n \n schema = Schema(\n vid=ID(stored=True, unique=True), # Object id\n title=NGRAMWORDS(),\n keywords=KEYWORD, # Lists of coverage identifiers, ISO time values and GVIDs, source names, source abbrev\n doc=TEXT) # Generated document for the core of the topic search\n return schema"
] |
codesearchnet
|
{
"query": "Represent the instruction about Documentation:",
"pos": "Represent the code about Documentation:",
"neg": "Represent the code:"
}
|
Returns the @GROUPID.
If derived_from is set, returns that group_id.
|
[
"def group_id(self):\n \n if self.derived_from is not None:\n return self.derived_from.group_id()\n if self.file_uuid is None:\n return None\n return utils.GROUP_ID_PREFIX + self.file_uuid"
] |
[
"def _extract_lookup(self, key):\n \"\"\"\"\"\"\n parts = key.split('__')\n # 'exact' is the default lookup if there was no explicit comparison op in `key`\n # Assume there is only one `__` in the key.\n # FIXME Change for child attribute query support\n op = 'exact' if len(parts) == 1 else parts[1]\n\n # Construct and assign the lookup class as a filter criteria\n return parts[0], self.get_lookup(op)"
] |
codesearchnet
|
{
"query": "Represent the Github comment about programming:",
"pos": "Represent the Github code about programming:",
"neg": "Represent the Github code about programming:"
}
|
Create a TypedArray instance.
@param {object} config
@returns {TypedArray}
@augments Typed
@constructor
|
[
"function TypedArray (config) {\n const array = this;\n\n // validate min items\n if (config.hasOwnProperty('minItems') && (!util.isInteger(config.minItems) || config.minItems < 0)) {\n throw Error('Invalid configuration value for property: minItems. Must be an integer that is greater than or equal to zero. Received: ' + config.minItems);\n }\n const minItems = config.hasOwnProperty('minItems') ? config.minItems : 0;\n\n // validate max items\n if (config.hasOwnProperty('maxItems') && (!util.isInteger(config.maxItems) || config.maxItems < minItems)) {\n throw Error('Invalid configuration value for property: maxItems. Must be an integer that is greater than or equal to the minItems. Received: ' + config.maxItems);\n }\n\n // validate schema\n if (config.hasOwnProperty('schema')) config.schema = FullyTyped(config.schema);\n\n // define properties\n Object.defineProperties(array, {\n\n maxItems: {\n /**\n * @property\n * @name TypedArray#maxItems\n * @type {number}\n */\n value: Math.round(config.maxItems),\n writable: false\n },\n\n minItems: {\n /**\n * @property\n * @name TypedArray#minItems\n * @type {number}\n */\n value: Math.round(config.minItems),\n writable: false\n },\n\n schema: {\n /**\n * @property\n * @name TypedArray#schema\n * @type {object}\n */\n value: config.schema,\n writable: false\n },\n\n uniqueItems: {\n /**\n * @property\n * @name TypedArray#uniqueItems\n * @type {boolean}\n */\n value: !!config.uniqueItems,\n writable: false\n }\n\n });\n\n return array;\n}"
] |
[
"function BinaryPacker_pack(source, // @arg Any - source data\n formatID) { // @arg Integer - 0x0001 - 0xffff\n // @ret Uint8Array|null\n//{@dev\n $valid(_isValidFormatID(formatID), BinaryPacker_pack, \"formatID\");\n//}@dev\n var moduleID = \"BinaryPacker\" + _toHex(formatID); // \"BinaryPacker0x0001\"\n\n return global[moduleID][\"pack\"](source);\n}"
] |
codesearchnet
|
{
"query": "Represent the Github post about Software development:",
"pos": "Represent the Github code about Software development:",
"neg": "Represent the Github code about Java programming:"
}
|
/*
(non-Javadoc)
@see javax.servlet.sip.SipServletMessage#getLocalAddr()
|
[
"public String getLocalAddr() {\n\t\tfinal SIPTransaction sipTransaction = (SIPTransaction)getTransaction();\n\t\tif(sipTransaction != null) {\n\t\t\treturn sipTransaction.getHost();\n\t\t} else {\n\t\t\tfinal String transport = JainSipUtils.findTransport(message);\n\t\t\tfinal MobicentsExtendedListeningPoint listeningPoint = sipFactoryImpl.getSipNetworkInterfaceManager().findMatchingListeningPoint(transport, false);\n\t\t\treturn listeningPoint.getHost(true);\n\t\t}\n\t}"
] |
[
"public void scheduleAsynchronousWork(SipSessionAsynchronousWork work) {\n\t\tsipFactory.getSipApplicationDispatcher().getAsynchronousExecutor().execute(new SipSessionAsyncTask(key, work, sipFactory));\n\t}"
] |
codesearchnet
|
{
"query": "Represent the description about Computer Science:",
"pos": "Represent the code about Computer Science:",
"neg": "Represent the code:"
}
|
Export a literal as an XPath expression
@param mixed $value Literal, e.g. "foo"
@return string XPath expression, e.g. "'foo'"
|
[
"public static function export($value)\n\t{\n\t\tif (!is_scalar($value))\n\t\t{\n\t\t\tthrow new InvalidArgumentException(__METHOD__ . '() cannot export non-scalar values');\n\t\t}\n\t\tif (is_int($value))\n\t\t{\n\t\t\treturn (string) $value;\n\t\t}\n\t\tif (is_float($value))\n\t\t{\n\t\t\t// Avoid locale issues by using sprintf()\n\t\t\treturn preg_replace('(\\\\.?0+$)', '', sprintf('%F', $value));\n\t\t}\n\n\t\treturn self::exportString((string) $value);\n\t}"
] |
[
"public function normalizeRules($rules)\n {\n // If you want to use a pipe in a regex, custom message etc,\n // single-quote the string (escaping would be too confusing in regexes):\n //\n // This works with:\n //\n // 'foo?\\'my piped | string\\''\n // \"foo?'my piped | string'\"\n //\n // BIG NOTE: There is a reason why there are 2 formats. I don't\n // want developres to use ONLY the pipe format. There is always\n // multi-argument format, where argument can be anything, and\n // we don't complicate things and try to get around regexps\n //\n // is('name|required?my pipe|string') // Bad\n // is('name','required?my pipe|string') // Good\n // is('name','required?','my pipe|string') // Best\n\n // TODO: clean up\n $rules = preg_split('/[|,:]/', $rules);\n $field = array_shift($rules);\n\n return array($field, $rules);\n }"
] |
codesearchnet
|
{
"query": "Represent the Github text about Software development:",
"pos": "Represent the Github code about Software development:",
"neg": "Represent the Github code:"
}
|
Set person address
@param array|Address $value Parameter value
@return Person provides a fluent interface.
|
[
"public function setAddress($value)\n {\n if (is_array($value)) {\n $value = new Address($value);\n }\n return $this->setParameter('address', $value);\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 description about programming:",
"pos": "Represent the Github code about programming:",
"neg": "Represent the Github code:"
}
|
Return connection base type device
@param array $params
@param string $type
@return object
|
[
"public function getConnection(array $params, $type) {\n if ($type == 'S') {\n $host = (!empty($params['num_ip'])) ? $params['num_ip'] : '127.0.0.1';\n $community = (!empty($params['des_snmp_community'])) ? $params['des_snmp_community'] : 'public';\n $version = (!empty($params['des_snmp_version'])) ? $params['des_snmp_version'] : '2c';\n $seclevel = (!empty($params['des_snmp_sec_level'])) ? $params['des_snmp_sec_level'] : 'noAuthNoPriv';\n $authprotocol = (!empty($params['des_snmp_auth_protocol'])) ? $params['des_snmp_auth_protocol'] : 'MD5';\n $authpassphrase = (!empty($params['des_snmp_auth_passphrase'])) ? $params['des_snmp_auth_passphrase'] : 'None';\n $privprotocol = (!empty($params['des_snmp_priv_protocol'])) ? $params['des_snmp_priv_protocol'] : 'DES';\n $privpassphrase = (!empty($params['des_snmp_priv_passphrase'])) ? $params['des_snmp_priv_passphrase'] : 'None';\n\n $connection = new \\Cityware\\Snmp\\SNMP($host, $community, $version, $seclevel, $authprotocol, $authpassphrase, $privprotocol, $privpassphrase);\n $connection->setSecLevel(3);\n $connection->disableCache();\n\n $this->setSnmpCon($connection);\n } else if ($type == 'W') {\n $host = (!empty($params['num_ip'])) ? $params['num_ip'] : '127.0.0.1';\n $username = (!empty($params['des_wmi_user'])) ? $params['des_wmi_user'] : null;\n $password = (!empty($params['des_wmi_password'])) ? $params['des_wmi_password'] : null;\n $domain = (!empty($params['des_wmi_domain'])) ? $params['des_wmi_domain'] : null;\n $wmi = new \\Cityware\\Wmi\\Wmi($host, $username, $password, $domain);\n $connection = $wmi->connect('root\\\\cimv2');\n $this->setWmiCon($connection);\n }\n\n return $connection;\n }"
] |
[
"def getDeviceRole(self):\n \"\"\"\"\"\"\n print '%s call getDeviceRole' % self.port\n return self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v Network:NodeType')[0])"
] |
codesearchnet
|
{
"query": "Represent the Github sentence about Software development:",
"pos": "Represent the Github code about Software development:",
"neg": "Represent the Github code:"
}
|
Marks passed node as active
@param string $nodeId node id
|
[
"public function markNodeActive($nodeId)\n {\n $xPath = new DOMXPath($this->getDomXml());\n $nodeList = $xPath->query(\"//*[@cl='{$nodeId}' or @list='{$nodeId}']\");\n\n if ($nodeList->length) {\n foreach ($nodeList as $node) {\n // special case for external resources\n $node->setAttribute('active', 1);\n $node->parentNode->setAttribute('active', 1);\n }\n }\n }"
] |
[
"def getDeviceRole(self):\n \"\"\"\"\"\"\n print '%s call getDeviceRole' % self.port\n return self.__stripValue(self.__sendCommand(WPANCTL_CMD + 'getprop -v Network:NodeType')[0])"
] |
codesearchnet
|
{
"query": "Represent the Github instruction about Software development:",
"pos": "Represent the Github code about Software development:",
"neg": "Represent the Github code:"
}
|
Remove keys from the public or secret keyrings.
:param keys: Single key ID or list of mutiple IDs
:param secret: Delete secret keys
:rtype: DeleteResult
|
[
"def delete_keys(self, keys, secret=False):\n '''\n \n '''\n return self.execute(\n DeleteResult(),\n ['--batch', '--yes', '--delete-secret-key' if secret else '--delete-key'] + list(make_list(keys))\n )"
] |
[
"def reset ():\n \n global __prefixes_suffixes, __suffixes_to_types, __types, __rule_names_to_types, __target_suffixes_cache\n\n __register_features ()\n\n # Stores suffixes for generated targets.\n __prefixes_suffixes = [property.PropertyMap(), property.PropertyMap()]\n\n # Maps suffixes to types\n __suffixes_to_types = {}\n\n # A map with all the registered types, indexed by the type name\n # Each entry is a dictionary with following values:\n # 'base': the name of base type or None if type has no base\n # 'derived': a list of names of type which derive from this one\n # 'scanner': the scanner class registered for this type, if any\n __types = {}\n\n # Caches suffixes for targets with certain properties.\n __target_suffixes_cache = {}"
] |
codesearchnet
|
{
"query": "Represent the Github description about Software Development:",
"pos": "Represent the Github code about Software Development:",
"neg": "Represent the Github code:"
}
|
unique method
@method unique
|
[
"public function unique() : Collection\n {\n $acc = [];\n foreach ($this->list as $item) {\n if (!in_array($item, $acc)) {\n $acc[] = $item;\n }\n }\n\n return self::from(...$acc);\n }"
] |
[
"def :\n \"\"\"\"\"\"\n CheckParent(self)\n\n return _fitz.Annot_"
] |
codesearchnet
|
{
"query": "Represent the Github comment:",
"pos": "Represent the Github code:",
"neg": "Represent the Github code:"
}
|
ubuntu 16.04 systemctl service config
:param service_name:
:param start_cmd:
:param stop_cmd:
:return:
|
[
"def systemctl_autostart(self, service_name, start_cmd, stop_cmd):\n \n # get config content\n service_content = bigdata_conf.systemctl_config.format(\n service_name=service_name,\n start_cmd=start_cmd,\n stop_cmd=stop_cmd\n )\n\n # write config into file\n with cd('/lib/systemd/system'):\n if not exists(service_name):\n sudo('touch {0}'.format(service_name))\n put(StringIO(service_content), service_name, use_sudo=True)\n\n # make service auto-start\n sudo('systemctl daemon-reload')\n sudo('systemctl disable {0}'.format(service_name))\n sudo('systemctl stop {0}'.format(service_name))\n sudo('systemctl enable {0}'.format(service_name))\n sudo('systemctl start {0}'.format(service_name))"
] |
[
"def server_pxe(host=None,\n admin_username=None,\n admin_password=None):\n '''\n \n '''\n if __execute_cmd('config -g cfgServerInfo -o cfgServerFirstBootDevice PXE',\n host=host, admin_username=admin_username,\n admin_password=admin_password):\n if __execute_cmd('config -g cfgServerInfo -o cfgServerBootOnce 1',\n host=host, admin_username=admin_username,\n admin_password=admin_password):\n return server_reboot\n else:\n log.warning('failed to set boot order')\n return False\n\n log.warning('failed to configure PXE boot')\n return False"
] |
codesearchnet
|
{
"query": "Represent the description:",
"pos": "Represent the code:",
"neg": "Represent the code:"
}
|
Set the ``xlink:href`` of this file.
|
[
"def url(self, url):\n \n if url is None:\n return\n el_FLocat = self._el.find('mets:FLocat', NS)\n if el_FLocat is None:\n el_FLocat = ET.SubElement(self._el, TAG_METS_FLOCAT)\n el_FLocat.set(\"{%s}href\" % NS[\"xlink\"], url)"
] |
[
"function parse_drawing(data, rels) {\n\tif(!data) return \"??\";\n\t/*\n\t Chartsheet Drawing:\n\t - 20.5.2.35 wsDr CT_Drawing\n\t - 20.5.2.1 absoluteAnchor CT_AbsoluteAnchor\n\t - 20.5.2.16 graphicFrame CT_GraphicalObjectFrame\n\t - 20.1.2.2.16 graphic CT_GraphicalObject\n\t - 20.1.2.2.17 graphicData CT_GraphicalObjectData\n - chart reference\n\t the actual type is based on the URI of the graphicData\n\t\tTODO: handle embedded charts and other types of graphics\n\t*/\n\tvar id = (data.match(/<c:chart [^>]*r:id=\"([^\"]*)\"/)||[\"\",\"\"])[1];\n\n\treturn rels['!id'][id].Target;\n}"
] |
codesearchnet
|
{
"query": "Represent the Github text:",
"pos": "Represent the Github code:",
"neg": "Represent the Github code:"
}
|
@param mixed $use_customer_key
@return Realm
|
[
"public function setUseCustomerKey( $use_customer_key )\n\t{\n\t\t$this->use_customer_key = ($use_customer_key == 1 || $use_customer_key == 'Y' || $use_customer_key === TRUE) ? TRUE : FALSE;\n\n\t\treturn $this;\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 summarization about Programming:",
"pos": "Represent the code about Programming:",
"neg": "Represent the code about programming:"
}
|
Create an instance of {@link JAXBElement }{@code <}{@link MsupType }{@code >}}
|
[
"@XmlElementDecl(namespace = \"http://www.w3.org/1998/Math/MathML\", name = \"msup\")\n public JAXBElement<MsupType> createMsup(MsupType value) {\n return new JAXBElement<MsupType>(_Msup_QNAME, MsupType.class, null, value);\n }"
] |
[
"@SuppressWarnings(\"unchecked\")\n public Map<String, Field> getValueAsMap() {\n return (Map<String, Field>) type.convert(getValue(), Type.MAP);\n }"
] |
codesearchnet
|
{
"query": "Represent the comment about Software development:",
"pos": "Represent the code about Software development:",
"neg": "Represent the code about programming:"
}
|
Compute SHA-1 hash value for a given input stream.
@param in Input stream
@return SHA-1 hash value (array of 20 bytes).
|
[
"static byte[] sha1(InputStream in) {\n try {\n MessageDigest md = MessageDigest.getInstance(SHA1_DIGEST); \n byte[] buffer = new byte[4096];\n int bytes;\n while ( (bytes = in.read(buffer)) > 0) {\n md.update(buffer, 0, bytes);\n }\n return md.digest();\n }\n catch(NoSuchAlgorithmException | IOException e) {\n throw new InternalErrorException(e);\n }\n }"
] |
[
"def create_response_pdu(self, data):\n \n log.debug('Create single bit response pdu {0}.'.format(data))\n bytes_ = [data[i:i + 8] for i in range(0, len(data), 8)]\n\n # Reduce each all bits per byte to a number. Byte\n # [0, 0, 0, 0, 0, 1, 1, 1] is intepreted as binary en is decimal 3.\n for index, byte in enumerate(bytes_):\n bytes_[index] = \\\n reduce(lambda a, b: (a << 1) + b, list(reversed(byte)))\n\n log.debug('Reduced single bit data to {0}.'.format(bytes_))\n # The first 2 B's of the format encode the function code (1 byte) and\n # the length (1 byte) of the following byte series. Followed by # a B\n # for every byte in the series of bytes. 3 lead to the format '>BBB'\n # and 257 lead to the format '>BBBB'.\n fmt = '>BB' + self.format_character * len(bytes_)\n return struct.pack(fmt, self.function_code, len(bytes_), *bytes_)"
] |
codesearchnet
|
{
"query": "Represent the text about programming:",
"pos": "Represent the code about programming:",
"neg": "Represent the code about Software development:"
}
|
// SplitFullName splits a name and returns the firstname, lastname
|
[
"func SplitFullName(fullName string) (string, string) {\n\tnameComponents := strings.Split(fullName, \" \")\n\tfirstName := nameComponents[0]\n\tlastName := \"\"\n\tif len(nameComponents) > 1 {\n\t\tlastName = strings.Join(nameComponents[1:], \" \")\n\t}\n\treturn firstName, lastName\n}"
] |
[
"def get_sphinx_ref(self, url, label=None):\n \n\n # Raise an exception if the initial part of url does not match\n # the base url for this object\n n = len(self.baseurl)\n if url[0:n] != self.baseurl:\n raise KeyError('base of url %s does not match base url %s' %\n (url, self.baseurl))\n # The reverse lookup key is either the full url or the postfix\n # to the base url, depending on flag addbase\n if self.addbase:\n pstfx = url[n:]\n else:\n pstfx = url\n\n # Look up the cross-reference role and referenced object\n # name via the postfix to the base url\n role, name = self.revinv[pstfx]\n\n # If the label string is provided and is shorter than the name\n # string we have lookup up, assume it is a partial name for\n # the same object: append a '.' at the front and use it as the\n # object name in the cross-reference\n if label is not None and len(label) < len(name):\n name = '.' + label\n\n # Construct cross-reference\n ref = ':%s:`%s`' % (role, name)\n return ref"
] |
codesearchnet
|
{
"query": "Represent the post:",
"pos": "Represent the code:",
"neg": "Represent the code:"
}
|
Sets the WHERE param to the query.
@param int|array $where WHERE param.
@param QueryBuilder $query Query to build.
@param string $primaryKey Table primary key.
@return QueryBuilder Query object.
|
[
"private static function _setWhere($where, QueryBuilder $query, string $primaryKey = \"id\") : QueryBuilder\n {\n if(!is_array($where)) {\n return $query->where([\n $primaryKey => $where\n ]);\n }\n\n $columns = $where;\n\n unset($columns[\"ORDER BY\"]);\n unset($columns[\"LIMIT\"]);\n unset($columns[\"OFFSET\"]);\n\n if(!empty($columns)) {\n $query->where($columns);\n }\n\n if(isset($where[\"ORDER BY\"])) {\n $order = $where[\"ORDER BY\"];\n if(!is_array($order)) {\n $order = [$order];\n }\n\n $query->order(... $order);\n }\n if(isset($where[\"LIMIT\"])) {\n $limit = $where[\"LIMIT\"];\n if(!is_array($limit)) {\n $limit = [$limit];\n }\n\n $query->limit(... $limit);\n }\n if(isset($where[\"OFFSET\"])) {\n $query->offset($where[\"OFFSET\"]);\n }\n\n return $query;\n }"
] |
[
"public function beforeGetFinalisedQuery(DataQuery $dataQuery, $queriedColumns = [], SQLSelect $sqlSelect)\n {\n // Get metadata and SQL from join table\n $hasManyRelation = $this->getParentRelationship($dataQuery);\n $joinTableSQLSelect = $hasManyRelation->dataQuery()->query();\n $joinTableSQL = $joinTableSQLSelect->sql($joinTableParameters);\n $joinTableColumns = array_keys($joinTableSQLSelect->getSelect()); // Get aliases (keys) only\n $joinTableAlias = $this->getJoinAlias();\n\n // Get fields to join on\n $localKey = $this->getLocalKey();\n $schema = DataObject::getSchema();\n $baseTable = $schema->baseDataClass($dataQuery->dataClass());\n $childField = $schema->sqlColumnForField($baseTable, 'ID');\n\n // Add select fields\n foreach ($joinTableColumns as $joinTableColumn) {\n $sqlSelect->selectField(\n \"\\\"{$joinTableAlias}\\\".\\\"{$joinTableColumn}\\\"\",\n \"{$joinTableAlias}_{$joinTableColumn}\"\n );\n }\n\n // Apply join and record sql for later insertion (at end of replacements)\n // By using a string placeholder $$_SUBQUERY_$$ we protect field/table rewrites from interfering twice\n // on the already-finalised inner list\n $sqlSelect->addInnerJoin(\n '(SELECT $$_SUBQUERY_$$)',\n \"\\\"{$joinTableAlias}\\\".\\\"{$localKey}\\\" = {$childField}\",\n $joinTableAlias,\n 20,\n $joinTableParameters\n );\n $dataQuery->setQueryParam('Foreign.JoinTableSQL', $joinTableSQL);\n\n // After this join, and prior to afterGetFinalisedQuery, $sqlSelect will be populated with the\n // necessary sql rewrites (versioned, etc) that effect the base table.\n // By using a placeholder for the subquery we can protect the subquery (already rewritten)\n // from being re-written a second time. However we DO want the join predicate (above) to be rewritten.\n // See http://php.net/manual/en/function.str-replace.php#refsect1-function.str-replace-notes\n // for the reason we only add the final substitution at the end of getFinalisedQuery()\n }"
] |
codesearchnet
|
{
"query": "Represent the Github instruction about Software development:",
"pos": "Represent the Github code about Software development:",
"neg": "Represent the Github code about Software development:"
}
|
Create an enum config
:param enum_type:
:param help_string:
:param default:
:return:
|
[
"def create_enum(enum_type, help_string=NO_HELP, default=NO_DEFAULT):\n # type: (Type[Enum], str, Union[Any, NO_DEFAULT_TYPE]) -> Type[Enum]\n \n # noinspection PyTypeChecker\n return ParamEnum(\n help_string=help_string,\n default=default,\n enum_type=enum_type,\n )"
] |
[
"def __store_config(self, args, kwargs):\n \n signature = (\n 'schema',\n 'ignore_none_values',\n 'allow_unknown',\n 'require_all',\n 'purge_unknown',\n 'purge_readonly',\n )\n for i, p in enumerate(signature[: len(args)]):\n if p in kwargs:\n raise TypeError(\"__init__ got multiple values for argument \" \"'%s'\" % p)\n else:\n kwargs[p] = args[i]\n self._config = kwargs\n \"\"\" This dictionary holds the configuration arguments that were used to\n initialize the :class:`Validator` instance except the\n ``error_handler``. \"\"\""
] |
codesearchnet
|
{
"query": "Represent the Github description about Software Development:",
"pos": "Represent the Github code about Software Development:",
"neg": "Represent the Github code about Programming:"
}
|
e
@param {String} label the label of the async task
@required @param {Any} gen the object to yield
@return {Function} trunked function
|
[
"function e(label, gen) {\n if (!gen) {\n gen = label;\n label = '';\n }\n\n if (!enabled) {\n return gen;\n }\n\n var hackErr = new Error('hack');\n hackErr.label = label;\n\n return function *() {\n try {\n return yield gen;\n } catch(err) {\n throw buildError(err, hackErr);\n }\n };\n}"
] |
[
"function transformer (selection) {\n const type = quantum.isSelection(selection) ? selection.type() : undefined\n const entityTransform = transformMap[type] || defaultTransform\n return entityTransform(selection, transformer, meta) // bootstrap to itself to make the transformer accessible to children\n }"
] |
codesearchnet
|
{
"query": "Represent the description about Programming:",
"pos": "Represent the code about Programming:",
"neg": "Represent the code:"
}
|
Add faxes.
@param \Sulu\Bundle\ContactBundle\Entity\Fax $faxes
@return FaxType
|
[
"public function addFaxe(\\Sulu\\Bundle\\ContactBundle\\Entity\\Fax $faxes)\n {\n $this->faxes[] = $faxes;\n\n return $this;\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 post about Programming:",
"pos": "Represent the code about Programming:",
"neg": "Represent the code about Software development:"
}
|
Lists the views this connection has.
@return View[]
|
[
"public function listViews()\n {\n $database = $this->_conn->getDatabase();\n $sql = $this->_platform->getListViewsSQL($database);\n $views = $this->_conn->fetchAll($sql);\n\n return $this->_getPortableViewsList($views);\n }"
] |
[
"@Override\n\tpublic void validateSetup(Server server, Query query) throws ValidationException {\n\t\tlogger.info(\"Starting Stackdriver writer connected to '{}', proxy {} ...\", gatewayUrl, proxy);\n\t}"
] |
codesearchnet
|
{
"query": "Represent the Github description about Software development:",
"pos": "Represent the Github code about Software development:",
"neg": "Represent the Github code about Programming:"
}
|
Block a user.
Returns a `relationship dict`_ containing the updated relationship to the user.
|
[
"def account_block(self, id):\n \n id = self.__unpack_id(id)\n url = '/api/v1/accounts/{0}/block'.format(str(id))\n return self.__api_request('POST', url)"
] |
[
"def build(self, **kwargs):\n \n build_args = dict(self.where_query)\n build_args.update(kwargs)\n record = self.model(**record_args(build_args))\n if self.join_args:\n # EXAMPLE:\n # Say we have a many-to-many relation like so:\n # Post -> Tagging -> Tag\n # If we are adding a tag to a post, we need to create the tagging\n # in addition to the tag. To do this, we add a \"related record\" to\n # the tag which is the tagging. By building the previous record,\n # if it exists, we can recursively build a long object tree.\n # That is, when we do post.tags(), we get a query that looks like:\n # Query(Tag).joins(\"taggings\").where(taggings={\"post_id\":post.id})\n # The call to \"build\" then creates a tag using kwargs and the where\n # constraint, and creates a tagging that looks like:\n # Tagging(post_id = post.id) and adds it to the tag's related\n # records. The tagging's tag_id is added once the tag is saved\n # which is the first time it gets an id\n # Join args will never have just one element\n next_to_build = getattr(self.record, self.join_args[-2]['table']).build()\n record._related_records.append(next_to_build)\n return record"
] |
codesearchnet
|
{
"query": "Represent the Github description about programming:",
"pos": "Represent the Github code about programming:",
"neg": "Represent the Github code:"
}
|
// MysqlAddr returns hostname:mysql port.
|
[
"func (ti *TabletInfo) MysqlAddr() string {\n\treturn netutil.JoinHostPort(topoproto.MysqlHostname(ti.Tablet), topoproto.MysqlPort(ti.Tablet))\n}"
] |
[
"@Override\n\tpublic void validateSetup(Server server, Query query) throws ValidationException {\n\t\tlogger.info(\"Starting Stackdriver writer connected to '{}', proxy {} ...\", gatewayUrl, proxy);\n\t}"
] |
codesearchnet
|
{
"query": "Represent the Github summarization about Computer Science:",
"pos": "Represent the Github code about Computer Science:",
"neg": "Represent the Github code about Programming:"
}
|
// Custom marshaller to add the resourceType property, as required by the specification
|
[
"func (resource *AppointmentResponse) MarshalJSON() ([]byte, error) {\n\tresource.ResourceType = \"AppointmentResponse\"\n\t// Dereferencing the pointer to avoid infinite recursion.\n\t// Passing in plain old x (a pointer to AppointmentResponse), would cause this same\n\t// MarshallJSON function to be called again\n\treturn json.Marshal(*resource)\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 text about programming:",
"pos": "Represent the code about programming:",
"neg": "Represent the code about Software development:"
}
|
Check the user has configured API version correctly.
|
[
"def check_stripe_api_version(app_configs=None, **kwargs):\n\t\"\"\"\"\"\"\n\tfrom . import settings as djstripe_settings\n\n\tmessages = []\n\tdefault_version = djstripe_settings.DEFAULT_STRIPE_API_VERSION\n\tversion = djstripe_settings.get_stripe_api_version()\n\n\tif not validate_stripe_api_version(version):\n\t\tmsg = \"Invalid Stripe API version: {}\".format(version)\n\t\thint = \"STRIPE_API_VERSION should be formatted as: YYYY-MM-DD\"\n\t\tmessages.append(checks.Critical(msg, hint=hint, id=\"djstripe.C004\"))\n\n\tif version != default_version:\n\t\tmsg = (\n\t\t\t\"The Stripe API version has a non-default value of '{}'. \"\n\t\t\t\"Non-default versions are not explicitly supported, and may \"\n\t\t\t\"cause compatibility issues.\".format(version)\n\t\t)\n\t\thint = \"Use the dj-stripe default for Stripe API version: {}\".format(default_version)\n\t\tmessages.append(checks.Warning(msg, hint=hint, id=\"djstripe.W001\"))\n\n\treturn messages"
] |
[
"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 instruction:",
"pos": "Represent the Github code:",
"neg": "Represent the Github code:"
}
|
Resumes all the worker threads.
|
[
"def resume(self):\n \n for child in chain(self.consumers.values(), self.workers):\n child.resume()"
] |
[
"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:"
}
|
boolean response if a message contains correct information to serialize
:param msg: <proto object>
:param raise_err: <bool>
:return: <bool>
|
[
"def successfuly_encodes(msg, raise_err=False):\n \n result = True\n try:\n msg.SerializeToString()\n except EncodeError as encode_error:\n if raise_err:\n raise encode_error\n result = False\n return result"
] |
[
"def send_put(self, mri, attribute_name, value):\n \n path = attribute_name + \".value\"\n typ, value = convert_to_type_tuple_value(serialize_object(value))\n if isinstance(typ, tuple):\n # Structure, make into a Value\n _, typeid, fields = typ\n value = Value(Type(fields, typeid), value)\n try:\n self._ctxt.put(mri, {path: value}, path)\n except RemoteError:\n if attribute_name == \"exports\":\n # TODO: use a tag instead of a name\n # This will change the structure of the block\n # Wait for reconnect\n self._queues[mri].get(timeout=DEFAULT_TIMEOUT)\n else:\n # Not expected, raise\n raise"
] |
codesearchnet
|
{
"query": "Represent the post about Software development:",
"pos": "Represent the code about Software development:",
"neg": "Represent the code about programming:"
}
|
Convert co-ordinate values to floats.
|
[
"def floatize(self):\n \"\"\"\"\"\"\n self.x = float(self.x)\n self.y = float(self.y)"
] |
[
"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 text about Computer Science:",
"pos": "Represent the Github code about Computer Science:",
"neg": "Represent the Github code:"
}
|
Get the route to the error page
@param ServerRequestInterface $request
@param ResponseInterface $response
@return Router\Route
|
[
"protected function getErrorRoute(ServerRequestInterface $request, ResponseInterface $response)\n {\n if (\n interface_exists('Jasny\\HttpMessage\\GlobalEnvironmentInterface') &&\n $request instanceof GlobalEnvironmentInterface\n ) {\n $request = $request->withoutGlobalEnvironment();\n }\n \n $status = $response->getStatusCode();\n \n $errorUri = $request->getUri()\n ->withPath($status)\n ->withQuery(null)\n ->withFragment(null);\n \n return $this->router->getRoutes()->getRoute($request->withUri($errorUri));\n }"
] |
[
"public function run()\n {\n $this->loadMiddleware();\n\n //~ Default response\n $response = new HttpMessage\\Response();\n //$response->getBody()->write('-- static --');\n\n //~ Get response\n $stack = new HttpMiddleware\\Stack($response, $this->middleware);\n $response = $stack->process(HttpMessage\\ServerRequest::createFromGlobal());\n\n //~ Send response\n (new HttpMessage\\ResponseSender($response))->send();\n }"
] |
codesearchnet
|
{
"query": "Represent the description about Software development:",
"pos": "Represent the code about Software development:",
"neg": "Represent the code:"
}
|
Returns a copy of this LocalTime with the nano-of-second value altered.
@param int $nano The new nano-of-second.
@return LocalTime
@throws DateTimeException If the nano-of-second if not valid.
|
[
"public function withNano(int $nano) : LocalTime\n {\n if ($nano === $this->nano) {\n return $this;\n }\n\n Field\\NanoOfSecond::check($nano);\n\n return new LocalTime($this->hour, $this->minute, $this->second, $nano);\n }"
] |
[
"@Override\n\tpublic Date readDate() {\n\t\t/*\n\t\t * Date: 0x0B T7 T6 .. T0 Z1 Z2 T7 to T0 form a 64 bit Big Endian number\n\t\t * that specifies the number of nanoseconds that have passed since\n\t\t * 1/1/1970 0:00 to the specified time. This format is UTC 1970. Z1 an\n\t\t * Z0 for a 16 bit Big Endian number indicating the indicated time's\n\t\t * timezone in minutes.\n\t\t */\n\t\tlong ms = (long) buf.getDouble();\n\t\t// The timezone can be ignored as the date always is encoded in UTC\n\t\t@SuppressWarnings(\"unused\")\n\t\tshort timeZoneMins = buf.getShort();\n\t\tDate date = new Date(ms);\n\t\tstoreReference(date);\n\t\treturn date;\n\t}"
] |
codesearchnet
|
{
"query": "Represent the text about programming:",
"pos": "Represent the code about programming:",
"neg": "Represent the code about programming:"
}
|
Internal method to validate the local part of the email address
@return boolean
|
[
"private function _validateLocalPart()\n {\n // First try to match the local part on the common dot-atom format\n $result = false;\n\n // Dot-atom characters are: 1*atext *(\".\" 1*atext)\n // atext: ALPHA / DIGIT / and \"!\", \"#\", \"$\", \"%\", \"&\", \"'\", \"*\",\n // \"+\", \"-\", \"/\", \"=\", \"?\", \"^\", \"_\", \"`\", \"{\", \"|\", \"}\", \"~\"\n $atext = 'a-zA-Z0-9\\x21\\x23\\x24\\x25\\x26\\x27\\x2a\\x2b\\x2d\\x2f\\x3d\\x3f\\x5e\\x5f\\x60\\x7b\\x7c\\x7d\\x7e';\n if (preg_match('/^[' . $atext . ']+(\\x2e+[' . $atext . ']+)*$/', $this->_localPart)) {\n $result = true;\n } else {\n // Try quoted string format\n\n // Quoted-string characters are: DQUOTE *([FWS] qtext/quoted-pair) [FWS] DQUOTE\n // qtext: Non white space controls, and the rest of the US-ASCII characters not\n // including \"\\\" or the quote character\n $noWsCtl = '\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f';\n $qtext = $noWsCtl . '\\x21\\x23-\\x5b\\x5d-\\x7e';\n $ws = '\\x20\\x09';\n if (preg_match('/^\\x22([' . $ws . $qtext . '])*[$ws]?\\x22$/', $this->_localPart)) {\n $result = true;\n } else {\n $this->_error(self::DOT_ATOM);\n $this->_error(self::QUOTED_STRING);\n $this->_error(self::INVALID_LOCAL_PART);\n }\n }\n\n return $result;\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 Github description about programming:",
"pos": "Represent the Github code about programming:",
"neg": "Represent the Github code:"
}
|
Returns all RDF types (classes) of a given resource.
@return array
|
[
"public function getClasses(): array {\n $this->loadMetadata();\n $ret = array();\n foreach ($this->metadata->allResources('http://www.w3.org/1999/02/22-rdf-syntax-ns#type') as $i) {\n $ret[] = $i->getUri();\n }\n return $ret;\n }"
] |
[
"def _get_generic_schema(self):\n \n schema = Schema(\n vid=ID(stored=True, unique=True), # Object id\n title=NGRAMWORDS(),\n keywords=KEYWORD, # Lists of coverage identifiers, ISO time values and GVIDs, source names, source abbrev\n doc=TEXT) # Generated document for the core of the topic search\n return schema"
] |
codesearchnet
|
{
"query": "Represent the Github post about database:",
"pos": "Represent the Github code about database:",
"neg": "Represent the Github code:"
}
|
Set closed date from this issue
@param [Hash] event
@param [Hash] issue
|
[
"def set_date_from_event(event, issue)\n if event[\"commit_id\"].nil?\n issue[\"actual_date\"] = issue[\"closed_at\"]\n else\n begin\n commit = @fetcher.fetch_commit(event[\"commit_id\"])\n issue[\"actual_date\"] = commit[\"commit\"][\"author\"][\"date\"]\n\n # issue['actual_date'] = commit['author']['date']\n rescue StandardError\n puts \"Warning: Can't fetch commit #{event['commit_id']}. It is probably referenced from another repo.\"\n issue[\"actual_date\"] = issue[\"closed_at\"]\n end\n end\n end"
] |
[
"function make_event(event, target) {\n return string_p(event)? Event.make(event, target)\n : /* otherwise */ event }"
] |
codesearchnet
|
{
"query": "Represent the text about Software development:",
"pos": "Represent the code about Software development:",
"neg": "Represent the code:"
}
|
// SetUserName sets the UserName field's value.
|
[
"func (s *DescribeUserStackAssociationsInput) SetUserName(v string) *DescribeUserStackAssociationsInput {\n\ts.UserName = &v\n\treturn s\n}"
] |
[
"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 text about Software development:",
"pos": "Represent the code about Software development:",
"neg": "Represent the code about programming:"
}
|
/* insert line breaks into first-pass tokenized data
|
[
"function breakLines(tokens, maxWidth) {\n if (!maxWidth) {\n maxWidth = Infinity;\n }\n let i = 0;\n let lineLength = 0;\n let lastTokenWithSpace = -1;\n while (i < tokens.length) { /* take all text tokens, remove space, apply linebreaks */\n let token = tokens[i];\n if (token.type == TYPE_NEWLINE) { /* reset */\n lineLength = 0;\n lastTokenWithSpace = -1;\n }\n if (token.type != TYPE_TEXT) { /* skip non-text tokens */\n i++;\n continue;\n }\n /* remove spaces at the beginning of line */\n while (lineLength == 0 && token.value.charAt(0) == \" \") {\n token.value = token.value.substring(1);\n }\n /* forced newline? insert two new tokens after this one */\n let index = token.value.indexOf(\"\\n\");\n if (index != -1) {\n token.value = breakInsideToken(tokens, i, index, true);\n /* if there are spaces at the end, we must remove them (we do not want the line too long) */\n let arr = token.value.split(\"\");\n while (arr.length && arr[arr.length - 1] == \" \") {\n arr.pop();\n }\n token.value = arr.join(\"\");\n }\n /* token degenerated? */\n if (!token.value.length) {\n tokens.splice(i, 1);\n continue;\n }\n if (lineLength + token.value.length > maxWidth) { /* line too long, find a suitable breaking spot */\n /* is it possible to break within this token? */\n let index = -1;\n while (1) {\n let nextIndex = token.value.indexOf(\" \", index + 1);\n if (nextIndex == -1) {\n break;\n }\n if (lineLength + nextIndex > maxWidth) {\n break;\n }\n index = nextIndex;\n }\n if (index != -1) { /* break at space within this one */\n token.value = breakInsideToken(tokens, i, index, true);\n }\n else if (lastTokenWithSpace != -1) { /* is there a previous token where a break can occur? */\n let token = tokens[lastTokenWithSpace];\n let breakIndex = token.value.lastIndexOf(\" \");\n token.value = breakInsideToken(tokens, lastTokenWithSpace, breakIndex, true);\n i = lastTokenWithSpace;\n }\n else { /* force break in this token */\n token.value = breakInsideToken(tokens, i, maxWidth - lineLength, false);\n }\n }\n else { /* line not long, continue */\n lineLength += token.value.length;\n if (token.value.indexOf(\" \") != -1) {\n lastTokenWithSpace = i;\n }\n }\n i++; /* advance to next token */\n }\n tokens.push({ type: TYPE_NEWLINE }); /* insert fake newline to fix the last text line */\n /* remove trailing space from text tokens before newlines */\n let lastTextToken = null;\n for (let i = 0; i < tokens.length; i++) {\n let token = tokens[i];\n switch (token.type) {\n case TYPE_TEXT:\n lastTextToken = token;\n break;\n case TYPE_NEWLINE:\n if (lastTextToken) { /* remove trailing space */\n let arr = lastTextToken.value.split(\"\");\n while (arr.length && arr[arr.length - 1] == \" \") {\n arr.pop();\n }\n lastTextToken.value = arr.join(\"\");\n }\n lastTextToken = null;\n break;\n }\n }\n tokens.pop(); /* remove fake token */\n return tokens;\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 sentence:",
"pos": "Represent the code:",
"neg": "Represent the code:"
}
|
Gets the member attribute.
@return Member|null The member attribute.
|
[
"public function getMemberAttribute()\n {\n $guild = $this->discord->guilds->get('id', $this->guild_id);\n\n return $guild->members->get('id', $this->user_id);\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 sentence about Programming:",
"pos": "Represent the code about Programming:",
"neg": "Represent the code about Software development:"
}
|
Given supplied arguments, find a contained
subcommand
@param array $args
@return \WP_CLI\Dispatcher\Subcommand|false
|
[
"public function find_subcommand( &$args ) {\n\t\t$name = array_shift( $args );\n\n\t\t$subcommands = $this->get_subcommands();\n\n\t\tif ( ! isset( $subcommands[ $name ] ) ) {\n\t\t\t$aliases = self::get_aliases( $subcommands );\n\n\t\t\tif ( isset( $aliases[ $name ] ) ) {\n\t\t\t\t$name = $aliases[ $name ];\n\t\t\t}\n\t\t}\n\n\t\tif ( ! isset( $subcommands[ $name ] ) ) {\n\t\t\treturn false;\n\t\t}\n\n\t\treturn $subcommands[ $name ];\n\t}"
] |
[
"final public static function sinfo(array $params):string\n {\n return (\\iumioFramework\\Core\\Base\\Server\\GlobalServer::getServerInfo($params['name']));\n }"
] |
codesearchnet
|
{
"query": "Represent the post about Software development:",
"pos": "Represent the code about Software development:",
"neg": "Represent the code about programming:"
}
|
Handles rolling back to a selected version on save.
@param int $version
|
[
"public function savePreviousVersion($version)\n {\n if (!is_numeric($version)) {\n return;\n }\n\n try {\n $this->setVersionNumber($version);\n $this->owner->write();\n } catch (Exception $e) {\n throw new ValidationException(new ValidationResult(\n false,\n \"Could not replace file #{$this->owner->ID} with version #$version.\"\n ));\n }\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 sentence about Database management:",
"pos": "Represent the Github code about Database management:",
"neg": "Represent the Github code:"
}
|
Initializes the options for the object.
Called from {@link __construct()} as a first step of object instantiation.
@param object An optional AnConfig object with configuration options.
|
[
"protected function _initialize(AnConfig $config)\n {\n $config->append(array(\n 'name' => 'google',\n 'version' => '3',\n 'url' => 'https://maps.googleapis.com/maps/api/geocode/json?',\n 'key' => get_config_value('locations.api_key', null)\n ));\n\n parent::_initialize($config);\n }"
] |
[
"protected Expression instantiate(Object oldInstance, Encoder out)\n {\n //\n // An implementation instance is actually constructed at decode time by calling\n // ControlBean.ensureControl on the parent bean. This will create a new impl\n // instance and run the impl initializer on it.\n //\n return new Expression(((XMLEncoder)out).getOwner(), \"ensureControl\", null);\n }"
] |
codesearchnet
|
{
"query": "Represent the Github sentence about Software development:",
"pos": "Represent the Github code about Software development:",
"neg": "Represent the Github code:"
}
|
Adds the given component as a child of this component. The tag is used to identify the child in a velocity
template.
@param component the component to add.
@param tag the tag used to identify the component.
@deprecated Use {@link WTemplate} instead.
|
[
"@Deprecated\n\tvoid add(final WComponent component, final String tag) {\n\t\tadd(component);\n\t\tcomponent.setTag(tag);\n\t}"
] |
[
"function WidgetDef(config, endFunc, out) {\n this.type = config.type; // The widget module type name that is passed to the factory\n this.id = config.id; // The unique ID of the widget\n this.config = config.config; // Widget config object (may be null)\n this.state = config.state; // Widget state object (may be null)\n this.scope = config.scope; // The ID of the widget that this widget is scoped within\n this.domEvents = null; // An array of DOM events that need to be added (in sets of three)\n this.customEvents = config.customEvents; // An array containing information about custom events\n this.bodyElId = config.bodyElId; // The ID for the default body element (if any any)\n this.children = []; // An array of nested WidgetDef instances\n this.end = endFunc; // A function that when called will pop this widget def off the stack\n this.extend = config.extend; // Information about other widgets that extend this widget.\n this.out = out; // The AsyncWriter that this widget is associated with\n this.hasDomEvents = config.hasDomEvents; // A flag to indicate if this widget has any\n // listeners for non-bubbling DOM events\n this._nextId = 0; // The unique integer to use for the next scoped ID\n}"
] |
codesearchnet
|
{
"query": "Represent the summarization about Software development:",
"pos": "Represent the code about Software development:",
"neg": "Represent the code:"
}
|
read a file and inject a string of swagger (str, str) -> null
|
[
"function useMain (mdFile, swagger) {\n const mainOpts = {\n position: argv.position,\n title: argv.title\n }\n opts.yaml ? mainOpts.yaml = true : mainOpts.json = true\n\n fs.readFile(mdFile, { encoding: 'utf8' }, function (err, md) {\n assert.ifError(err)\n const compiled = remark()\n .use(main(swagger, mainOpts))\n .process(md)\n\n const rs = fromString(compiled)\n const ws = argv.w ? fs.createWriteStream(mdFile) : stdout\n pump(rs, ws, handleErr)\n })\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 Github comment:",
"pos": "Represent the Github code:",
"neg": "Represent the Github code:"
}
|
{@inheritdoc}
@see Knp\Menu.MenuItem::addChild()
Our menu items created by menu factory and $child always MenuItemInterface.
Factory sets current uri and other variable parts of menu item options
We don't need to set it here
|
[
"public function addChild($child, array $options = array())\n {\n $child->setParent($this);\n\n $this->children[$child->getName()] = $child;\n\n return $child;\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 post about programming:",
"pos": "Represent the code about programming:",
"neg": "Represent the code about programming:"
}
|
Get a default db value, if any is available
@return ConnectionInterface|null A default db value or Null if no default value is available
|
[
"public function getDefaultDb(): ?ConnectionInterface\n {\n // By default, the DB Facade does not return the\n // any actual database connection, but rather an\n // instance of \\Illuminate\\Database\\DatabaseManager.\n // Therefore, we make sure only to obtain its\n // \"connection\", to make sure that its only the connection\n // instance that we obtain.\n $manager = DB::getFacadeRoot();\n if (isset($manager)) {\n return $manager->connection();\n }\n return $manager;\n }"
] |
[
"private function getColumnFromName($name)\n {\n foreach ($this->columnConfiguration as $i => $col) {\n if ($col->getName() == $name) {\n return $col;\n }\n }\n\n // This exception should never happen. If it does, something is\n // wrong w/ the relationship between searchable columns and the\n // configuration.\n throw new DatatableException(\"A requested column was not found in the columnConfiguration.\");\n }"
] |
codesearchnet
|
{
"query": "Represent the Github text about Software Development:",
"pos": "Represent the Github code about Software Development:",
"neg": "Represent the Github code about Software development:"
}
|
Loads source HTML into memory, either from $source string or a file.
@param string $source HTML content
@param bool $from_file Indicates $source is a file to pull content from
|
[
"public function set_html($source, $from_file = false)\n {\n if ($from_file && file_exists($source)) {\n $this->html = file_get_contents($source);\n } else {\n $this->html = $source;\n }\n\n $this->_converted = false;\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 text about Programming:",
"pos": "Represent the Github code about Programming:",
"neg": "Represent the Github code about programming:"
}
|
文字列のダイアクリティカルマークや囲みを外します。
@param string $input
@return string
|
[
"protected static function deleteMarks(string $input): string\n {\n return preg_replace(\n '/\\\\p{M}+/u',\n '',\n \\Normalizer::normalize($input, \\Normalizer::FORM_KD)\n );\n }"
] |
[
"func (m *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\t// NOTE ucon内部のルーティングは一元的にこの関数から行う\n\t// Handlerを細分化しhttp.ServeMuxに登録すると、OPTIONSのhandleがうまくできなくなる\n\t// このため、Handlerはucon全体で1つとし、OPTIONSも通常のMethodと同じようにHandlerを設定し利用する\n\t// OPTIONSを適切にhandleするため、全てのHandlerに特殊なHookを入れるよりマシである\n\n\tm.router.ServeHTTP(w, r)\n}"
] |
codesearchnet
|
{
"query": "Represent the instruction about programming:",
"pos": "Represent the code about programming:",
"neg": "Represent the code about Software development:"
}
|
Update components.
|
[
"def command_update(prog_name, prof_mgr, prof_name, prog_args):\n\n\t\n\t\n\t# Retrieve arguments\n\tparser = argparse.ArgumentParser(\n\t\tprog=prog_name\n\t)\n\tparser.add_argument(\n\t\t\"components\",\n\t\tmetavar=\"comps\",\n\t\tnargs=argparse.REMAINDER,\n\t\thelp=\"system components\"\n\t)\n\targs = parser.parse_args(prog_args)\n\t\n\t# Profile load\n\tprof_stub = prof_mgr.load(prof_name)\n\t\n\t# Collect component stubs\n\tcomp_stubs = []\n\tif len(args.components) == 0:\n\t\traise Exception(\"Empty component list\")\n\tfor comp_name in args.components:\n\t\tcomp_stub = prof_stub.component(comp_name)\n\t\tcomponent_exists(prof_stub, comp_stub)\n\t\tcomp_stubs.append(comp_stub)\n\t\t\n\tcontext = prof_stub.context()\n\t\n\t# Create delete plan\n\tplan = []\n\tfor comp_stub in comp_stubs:\n\t\tcomp_stub.delete(context, plan)\n\t\t\n\t# Execute delete plan\n\tfor op in plan:\n\t\toperation_execute(op, context)\n\t\t\n\t# Update component stub list\n\tfor op in plan:\n\t\tcomp_stub = prof_stub.component(op.name())\n\t\tif comp_stub not in comp_stubs:\n\t\t\tcomp_stubs.append(comp_stub)\n\t\n\t# Create insert plan\n\tplan = []\n\tfor comp_stub in comp_stubs:\n\t\tcomp_stub.insert(context, plan)\n\t\t\n\t# Execute insert plan\n\tfor op in plan:\n\t\toperation_execute(op, context)"
] |
[
"def :\n \"\"\"\"\"\"\n CheckParent(self)\n\n return _fitz.Annot_"
] |
codesearchnet
|
{
"query": "Represent the description:",
"pos": "Represent the code:",
"neg": "Represent the code:"
}
|
@param string $input
@param int $length
@param string $string
@param int $type
@return string
|
[
"public static function pad(string $input, int $length, string $string = ' ', int $type = STR_PAD_RIGHT): string\n {\n $diff = strlen($input) - mb_strlen($input, 'utf-8');\n\n return str_pad($input, $length + $diff, $string, $type);\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 description about Programming:",
"pos": "Represent the code about Programming:",
"neg": "Represent the code about Programming:"
}
|
The system creates a new draft version as a copy from the current version.
@param mixed $contentId
@throws ForbiddenException if the current version is already a draft
@return \eZ\Publish\Core\REST\Server\Values\CreatedVersion
|
[
"public function createDraftFromCurrentVersion($contentId)\n {\n $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId);\n $contentType = $this->repository->getContentTypeService()->loadContentType($contentInfo->contentTypeId);\n $versionInfo = $this->repository->getContentService()->loadVersionInfo(\n $contentInfo\n );\n\n if ($versionInfo->isDraft()) {\n throw new ForbiddenException('Current version is already in status DRAFT');\n }\n\n $contentDraft = $this->repository->getContentService()->createContentDraft($contentInfo);\n\n return new Values\\CreatedVersion(\n array(\n 'version' => new Values\\Version(\n $contentDraft,\n $contentType,\n $this->repository->getContentService()->loadRelations($contentDraft->getVersionInfo())\n ),\n )\n );\n }"
] |
[
"protected function getLimitationByIdentifier($identifier)\n {\n switch ($identifier) {\n case APILimitation::CONTENTTYPE:\n return new \\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation\\ContentTypeLimitation();\n\n case APILimitation::LANGUAGE:\n return new \\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation\\LanguageLimitation();\n\n case APILimitation::LOCATION:\n return new \\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation\\LocationLimitation();\n\n case APILimitation::OWNER:\n return new \\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation\\OwnerLimitation();\n\n case APILimitation::PARENTOWNER:\n return new \\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation\\ParentOwnerLimitation();\n\n case APILimitation::PARENTCONTENTTYPE:\n return new \\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation\\ParentContentTypeLimitation();\n\n case APILimitation::PARENTDEPTH:\n return new \\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation\\ParentDepthLimitation();\n\n case APILimitation::SECTION:\n return new \\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation\\SectionLimitation();\n\n case APILimitation::SITEACCESS:\n return new \\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation\\SiteaccessLimitation();\n\n case APILimitation::STATE:\n return new \\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation\\ObjectStateLimitation();\n\n case APILimitation::SUBTREE:\n return new \\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation\\SubtreeLimitation();\n\n case APILimitation::USERGROUP:\n return new \\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation\\UserGroupLimitation();\n\n case APILimitation::PARENTUSERGROUP:\n return new \\eZ\\Publish\\API\\Repository\\Values\\User\\Limitation\\ParentUserGroupLimitation();\n\n default:\n throw new \\eZ\\Publish\\Core\\Base\\Exceptions\\NotFoundException('Limitation', $identifier);\n }\n }"
] |
codesearchnet
|
{
"query": "Represent the Github description:",
"pos": "Represent the Github code:",
"neg": "Represent the Github code about Programming:"
}
|
Set name
@throws \InvalidArgumentException if the name is empty
@param string $name Capability name
@return \RolesCapabilities\Capability
|
[
"public function setName(string $name): \\RolesCapabilities\\Capability\n {\n if (empty($name)) {\n throw new InvalidArgumentException(\"Name cannot be empty\");\n }\n $this->name = $name;\n\n return $this;\n }"
] |
[
"protected function initDefaultInitialContext()\n {\n\n // initialize the configuration values for the initial context\n $description = new DescriptionNode(new NodeValue('The initial context configuration.'));\n $storage = new StorageNode('AppserverIo\\Storage\\StackableStorage');\n\n // set the default initial context configuration\n $this->initialContext = new InitialContextNode('AppserverIo\\Appserver\\Core\\InitialContext', $description, $storage);\n }"
] |
codesearchnet
|
{
"query": "Represent the Github post about programming:",
"pos": "Represent the Github code about programming:",
"neg": "Represent the Github code about programming:"
}
|
// Receives a multi-part message.
|
[
"func (s *Socket) Recv() (parts [][]byte, err error) {\n\tparts = make([][]byte, 0)\n\tfor more := true; more; {\n\t\tvar part []byte\n\t\tif part, more, err = s.RecvPart(); err != nil {\n\t\t\treturn\n\t\t}\n\t\tparts = append(parts, part)\n\t}\n\treturn\n}"
] |
[
"def requests(self):\n ''''''\n path = pathjoin(self.path, self.name, Request.path)\n response = self.service.send(SRequest('GET', path))\n # a bin behaves as a push-down store --- better to return the requests\n # in order of appearance\n return list(reversed(Request.from_response(response, bin=self)))"
] |
codesearchnet
|
{
"query": "Represent the description about Messaging:",
"pos": "Represent the code about Messaging:",
"neg": "Represent the code:"
}
|
Prints alerts and updates the prompt any time the prompt is showing
|
[
"def _alerter_thread_func(self) -> None:\n \n\n self._alert_count = 0\n self._next_alert_time = 0\n\n while not self._stop_thread:\n # Always acquire terminal_lock before printing alerts or updating the prompt\n # To keep the app responsive, do not block on this call\n if self.terminal_lock.acquire(blocking=False):\n\n # Get any alerts that need to be printed\n alert_str = self._generate_alert_str()\n\n # Generate a new prompt\n new_prompt = self._generate_colored_prompt()\n\n # Check if we have alerts to print\n if alert_str:\n # new_prompt is an optional parameter to async_alert()\n self.async_alert(alert_str, new_prompt)\n new_title = \"Alerts Printed: {}\".format(self._alert_count)\n self.set_window_title(new_title)\n\n # No alerts needed to be printed, check if the prompt changed\n elif new_prompt != self.prompt:\n self.async_update_prompt(new_prompt)\n\n # Don't forget to release the lock\n self.terminal_lock.release()\n\n time.sleep(0.5)"
] |
[
"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 comment:",
"pos": "Represent the code:",
"neg": "Represent the code about Software development:"
}
|
// Warningf forwards to Logger.Warning
|
[
"func (l logf) Warningf(s string, args ...interface{}) {\n\tl.log.Warning(s, args...)\n}"
] |
[
"function make_event(event, target) {\n return string_p(event)? Event.make(event, target)\n : /* otherwise */ event }"
] |
codesearchnet
|
{
"query": "Represent the Github summarization about programming:",
"pos": "Represent the Github code about programming:",
"neg": "Represent the Github code:"
}
|
Build an instance of TodayInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.api.v2010.account.usage.record.today.TodayInstance
:rtype: twilio.rest.api.v2010.account.usage.record.today.TodayInstance
|
[
"def get_instance(self, payload):\n \n return TodayInstance(self._version, payload, account_sid=self._solution['account_sid'], )"
] |
[
"def last_month(self):\n \n if self._last_month is None:\n self._last_month = LastMonthList(self._version, account_sid=self._solution['account_sid'], )\n return self._last_month"
] |
codesearchnet
|
{
"query": "Represent the comment about Twilio:",
"pos": "Represent the code about Twilio:",
"neg": "Represent the code about Twilio:"
}
|
// SetAuthenticationToken sets the AuthenticationToken field's value.
|
[
"func (s *CreateUserInput) SetAuthenticationToken(v string) *CreateUserInput {\n\ts.AuthenticationToken = &v\n\treturn s\n}"
] |
[
"@Override\n public void setAttributes(final Map<String, List<Object>> attrs) {\n for (final Entry<String, List<Object>> attrEntry : attrs.entrySet()) {\n final String key = attrEntry.getKey();\n final List<Object> value = attrEntry.getValue();\n setAttribute(key, value);\n }\n /*\n * This is the method used by Authentication.authenticate() -- and\n * elsewhere -- to initialize a valid IPerson in the portal. We want\n * to *fail fast* if there's something wrong with that process.\n */\n validateUsername();\n }"
] |
codesearchnet
|
{
"query": "Represent the text about Programming:",
"pos": "Represent the code about Programming:",
"neg": "Represent the code about Software development:"
}
|
// Everything but the last element of the full type name, CamelCased.
// The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... .
|
[
"func (e *EnumDescriptor) prefix() string {\n\ttypeName := e.alias()\n\tif e.parent == nil {\n\t\t// If the enum is not part of a message, the prefix is just the type name.\n\t\treturn CamelCase(typeName[len(typeName)-1]) + \"_\"\n\t}\n\treturn CamelCaseSlice(typeName[0:len(typeName)-1]) + \"_\"\n}"
] |
[
"public LHS toLHS( CallStack callstack, Interpreter interpreter)\n throws EvalError\n {\n // loosely typed map expression new {a=1, b=2} are treated\n // as non assignment (LHS) to retrieve Map.Entry key values\n // then wrapped in a MAP_ENTRY type LHS for value assignment.\n return (LHS) eval( interpreter.getStrictJava() || !isMapExpression,\n callstack, interpreter );\n }"
] |
codesearchnet
|
{
"query": "Represent the comment about Programming:",
"pos": "Represent the code about Programming:",
"neg": "Represent the code:"
}
|
expects pages/:name/template.hbs
|
[
"function (id) {\n var o = this.options;\n return path.resolve(o.root, o.viewsDir, id, \"template\" + o.extension);\n }"
] |
[
"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 summarization:",
"pos": "Represent the code:",
"neg": "Represent the code:"
}
|
General power-of-2 base conversion.
|
[
"def convertbits(data, frombits, tobits, pad=True):\n \"\"\"\"\"\"\n acc = 0\n bits = 0\n ret = []\n maxv = (1 << tobits) - 1\n max_acc = (1 << (frombits + tobits - 1)) - 1\n for value in data:\n if value < 0 or (value >> frombits):\n return None\n acc = ((acc << frombits) | value) & max_acc\n bits += frombits\n while bits >= tobits:\n bits -= tobits\n ret.append((acc >> bits) & maxv)\n if pad:\n if bits:\n ret.append((acc << (tobits - bits)) & maxv)\n elif bits >= frombits or ((acc << (tobits - bits)) & maxv):\n return None\n return ret"
] |
[
"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 Github description:",
"pos": "Represent the Github code:",
"neg": "Represent the Github code:"
}
|
Adds new tag words.
@param string[] $allWords All words extracted from post
@throws Exception
|
[
"protected function addNewWords($allWords)\r\n {\r\n try {\r\n $newWords = $allWords;\r\n $query = (new Query())->from(Vocabulary::tableName())->where(['word' => $allWords]);\r\n foreach ($query->each() as $vocabularyFound) {\r\n if (($key = array_search($vocabularyFound['word'], $allWords)) !== false) {\r\n unset($newWords[$key]);\r\n }\r\n }\r\n $formatWords = [];\r\n foreach ($newWords as $word) {\r\n $formatWords[] = [$word];\r\n }\r\n if (!empty($formatWords)) {\r\n if (!Podium::getInstance()->db->createCommand()->batchInsert(\r\n Vocabulary::tableName(), ['word'], $formatWords\r\n )->execute()) {\r\n throw new Exception('Words saving error!');\r\n }\r\n }\r\n } catch (Exception $e) {\r\n Log::error($e->getMessage(), null, __METHOD__);\r\n throw $e;\r\n }\r\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 description about programming:",
"pos": "Represent the code about programming:",
"neg": "Represent the code:"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.