repository_name stringlengths 5 67 | func_path_in_repository stringlengths 4 234 | func_name stringlengths 0 314 | whole_func_string stringlengths 52 3.87M | language stringclasses 6
values | func_code_string stringlengths 52 3.87M | func_code_tokens listlengths 15 672k | func_documentation_string stringlengths 1 47.2k | func_documentation_tokens listlengths 1 3.92k | split_name stringclasses 1
value | func_code_url stringlengths 85 339 |
|---|---|---|---|---|---|---|---|---|---|---|
yii2mod/yii2-rbac | controllers/AssignmentController.php | AssignmentController.actionIndex | public function actionIndex()
{
/* @var AssignmentSearch */
$searchModel = Yii::createObject($this->searchClass);
if ($searchModel instanceof AssignmentSearch) {
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $this->userIdentityClass, $this->idField, $this->usernameField);
} else {
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
}
return $this->render('index', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
'gridViewColumns' => $this->gridViewColumns,
]);
} | php | public function actionIndex()
{
/* @var AssignmentSearch */
$searchModel = Yii::createObject($this->searchClass);
if ($searchModel instanceof AssignmentSearch) {
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $this->userIdentityClass, $this->idField, $this->usernameField);
} else {
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
}
return $this->render('index', [
'dataProvider' => $dataProvider,
'searchModel' => $searchModel,
'gridViewColumns' => $this->gridViewColumns,
]);
} | [
"public",
"function",
"actionIndex",
"(",
")",
"{",
"/* @var AssignmentSearch */",
"$",
"searchModel",
"=",
"Yii",
"::",
"createObject",
"(",
"$",
"this",
"->",
"searchClass",
")",
";",
"if",
"(",
"$",
"searchModel",
"instanceof",
"AssignmentSearch",
")",
"{",
... | List of all assignments
@return string | [
"List",
"of",
"all",
"assignments"
] | train | https://github.com/yii2mod/yii2-rbac/blob/6b98a04fc75bc82ccf87001959f496b283266a40/controllers/AssignmentController.php#L95-L111 |
yii2mod/yii2-rbac | controllers/AssignmentController.php | AssignmentController.actionView | public function actionView(int $id)
{
$model = $this->findModel($id);
return $this->render('view', [
'model' => $model,
'usernameField' => $this->usernameField,
]);
} | php | public function actionView(int $id)
{
$model = $this->findModel($id);
return $this->render('view', [
'model' => $model,
'usernameField' => $this->usernameField,
]);
} | [
"public",
"function",
"actionView",
"(",
"int",
"$",
"id",
")",
"{",
"$",
"model",
"=",
"$",
"this",
"->",
"findModel",
"(",
"$",
"id",
")",
";",
"return",
"$",
"this",
"->",
"render",
"(",
"'view'",
",",
"[",
"'model'",
"=>",
"$",
"model",
",",
... | Displays a single Assignment model.
@param int $id
@return mixed | [
"Displays",
"a",
"single",
"Assignment",
"model",
"."
] | train | https://github.com/yii2mod/yii2-rbac/blob/6b98a04fc75bc82ccf87001959f496b283266a40/controllers/AssignmentController.php#L120-L128 |
yii2mod/yii2-rbac | controllers/AssignmentController.php | AssignmentController.actionAssign | public function actionAssign(int $id)
{
$items = Yii::$app->getRequest()->post('items', []);
$assignmentModel = $this->findModel($id);
$assignmentModel->assign($items);
return $assignmentModel->getItems();
} | php | public function actionAssign(int $id)
{
$items = Yii::$app->getRequest()->post('items', []);
$assignmentModel = $this->findModel($id);
$assignmentModel->assign($items);
return $assignmentModel->getItems();
} | [
"public",
"function",
"actionAssign",
"(",
"int",
"$",
"id",
")",
"{",
"$",
"items",
"=",
"Yii",
"::",
"$",
"app",
"->",
"getRequest",
"(",
")",
"->",
"post",
"(",
"'items'",
",",
"[",
"]",
")",
";",
"$",
"assignmentModel",
"=",
"$",
"this",
"->",
... | Assign items
@param int $id
@return array | [
"Assign",
"items"
] | train | https://github.com/yii2mod/yii2-rbac/blob/6b98a04fc75bc82ccf87001959f496b283266a40/controllers/AssignmentController.php#L137-L144 |
yii2mod/yii2-rbac | controllers/AssignmentController.php | AssignmentController.actionRemove | public function actionRemove(int $id)
{
$items = Yii::$app->getRequest()->post('items', []);
$assignmentModel = $this->findModel($id);
$assignmentModel->revoke($items);
return $assignmentModel->getItems();
} | php | public function actionRemove(int $id)
{
$items = Yii::$app->getRequest()->post('items', []);
$assignmentModel = $this->findModel($id);
$assignmentModel->revoke($items);
return $assignmentModel->getItems();
} | [
"public",
"function",
"actionRemove",
"(",
"int",
"$",
"id",
")",
"{",
"$",
"items",
"=",
"Yii",
"::",
"$",
"app",
"->",
"getRequest",
"(",
")",
"->",
"post",
"(",
"'items'",
",",
"[",
"]",
")",
";",
"$",
"assignmentModel",
"=",
"$",
"this",
"->",
... | Remove items
@param int $id
@return array | [
"Remove",
"items"
] | train | https://github.com/yii2mod/yii2-rbac/blob/6b98a04fc75bc82ccf87001959f496b283266a40/controllers/AssignmentController.php#L153-L160 |
yii2mod/yii2-rbac | controllers/AssignmentController.php | AssignmentController.findModel | protected function findModel(int $id)
{
$class = $this->userIdentityClass;
if (($user = $class::findIdentity($id)) !== null) {
return new AssignmentModel($user);
}
throw new NotFoundHttpException(Yii::t('yii2mod.rbac', 'The requested page does not exist.'));
} | php | protected function findModel(int $id)
{
$class = $this->userIdentityClass;
if (($user = $class::findIdentity($id)) !== null) {
return new AssignmentModel($user);
}
throw new NotFoundHttpException(Yii::t('yii2mod.rbac', 'The requested page does not exist.'));
} | [
"protected",
"function",
"findModel",
"(",
"int",
"$",
"id",
")",
"{",
"$",
"class",
"=",
"$",
"this",
"->",
"userIdentityClass",
";",
"if",
"(",
"(",
"$",
"user",
"=",
"$",
"class",
"::",
"findIdentity",
"(",
"$",
"id",
")",
")",
"!==",
"null",
")... | Finds the Assignment model based on its primary key value.
If the model is not found, a 404 HTTP exception will be thrown.
@param int $id
@return AssignmentModel the loaded model
@throws NotFoundHttpException if the model cannot be found | [
"Finds",
"the",
"Assignment",
"model",
"based",
"on",
"its",
"primary",
"key",
"value",
".",
"If",
"the",
"model",
"is",
"not",
"found",
"a",
"404",
"HTTP",
"exception",
"will",
"be",
"thrown",
"."
] | train | https://github.com/yii2mod/yii2-rbac/blob/6b98a04fc75bc82ccf87001959f496b283266a40/controllers/AssignmentController.php#L172-L181 |
yii2mod/yii2-rbac | models/search/AssignmentSearch.php | AssignmentSearch.search | public function search(array $params, $class, string $idField, string $usernameField): ActiveDataProvider
{
$query = $class::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => $this->pageSize,
],
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([$idField => $this->id]);
$query->andFilterWhere(['like', $usernameField, $this->username]);
return $dataProvider;
} | php | public function search(array $params, $class, string $idField, string $usernameField): ActiveDataProvider
{
$query = $class::find();
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => $this->pageSize,
],
]);
$this->load($params);
if (!$this->validate()) {
return $dataProvider;
}
$query->andFilterWhere([$idField => $this->id]);
$query->andFilterWhere(['like', $usernameField, $this->username]);
return $dataProvider;
} | [
"public",
"function",
"search",
"(",
"array",
"$",
"params",
",",
"$",
"class",
",",
"string",
"$",
"idField",
",",
"string",
"$",
"usernameField",
")",
":",
"ActiveDataProvider",
"{",
"$",
"query",
"=",
"$",
"class",
"::",
"find",
"(",
")",
";",
"$",
... | Creates data provider instance with search query applied
@param array $params
@param \yii\db\ActiveRecord $class
@param $idField
@param string $usernameField
@return ActiveDataProvider | [
"Creates",
"data",
"provider",
"instance",
"with",
"search",
"query",
"applied"
] | train | https://github.com/yii2mod/yii2-rbac/blob/6b98a04fc75bc82ccf87001959f496b283266a40/models/search/AssignmentSearch.php#L50-L71 |
LaravelCollective/remote | src/RemoteManager.php | RemoteManager.into | public function into($name)
{
if (is_string($name) || is_array($name)) {
return $this->connection($name);
} else {
return $this->connection(func_get_args());
}
} | php | public function into($name)
{
if (is_string($name) || is_array($name)) {
return $this->connection($name);
} else {
return $this->connection(func_get_args());
}
} | [
"public",
"function",
"into",
"(",
"$",
"name",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"name",
")",
"||",
"is_array",
"(",
"$",
"name",
")",
")",
"{",
"return",
"$",
"this",
"->",
"connection",
"(",
"$",
"name",
")",
";",
"}",
"else",
"{",
... | Get a remote connection instance.
@param string|array|mixed $name
@return \Collective\Remote\ConnectionInterface | [
"Get",
"a",
"remote",
"connection",
"instance",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/RemoteManager.php#L35-L42 |
LaravelCollective/remote | src/RemoteManager.php | RemoteManager.makeConnection | protected function makeConnection($name, array $config)
{
$timeout = isset($config['timeout']) ? $config['timeout'] : 10;
$this->setOutput($connection = new Connection(
$name, $config['host'], $config['username'], $this->getAuth($config), null, $timeout
));
return $connection;
} | php | protected function makeConnection($name, array $config)
{
$timeout = isset($config['timeout']) ? $config['timeout'] : 10;
$this->setOutput($connection = new Connection(
$name, $config['host'], $config['username'], $this->getAuth($config), null, $timeout
));
return $connection;
} | [
"protected",
"function",
"makeConnection",
"(",
"$",
"name",
",",
"array",
"$",
"config",
")",
"{",
"$",
"timeout",
"=",
"isset",
"(",
"$",
"config",
"[",
"'timeout'",
"]",
")",
"?",
"$",
"config",
"[",
"'timeout'",
"]",
":",
"10",
";",
"$",
"this",
... | Make a new connection instance.
@param string $name
@param array $config
@return \Collective\Remote\Connection | [
"Make",
"a",
"new",
"connection",
"instance",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/RemoteManager.php#L104-L115 |
LaravelCollective/remote | src/SecLibGateway.php | SecLibGateway.setHostAndPort | protected function setHostAndPort($host)
{
if (!str_contains($host, ':')) {
$this->host = $host;
} else {
list($this->host, $this->port) = explode(':', $host);
$this->port = (int) $this->port;
}
} | php | protected function setHostAndPort($host)
{
if (!str_contains($host, ':')) {
$this->host = $host;
} else {
list($this->host, $this->port) = explode(':', $host);
$this->port = (int) $this->port;
}
} | [
"protected",
"function",
"setHostAndPort",
"(",
"$",
"host",
")",
"{",
"if",
"(",
"!",
"str_contains",
"(",
"$",
"host",
",",
"':'",
")",
")",
"{",
"$",
"this",
"->",
"host",
"=",
"$",
"host",
";",
"}",
"else",
"{",
"list",
"(",
"$",
"this",
"->"... | Set the host and port from a full host string.
@param string $host
@return void | [
"Set",
"the",
"host",
"and",
"port",
"from",
"a",
"full",
"host",
"string",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/SecLibGateway.php#L78-L87 |
LaravelCollective/remote | src/SecLibGateway.php | SecLibGateway.getConnection | public function getConnection()
{
if ($this->connection) {
return $this->connection;
}
return $this->connection = new SFTP($this->host, $this->port, $this->timeout);
} | php | public function getConnection()
{
if ($this->connection) {
return $this->connection;
}
return $this->connection = new SFTP($this->host, $this->port, $this->timeout);
} | [
"public",
"function",
"getConnection",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"connection",
")",
"{",
"return",
"$",
"this",
"->",
"connection",
";",
"}",
"return",
"$",
"this",
"->",
"connection",
"=",
"new",
"SFTP",
"(",
"$",
"this",
"->",
"h... | Get the underlying SFTP connection.
@return \phpseclib\Net\SFTP | [
"Get",
"the",
"underlying",
"SFTP",
"connection",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/SecLibGateway.php#L106-L113 |
LaravelCollective/remote | src/SecLibGateway.php | SecLibGateway.getAuthForLogin | protected function getAuthForLogin()
{
if ($this->useAgent()) {
return $this->getAgent();
}
// If a "key" was specified in the auth credentials, we will load it into a
// secure RSA key instance, which will be used to connect to the servers
// in place of a password, and avoids the developer specifying a pass.
elseif ($this->hasRsaKey()) {
return $this->loadRsaKey($this->auth);
}
// If a plain password was set on the auth credentials, we will just return
// that as it can be used to connect to the server. This will be used if
// there is no RSA key and it gets specified in the credential arrays.
elseif (isset($this->auth['password'])) {
return $this->auth['password'];
}
throw new \InvalidArgumentException('Password / key is required.');
} | php | protected function getAuthForLogin()
{
if ($this->useAgent()) {
return $this->getAgent();
}
// If a "key" was specified in the auth credentials, we will load it into a
// secure RSA key instance, which will be used to connect to the servers
// in place of a password, and avoids the developer specifying a pass.
elseif ($this->hasRsaKey()) {
return $this->loadRsaKey($this->auth);
}
// If a plain password was set on the auth credentials, we will just return
// that as it can be used to connect to the server. This will be used if
// there is no RSA key and it gets specified in the credential arrays.
elseif (isset($this->auth['password'])) {
return $this->auth['password'];
}
throw new \InvalidArgumentException('Password / key is required.');
} | [
"protected",
"function",
"getAuthForLogin",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"useAgent",
"(",
")",
")",
"{",
"return",
"$",
"this",
"->",
"getAgent",
"(",
")",
";",
"}",
"// If a \"key\" was specified in the auth credentials, we will load it into a",
"... | /**
Get the authentication object for login.
@throws \InvalidArgumentException
@return \Crypt_RSA|\System_SSH_Agent|string | [
"/",
"**",
"Get",
"the",
"authentication",
"object",
"for",
"login",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/SecLibGateway.php#L123-L144 |
LaravelCollective/remote | src/SecLibGateway.php | SecLibGateway.hasRsaKey | protected function hasRsaKey()
{
$hasKey = (isset($this->auth['key']) && trim($this->auth['key']) != '');
return $hasKey || (isset($this->auth['keytext']) && trim($this->auth['keytext']) != '');
} | php | protected function hasRsaKey()
{
$hasKey = (isset($this->auth['key']) && trim($this->auth['key']) != '');
return $hasKey || (isset($this->auth['keytext']) && trim($this->auth['keytext']) != '');
} | [
"protected",
"function",
"hasRsaKey",
"(",
")",
"{",
"$",
"hasKey",
"=",
"(",
"isset",
"(",
"$",
"this",
"->",
"auth",
"[",
"'key'",
"]",
")",
"&&",
"trim",
"(",
"$",
"this",
"->",
"auth",
"[",
"'key'",
"]",
")",
"!=",
"''",
")",
";",
"return",
... | Determine if an RSA key is configured.
@return bool | [
"Determine",
"if",
"an",
"RSA",
"key",
"is",
"configured",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/SecLibGateway.php#L171-L176 |
LaravelCollective/remote | src/SecLibGateway.php | SecLibGateway.loadRsaKey | protected function loadRsaKey(array $auth)
{
with($key = $this->getKey($auth))->loadKey($this->readRsaKey($auth));
return $key;
} | php | protected function loadRsaKey(array $auth)
{
with($key = $this->getKey($auth))->loadKey($this->readRsaKey($auth));
return $key;
} | [
"protected",
"function",
"loadRsaKey",
"(",
"array",
"$",
"auth",
")",
"{",
"with",
"(",
"$",
"key",
"=",
"$",
"this",
"->",
"getKey",
"(",
"$",
"auth",
")",
")",
"->",
"loadKey",
"(",
"$",
"this",
"->",
"readRsaKey",
"(",
"$",
"auth",
")",
")",
... | Load the RSA key instance.
@param array $auth
@return \Crypt_RSA | [
"Load",
"the",
"RSA",
"key",
"instance",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/SecLibGateway.php#L185-L190 |
LaravelCollective/remote | src/SecLibGateway.php | SecLibGateway.getKey | protected function getKey(array $auth)
{
with($key = $this->getNewKey())->setPassword(array_get($auth, 'keyphrase'));
return $key;
} | php | protected function getKey(array $auth)
{
with($key = $this->getNewKey())->setPassword(array_get($auth, 'keyphrase'));
return $key;
} | [
"protected",
"function",
"getKey",
"(",
"array",
"$",
"auth",
")",
"{",
"with",
"(",
"$",
"key",
"=",
"$",
"this",
"->",
"getNewKey",
"(",
")",
")",
"->",
"setPassword",
"(",
"array_get",
"(",
"$",
"auth",
",",
"'keyphrase'",
")",
")",
";",
"return",... | Create a new RSA key instance.
@param array $auth
@return \Crypt_RSA | [
"Create",
"a",
"new",
"RSA",
"key",
"instance",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/SecLibGateway.php#L199-L204 |
LaravelCollective/remote | src/SecLibGateway.php | SecLibGateway.put | public function put($local, $remote)
{
$this->getConnection()->put($remote, $local, SFTP::SOURCE_LOCAL_FILE);
} | php | public function put($local, $remote)
{
$this->getConnection()->put($remote, $local, SFTP::SOURCE_LOCAL_FILE);
} | [
"public",
"function",
"put",
"(",
"$",
"local",
",",
"$",
"remote",
")",
"{",
"$",
"this",
"->",
"getConnection",
"(",
")",
"->",
"put",
"(",
"$",
"remote",
",",
"$",
"local",
",",
"SFTP",
"::",
"SOURCE_LOCAL_FILE",
")",
";",
"}"
] | Upload a local file to the server.
@param string $local
@param string $remote
@return void | [
"Upload",
"a",
"local",
"file",
"to",
"the",
"server",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/SecLibGateway.php#L311-L314 |
LaravelCollective/remote | src/SecLibGateway.php | SecLibGateway.nextLine | public function nextLine()
{
$value = $this->getConnection()->_get_channel_packet(SSH2::CHANNEL_EXEC);
return $value === true ? null : $value;
} | php | public function nextLine()
{
$value = $this->getConnection()->_get_channel_packet(SSH2::CHANNEL_EXEC);
return $value === true ? null : $value;
} | [
"public",
"function",
"nextLine",
"(",
")",
"{",
"$",
"value",
"=",
"$",
"this",
"->",
"getConnection",
"(",
")",
"->",
"_get_channel_packet",
"(",
"SSH2",
"::",
"CHANNEL_EXEC",
")",
";",
"return",
"$",
"value",
"===",
"true",
"?",
"null",
":",
"$",
"v... | Get the next line of output from the server.
@return string|null | [
"Get",
"the",
"next",
"line",
"of",
"output",
"from",
"the",
"server",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/SecLibGateway.php#L371-L376 |
LaravelCollective/remote | src/MultiConnection.php | MultiConnection.define | public function define($task, $commands)
{
foreach ($this->connections as $connection) {
$connection->define($task, $commands);
}
} | php | public function define($task, $commands)
{
foreach ($this->connections as $connection) {
$connection->define($task, $commands);
}
} | [
"public",
"function",
"define",
"(",
"$",
"task",
",",
"$",
"commands",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"connections",
"as",
"$",
"connection",
")",
"{",
"$",
"connection",
"->",
"define",
"(",
"$",
"task",
",",
"$",
"commands",
")",
";"... | Define a set of commands as a task.
@param string $task
@param string|array $commands
@return void | [
"Define",
"a",
"set",
"of",
"commands",
"as",
"a",
"task",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/MultiConnection.php#L34-L39 |
LaravelCollective/remote | src/MultiConnection.php | MultiConnection.task | public function task($task, Closure $callback = null)
{
foreach ($this->connections as $connection) {
$connection->task($task, $callback);
}
} | php | public function task($task, Closure $callback = null)
{
foreach ($this->connections as $connection) {
$connection->task($task, $callback);
}
} | [
"public",
"function",
"task",
"(",
"$",
"task",
",",
"Closure",
"$",
"callback",
"=",
"null",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"connections",
"as",
"$",
"connection",
")",
"{",
"$",
"connection",
"->",
"task",
"(",
"$",
"task",
",",
"$",
... | Run a task against the connection.
@param string $task
@param \Closure $callback
@return void | [
"Run",
"a",
"task",
"against",
"the",
"connection",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/MultiConnection.php#L49-L54 |
LaravelCollective/remote | src/MultiConnection.php | MultiConnection.run | public function run($commands, Closure $callback = null)
{
foreach ($this->connections as $connection) {
$connection->run($commands, $callback);
}
} | php | public function run($commands, Closure $callback = null)
{
foreach ($this->connections as $connection) {
$connection->run($commands, $callback);
}
} | [
"public",
"function",
"run",
"(",
"$",
"commands",
",",
"Closure",
"$",
"callback",
"=",
"null",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"connections",
"as",
"$",
"connection",
")",
"{",
"$",
"connection",
"->",
"run",
"(",
"$",
"commands",
",",
... | Run a set of commands against the connection.
@param string|array $commands
@param \Closure $callback
@return void | [
"Run",
"a",
"set",
"of",
"commands",
"against",
"the",
"connection",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/MultiConnection.php#L64-L69 |
LaravelCollective/remote | src/MultiConnection.php | MultiConnection.get | public function get($remote, $local)
{
foreach ($this->connections as $connection) {
$connection->get($remote, $local);
}
} | php | public function get($remote, $local)
{
foreach ($this->connections as $connection) {
$connection->get($remote, $local);
}
} | [
"public",
"function",
"get",
"(",
"$",
"remote",
",",
"$",
"local",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"connections",
"as",
"$",
"connection",
")",
"{",
"$",
"connection",
"->",
"get",
"(",
"$",
"remote",
",",
"$",
"local",
")",
";",
"}",... | Download the contents of a remote file.
@param string $remote
@param string $local
@return void | [
"Download",
"the",
"contents",
"of",
"a",
"remote",
"file",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/MultiConnection.php#L79-L84 |
LaravelCollective/remote | src/MultiConnection.php | MultiConnection.put | public function put($local, $remote)
{
foreach ($this->connections as $connection) {
$connection->put($local, $remote);
}
} | php | public function put($local, $remote)
{
foreach ($this->connections as $connection) {
$connection->put($local, $remote);
}
} | [
"public",
"function",
"put",
"(",
"$",
"local",
",",
"$",
"remote",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"connections",
"as",
"$",
"connection",
")",
"{",
"$",
"connection",
"->",
"put",
"(",
"$",
"local",
",",
"$",
"remote",
")",
";",
"}",... | Upload a local file to the server.
@param string $local
@param string $remote
@return void | [
"Upload",
"a",
"local",
"file",
"to",
"the",
"server",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/MultiConnection.php#L108-L113 |
LaravelCollective/remote | src/MultiConnection.php | MultiConnection.putString | public function putString($remote, $contents)
{
foreach ($this->connections as $connection) {
$connection->putString($remote, $contents);
}
} | php | public function putString($remote, $contents)
{
foreach ($this->connections as $connection) {
$connection->putString($remote, $contents);
}
} | [
"public",
"function",
"putString",
"(",
"$",
"remote",
",",
"$",
"contents",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"connections",
"as",
"$",
"connection",
")",
"{",
"$",
"connection",
"->",
"putString",
"(",
"$",
"remote",
",",
"$",
"contents",
... | Upload a string to to the given file on the server.
@param string $remote
@param string $contents
@return void | [
"Upload",
"a",
"string",
"to",
"to",
"the",
"given",
"file",
"on",
"the",
"server",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/MultiConnection.php#L123-L128 |
LaravelCollective/remote | src/MultiConnection.php | MultiConnection.rename | public function rename($remote, $newRemote)
{
foreach ($this->connections as $connection) {
$connection->rename($remote, $newRemote);
}
} | php | public function rename($remote, $newRemote)
{
foreach ($this->connections as $connection) {
$connection->rename($remote, $newRemote);
}
} | [
"public",
"function",
"rename",
"(",
"$",
"remote",
",",
"$",
"newRemote",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"connections",
"as",
"$",
"connection",
")",
"{",
"$",
"connection",
"->",
"rename",
"(",
"$",
"remote",
",",
"$",
"newRemote",
")",... | Rename a remote file.
@param string $remote
@param string $newRemote
@return bool | [
"Rename",
"a",
"remote",
"file",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/MultiConnection.php#L152-L157 |
LaravelCollective/remote | src/Console/TailCommand.php | TailCommand.handle | public function handle()
{
$path = $this->getPath($this->argument('connection'));
if ($path) {
$this->tailLogFile($path, $this->argument('connection'));
} else {
$this->error('Could not determine path to log file.');
}
} | php | public function handle()
{
$path = $this->getPath($this->argument('connection'));
if ($path) {
$this->tailLogFile($path, $this->argument('connection'));
} else {
$this->error('Could not determine path to log file.');
}
} | [
"public",
"function",
"handle",
"(",
")",
"{",
"$",
"path",
"=",
"$",
"this",
"->",
"getPath",
"(",
"$",
"this",
"->",
"argument",
"(",
"'connection'",
")",
")",
";",
"if",
"(",
"$",
"path",
")",
"{",
"$",
"this",
"->",
"tailLogFile",
"(",
"$",
"... | Execute the console command.
@return void | [
"Execute",
"the",
"console",
"command",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/Console/TailCommand.php#L34-L43 |
LaravelCollective/remote | src/Console/TailCommand.php | TailCommand.tailLogFile | protected function tailLogFile($path, $connection)
{
if (is_null($connection)) {
$this->tailLocalLogs($path);
} else {
$this->tailRemoteLogs($path, $connection);
}
} | php | protected function tailLogFile($path, $connection)
{
if (is_null($connection)) {
$this->tailLocalLogs($path);
} else {
$this->tailRemoteLogs($path, $connection);
}
} | [
"protected",
"function",
"tailLogFile",
"(",
"$",
"path",
",",
"$",
"connection",
")",
"{",
"if",
"(",
"is_null",
"(",
"$",
"connection",
")",
")",
"{",
"$",
"this",
"->",
"tailLocalLogs",
"(",
"$",
"path",
")",
";",
"}",
"else",
"{",
"$",
"this",
... | Tail the given log file for the connection.
@param string $path
@param string $connection
@return void | [
"Tail",
"the",
"given",
"log",
"file",
"for",
"the",
"connection",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/Console/TailCommand.php#L53-L60 |
LaravelCollective/remote | src/Console/TailCommand.php | TailCommand.tailRemoteLogs | protected function tailRemoteLogs($path, $connection)
{
$out = $this->output;
$lines = $this->option('lines');
$this->getRemote($connection)->run('cd '.escapeshellarg($path).' && tail -f $(ls -t | head -n 1) -n '.$lines, function ($line) use ($out) {
$out->write($line);
});
} | php | protected function tailRemoteLogs($path, $connection)
{
$out = $this->output;
$lines = $this->option('lines');
$this->getRemote($connection)->run('cd '.escapeshellarg($path).' && tail -f $(ls -t | head -n 1) -n '.$lines, function ($line) use ($out) {
$out->write($line);
});
} | [
"protected",
"function",
"tailRemoteLogs",
"(",
"$",
"path",
",",
"$",
"connection",
")",
"{",
"$",
"out",
"=",
"$",
"this",
"->",
"output",
";",
"$",
"lines",
"=",
"$",
"this",
"->",
"option",
"(",
"'lines'",
")",
";",
"$",
"this",
"->",
"getRemote"... | Tail a remote log file at the given path and connection.
@param string $path
@param string $connection
@return void | [
"Tail",
"a",
"remote",
"log",
"file",
"at",
"the",
"given",
"path",
"and",
"connection",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/Console/TailCommand.php#L92-L101 |
LaravelCollective/remote | src/Console/TailCommand.php | TailCommand.findNewestLocalLogfile | protected function findNewestLocalLogfile($path)
{
$files = glob($path.'/*.log');
$files = array_combine($files, array_map('filemtime', $files));
arsort($files);
$newestLogFile = key($files);
return $newestLogFile;
} | php | protected function findNewestLocalLogfile($path)
{
$files = glob($path.'/*.log');
$files = array_combine($files, array_map('filemtime', $files));
arsort($files);
$newestLogFile = key($files);
return $newestLogFile;
} | [
"protected",
"function",
"findNewestLocalLogfile",
"(",
"$",
"path",
")",
"{",
"$",
"files",
"=",
"glob",
"(",
"$",
"path",
".",
"'/*.log'",
")",
";",
"$",
"files",
"=",
"array_combine",
"(",
"$",
"files",
",",
"array_map",
"(",
"'filemtime'",
",",
"$",
... | Get the path to the latest local Laravel log file.
@param $path
@return mixed | [
"Get",
"the",
"path",
"to",
"the",
"latest",
"local",
"Laravel",
"log",
"file",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/Console/TailCommand.php#L110-L121 |
LaravelCollective/remote | src/Console/TailCommand.php | TailCommand.getPath | protected function getPath($connection)
{
if ($this->option('path')) {
return $this->option('path');
}
if (is_null($connection) && $this->option('path')) {
return storage_path($this->option('path'));
} elseif (is_null($connection) && !$this->option('path')) {
return storage_path('logs');
}
return $this->getRoot($connection).str_replace(base_path(), '', storage_path('logs'));
} | php | protected function getPath($connection)
{
if ($this->option('path')) {
return $this->option('path');
}
if (is_null($connection) && $this->option('path')) {
return storage_path($this->option('path'));
} elseif (is_null($connection) && !$this->option('path')) {
return storage_path('logs');
}
return $this->getRoot($connection).str_replace(base_path(), '', storage_path('logs'));
} | [
"protected",
"function",
"getPath",
"(",
"$",
"connection",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"option",
"(",
"'path'",
")",
")",
"{",
"return",
"$",
"this",
"->",
"option",
"(",
"'path'",
")",
";",
"}",
"if",
"(",
"is_null",
"(",
"$",
"connec... | Get the path to the Laravel log file.
@param string $connection
@return string | [
"Get",
"the",
"path",
"to",
"the",
"Laravel",
"log",
"file",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/Console/TailCommand.php#L142-L155 |
LaravelCollective/remote | src/Connection.php | Connection.task | public function task($task, Closure $callback = null)
{
if (isset($this->tasks[$task])) {
$this->run($this->tasks[$task], $callback);
}
} | php | public function task($task, Closure $callback = null)
{
if (isset($this->tasks[$task])) {
$this->run($this->tasks[$task], $callback);
}
} | [
"public",
"function",
"task",
"(",
"$",
"task",
",",
"Closure",
"$",
"callback",
"=",
"null",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"tasks",
"[",
"$",
"task",
"]",
")",
")",
"{",
"$",
"this",
"->",
"run",
"(",
"$",
"this",
"->",... | Run a task against the connection.
@param string $task
@param \Closure $callback
@return void | [
"Run",
"a",
"task",
"against",
"the",
"connection",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/Connection.php#L95-L100 |
LaravelCollective/remote | src/Connection.php | Connection.run | public function run($commands, Closure $callback = null)
{
// First, we will initialize the SSH gateway, and then format the commands so
// they can be run. Once we have the commands formatted and the server is
// ready to go we will just fire off these commands against the server.
$gateway = $this->getGateway();
$callback = $this->getCallback($callback);
$gateway->run($this->formatCommands($commands));
// After running the commands against the server, we will continue to ask for
// the next line of output that is available, and write it them out using
// our callback. Once we hit the end of output, we'll bail out of here.
while (true) {
if (is_null($line = $gateway->nextLine())) {
break;
}
call_user_func($callback, $line, $this);
}
} | php | public function run($commands, Closure $callback = null)
{
// First, we will initialize the SSH gateway, and then format the commands so
// they can be run. Once we have the commands formatted and the server is
// ready to go we will just fire off these commands against the server.
$gateway = $this->getGateway();
$callback = $this->getCallback($callback);
$gateway->run($this->formatCommands($commands));
// After running the commands against the server, we will continue to ask for
// the next line of output that is available, and write it them out using
// our callback. Once we hit the end of output, we'll bail out of here.
while (true) {
if (is_null($line = $gateway->nextLine())) {
break;
}
call_user_func($callback, $line, $this);
}
} | [
"public",
"function",
"run",
"(",
"$",
"commands",
",",
"Closure",
"$",
"callback",
"=",
"null",
")",
"{",
"// First, we will initialize the SSH gateway, and then format the commands so",
"// they can be run. Once we have the commands formatted and the server is",
"// ready to go we ... | Run a set of commands against the connection.
@param string|array $commands
@param \Closure $callback
@return void | [
"Run",
"a",
"set",
"of",
"commands",
"against",
"the",
"connection",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/Connection.php#L110-L131 |
LaravelCollective/remote | src/Connection.php | Connection.getGateway | public function getGateway()
{
if (!$this->gateway->connected() && !$this->gateway->connect($this->username)) {
throw new \RuntimeException('Unable to connect to remote server.');
}
return $this->gateway;
} | php | public function getGateway()
{
if (!$this->gateway->connected() && !$this->gateway->connect($this->username)) {
throw new \RuntimeException('Unable to connect to remote server.');
}
return $this->gateway;
} | [
"public",
"function",
"getGateway",
"(",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"gateway",
"->",
"connected",
"(",
")",
"&&",
"!",
"$",
"this",
"->",
"gateway",
"->",
"connect",
"(",
"$",
"this",
"->",
"username",
")",
")",
"{",
"throw",
"new... | Get the gateway implementation.
@throws \RuntimeException
@return \Collective\Remote\GatewayInterface | [
"Get",
"the",
"gateway",
"implementation",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/Connection.php#L140-L147 |
LaravelCollective/remote | src/Connection.php | Connection.display | public function display($line)
{
$server = $this->username.'@'.$this->host;
$lead = '<comment>['.$server.']</comment> <info>('.$this->name.')</info>';
$this->getOutput()->writeln($lead.' '.$line);
} | php | public function display($line)
{
$server = $this->username.'@'.$this->host;
$lead = '<comment>['.$server.']</comment> <info>('.$this->name.')</info>';
$this->getOutput()->writeln($lead.' '.$line);
} | [
"public",
"function",
"display",
"(",
"$",
"line",
")",
"{",
"$",
"server",
"=",
"$",
"this",
"->",
"username",
".",
"'@'",
".",
"$",
"this",
"->",
"host",
";",
"$",
"lead",
"=",
"'<comment>['",
".",
"$",
"server",
".",
"']</comment> <info>('",
".",
... | Display the given line using the default output.
@param string $line
@return void | [
"Display",
"the",
"given",
"line",
"using",
"the",
"default",
"output",
"."
] | train | https://github.com/LaravelCollective/remote/blob/f37309c1cbdfe5c2e01e4f90b6f21a6180e215e1/src/Connection.php#L174-L181 |
nette/coding-standard | src/Sniffs/WhiteSpace/FunctionSpacingSniff.php | FunctionSpacingSniff.process | public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
/*
Check the number of blank lines
after the function.
*/
if (isset($tokens[$stackPtr]['scope_closer']) === false) {
// Must be an interface method, so the closer is the semicolon.
$closer = $phpcsFile->findNext(T_SEMICOLON, $stackPtr);
} else {
$closer = $tokens[$stackPtr]['scope_closer'];
}
$this->spacing = end($tokens[$stackPtr]['conditions']) === T_INTERFACE ? 1 : 2;
// Allow for comments on the same line as the closer.
for ($nextLineToken = ($closer + 1); $nextLineToken < $phpcsFile->numTokens; $nextLineToken++) {
if ($tokens[$nextLineToken]['line'] !== $tokens[$closer]['line']) {
break;
}
}
$foundLines = 0;
if ($nextLineToken === ($phpcsFile->numTokens - 1)) {
// We are at the end of the file.
// Don't check spacing after the function because this
// should be done by an EOF sniff.
$foundLines = $this->spacing;
} else {
$nextContent = $phpcsFile->findNext(T_WHITESPACE, $nextLineToken, null, true);
if ($nextContent === false) {
// We are at the end of the file.
// Don't check spacing after the function because this
// should be done by an EOF sniff.
$foundLines = $this->spacing;
} elseif ($tokens[$nextContent]['code'] === T_CLOSE_CURLY_BRACKET) {
// last function in class
$foundLines = $this->spacing;
} else {
$foundLines += ($tokens[$nextContent]['line'] - $tokens[$nextLineToken]['line']);
}
}
if ($foundLines !== $this->spacing) {
$error = 'Expected %s blank line';
if ($this->spacing !== 1) {
$error .= 's';
}
$error .= ' after function; %s found';
$data = [
$this->spacing,
$foundLines,
];
$fix = $phpcsFile->addFixableError($error, $closer, 'After', $data);
if ($fix === true) {
$phpcsFile->fixer->beginChangeset();
for ($i = $nextLineToken; $i <= $nextContent; $i++) {
if ($tokens[$i]['line'] === $tokens[$nextContent]['line']) {
$phpcsFile->fixer->addContentBefore($i, str_repeat($phpcsFile->eolChar, $this->spacing));
break;
}
$phpcsFile->fixer->replaceToken($i, '');
}
$phpcsFile->fixer->endChangeset();
}//end if
}//end if
/*
Check the number of blank lines
before the function.
*/
$prevLineToken = null;
for ($i = $stackPtr; $i > 0; $i--) {
if (strpos($tokens[$i]['content'], $phpcsFile->eolChar) === false) {
continue;
} else {
$prevLineToken = $i;
break;
}
}
if (($prevLineToken === null) === true) {
// Never found the previous line, which means
// there are 0 blank lines before the function.
$foundLines = 0;
$prevContent = 0;
} else {
$currentLine = $tokens[$stackPtr]['line'];
$prevContent = $phpcsFile->findPrevious(T_WHITESPACE, $prevLineToken, null, true);
if ($tokens[$prevContent]['code'] === T_COMMENT) {
// Ignore comments as they can have different spacing rules, and this
// isn't a proper function comment anyway.
return;
}
if ($tokens[$prevContent]['code'] === T_DOC_COMMENT_CLOSE_TAG
&& $tokens[$prevContent]['line'] === ($currentLine - 1)
) {
// Account for function comments.
$prevContent = $phpcsFile->findPrevious(T_WHITESPACE, ($tokens[$prevContent]['comment_opener'] - 1), null, true);
}
if ($tokens[$prevContent]['code'] === T_OPEN_CURLY_BRACKET) {
// first function in class
return;
}
if ($tokens[$prevContent]['level'] && ($useToken = $phpcsFile->findPrevious(T_USE, $prevContent)) && $tokens[$useToken]['line'] === $tokens[$prevContent]['line']) {
$this->spacing = 1; // method after 'use'
}
// Before we throw an error, check that we are not throwing an error
// for another function. We don't want to error for no blank lines after
// the previous function and no blank lines before this one as well.
$prevLine = ($tokens[$prevContent]['line'] - 1);
$i = ($stackPtr - 1);
$foundLines = 0;
while ($currentLine !== $prevLine && $currentLine > 1 && $i > 0) {
if (isset($tokens[$i]['scope_condition']) === true) {
$scopeCondition = $tokens[$i]['scope_condition'];
if ($tokens[$scopeCondition]['code'] === T_FUNCTION) {
// Found a previous function.
return;
}
} elseif ($tokens[$i]['code'] === T_FUNCTION) {
// Found another interface function.
return;
}
$currentLine = $tokens[$i]['line'];
if ($currentLine === $prevLine) {
break;
}
if ($tokens[($i - 1)]['line'] < $currentLine && $tokens[($i + 1)]['line'] > $currentLine) {
// This token is on a line by itself. If it is whitespace, the line is empty.
if ($tokens[$i]['code'] === T_WHITESPACE) {
$foundLines++;
}
}
$i--;
}//end while
}//end if
if ($foundLines !== $this->spacing) {
$error = 'Expected %s blank line';
if ($this->spacing !== 1) {
$error .= 's';
}
$error .= ' before function; %s found';
$data = [
$this->spacing,
$foundLines,
];
$fix = $phpcsFile->addFixableError($error, $stackPtr, 'Before', $data);
if ($fix === true) {
if ($prevContent === 0) {
$nextSpace = 0;
} else {
$nextSpace = $phpcsFile->findNext(T_WHITESPACE, ($prevContent + 1), $stackPtr);
if ($nextSpace === false) {
$nextSpace = ($stackPtr - 1);
}
}
if ($foundLines < $this->spacing) {
$padding = str_repeat($phpcsFile->eolChar, ($this->spacing - $foundLines));
$phpcsFile->fixer->addContent($nextSpace, $padding);
} else {
$nextContent = $phpcsFile->findNext(T_WHITESPACE, ($nextSpace + 1), null, true);
$phpcsFile->fixer->beginChangeset();
for ($i = $nextSpace; $i < ($nextContent - 1); $i++) {
if (strpos($tokens[$i]['content'], "\n") !== false) {
$phpcsFile->fixer->replaceToken($i, '');
}
}
$phpcsFile->fixer->replaceToken($i, str_repeat($phpcsFile->eolChar, $this->spacing + 1) . str_repeat("\t", $tokens[$i]['level']));
$phpcsFile->fixer->endChangeset();
}
}//end if
}//end if
} | php | public function process(File $phpcsFile, $stackPtr)
{
$tokens = $phpcsFile->getTokens();
/*
Check the number of blank lines
after the function.
*/
if (isset($tokens[$stackPtr]['scope_closer']) === false) {
// Must be an interface method, so the closer is the semicolon.
$closer = $phpcsFile->findNext(T_SEMICOLON, $stackPtr);
} else {
$closer = $tokens[$stackPtr]['scope_closer'];
}
$this->spacing = end($tokens[$stackPtr]['conditions']) === T_INTERFACE ? 1 : 2;
// Allow for comments on the same line as the closer.
for ($nextLineToken = ($closer + 1); $nextLineToken < $phpcsFile->numTokens; $nextLineToken++) {
if ($tokens[$nextLineToken]['line'] !== $tokens[$closer]['line']) {
break;
}
}
$foundLines = 0;
if ($nextLineToken === ($phpcsFile->numTokens - 1)) {
// We are at the end of the file.
// Don't check spacing after the function because this
// should be done by an EOF sniff.
$foundLines = $this->spacing;
} else {
$nextContent = $phpcsFile->findNext(T_WHITESPACE, $nextLineToken, null, true);
if ($nextContent === false) {
// We are at the end of the file.
// Don't check spacing after the function because this
// should be done by an EOF sniff.
$foundLines = $this->spacing;
} elseif ($tokens[$nextContent]['code'] === T_CLOSE_CURLY_BRACKET) {
// last function in class
$foundLines = $this->spacing;
} else {
$foundLines += ($tokens[$nextContent]['line'] - $tokens[$nextLineToken]['line']);
}
}
if ($foundLines !== $this->spacing) {
$error = 'Expected %s blank line';
if ($this->spacing !== 1) {
$error .= 's';
}
$error .= ' after function; %s found';
$data = [
$this->spacing,
$foundLines,
];
$fix = $phpcsFile->addFixableError($error, $closer, 'After', $data);
if ($fix === true) {
$phpcsFile->fixer->beginChangeset();
for ($i = $nextLineToken; $i <= $nextContent; $i++) {
if ($tokens[$i]['line'] === $tokens[$nextContent]['line']) {
$phpcsFile->fixer->addContentBefore($i, str_repeat($phpcsFile->eolChar, $this->spacing));
break;
}
$phpcsFile->fixer->replaceToken($i, '');
}
$phpcsFile->fixer->endChangeset();
}//end if
}//end if
/*
Check the number of blank lines
before the function.
*/
$prevLineToken = null;
for ($i = $stackPtr; $i > 0; $i--) {
if (strpos($tokens[$i]['content'], $phpcsFile->eolChar) === false) {
continue;
} else {
$prevLineToken = $i;
break;
}
}
if (($prevLineToken === null) === true) {
// Never found the previous line, which means
// there are 0 blank lines before the function.
$foundLines = 0;
$prevContent = 0;
} else {
$currentLine = $tokens[$stackPtr]['line'];
$prevContent = $phpcsFile->findPrevious(T_WHITESPACE, $prevLineToken, null, true);
if ($tokens[$prevContent]['code'] === T_COMMENT) {
// Ignore comments as they can have different spacing rules, and this
// isn't a proper function comment anyway.
return;
}
if ($tokens[$prevContent]['code'] === T_DOC_COMMENT_CLOSE_TAG
&& $tokens[$prevContent]['line'] === ($currentLine - 1)
) {
// Account for function comments.
$prevContent = $phpcsFile->findPrevious(T_WHITESPACE, ($tokens[$prevContent]['comment_opener'] - 1), null, true);
}
if ($tokens[$prevContent]['code'] === T_OPEN_CURLY_BRACKET) {
// first function in class
return;
}
if ($tokens[$prevContent]['level'] && ($useToken = $phpcsFile->findPrevious(T_USE, $prevContent)) && $tokens[$useToken]['line'] === $tokens[$prevContent]['line']) {
$this->spacing = 1; // method after 'use'
}
// Before we throw an error, check that we are not throwing an error
// for another function. We don't want to error for no blank lines after
// the previous function and no blank lines before this one as well.
$prevLine = ($tokens[$prevContent]['line'] - 1);
$i = ($stackPtr - 1);
$foundLines = 0;
while ($currentLine !== $prevLine && $currentLine > 1 && $i > 0) {
if (isset($tokens[$i]['scope_condition']) === true) {
$scopeCondition = $tokens[$i]['scope_condition'];
if ($tokens[$scopeCondition]['code'] === T_FUNCTION) {
// Found a previous function.
return;
}
} elseif ($tokens[$i]['code'] === T_FUNCTION) {
// Found another interface function.
return;
}
$currentLine = $tokens[$i]['line'];
if ($currentLine === $prevLine) {
break;
}
if ($tokens[($i - 1)]['line'] < $currentLine && $tokens[($i + 1)]['line'] > $currentLine) {
// This token is on a line by itself. If it is whitespace, the line is empty.
if ($tokens[$i]['code'] === T_WHITESPACE) {
$foundLines++;
}
}
$i--;
}//end while
}//end if
if ($foundLines !== $this->spacing) {
$error = 'Expected %s blank line';
if ($this->spacing !== 1) {
$error .= 's';
}
$error .= ' before function; %s found';
$data = [
$this->spacing,
$foundLines,
];
$fix = $phpcsFile->addFixableError($error, $stackPtr, 'Before', $data);
if ($fix === true) {
if ($prevContent === 0) {
$nextSpace = 0;
} else {
$nextSpace = $phpcsFile->findNext(T_WHITESPACE, ($prevContent + 1), $stackPtr);
if ($nextSpace === false) {
$nextSpace = ($stackPtr - 1);
}
}
if ($foundLines < $this->spacing) {
$padding = str_repeat($phpcsFile->eolChar, ($this->spacing - $foundLines));
$phpcsFile->fixer->addContent($nextSpace, $padding);
} else {
$nextContent = $phpcsFile->findNext(T_WHITESPACE, ($nextSpace + 1), null, true);
$phpcsFile->fixer->beginChangeset();
for ($i = $nextSpace; $i < ($nextContent - 1); $i++) {
if (strpos($tokens[$i]['content'], "\n") !== false) {
$phpcsFile->fixer->replaceToken($i, '');
}
}
$phpcsFile->fixer->replaceToken($i, str_repeat($phpcsFile->eolChar, $this->spacing + 1) . str_repeat("\t", $tokens[$i]['level']));
$phpcsFile->fixer->endChangeset();
}
}//end if
}//end if
} | [
"public",
"function",
"process",
"(",
"File",
"$",
"phpcsFile",
",",
"$",
"stackPtr",
")",
"{",
"$",
"tokens",
"=",
"$",
"phpcsFile",
"->",
"getTokens",
"(",
")",
";",
"/*\n\t\t\tCheck the number of blank lines\n\t\t\tafter the function.\n\t\t*/",
"if",
"(",
"isset"... | Processes this sniff when one of its tokens is encountered.
@param \PHP_CodeSniffer\Files\File $phpcsFile The file being scanned.
@param int $stackPtr The position of the current token
in the stack passed in $tokens.
@return void | [
"Processes",
"this",
"sniff",
"when",
"one",
"of",
"its",
"tokens",
"is",
"encountered",
"."
] | train | https://github.com/nette/coding-standard/blob/9dc1871826b76b195cd38f84cceaa5f96f4608dc/src/Sniffs/WhiteSpace/FunctionSpacingSniff.php#L47-L243 |
nette/coding-standard | src/Fixer/Basic/BracesFixer.php | BracesFixer.createConfigurationDefinition | protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('allow_single_line_closure', 'Whether single line lambda notation should be allowed.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
(new FixerOptionBuilder('position_after_functions_and_oop_constructs', 'whether the opening brace should be placed on "next" or "same" line after classy constructs (non-anonymous classes, interfaces, traits, methods and non-lambda functions).'))
->setAllowedValues([self::LINE_NEXT, self::LINE_SAME])
->setDefault(self::LINE_NEXT)
->getOption(),
]);
} | php | protected function createConfigurationDefinition()
{
return new FixerConfigurationResolver([
(new FixerOptionBuilder('allow_single_line_closure', 'Whether single line lambda notation should be allowed.'))
->setAllowedTypes(['bool'])
->setDefault(false)
->getOption(),
(new FixerOptionBuilder('position_after_functions_and_oop_constructs', 'whether the opening brace should be placed on "next" or "same" line after classy constructs (non-anonymous classes, interfaces, traits, methods and non-lambda functions).'))
->setAllowedValues([self::LINE_NEXT, self::LINE_SAME])
->setDefault(self::LINE_NEXT)
->getOption(),
]);
} | [
"protected",
"function",
"createConfigurationDefinition",
"(",
")",
"{",
"return",
"new",
"FixerConfigurationResolver",
"(",
"[",
"(",
"new",
"FixerOptionBuilder",
"(",
"'allow_single_line_closure'",
",",
"'Whether single line lambda notation should be allowed.'",
")",
")",
"... | {@inheritdoc} | [
"{"
] | train | https://github.com/nette/coding-standard/blob/9dc1871826b76b195cd38f84cceaa5f96f4608dc/src/Fixer/Basic/BracesFixer.php#L163-L175 |
nette/coding-standard | src/Fixer/Basic/BracesFixer.php | BracesFixer.detectIndent | private function detectIndent(Tokens $tokens, $index)
{
while (true) {
$whitespaceIndex = $tokens->getPrevTokenOfKind($index, [[T_WHITESPACE]]);
if ($whitespaceIndex === null) {
return '';
}
$whitespaceToken = $tokens[$whitespaceIndex];
if (strpos($whitespaceToken->getContent(), "\n") !== false) {
break;
}
$prevToken = $tokens[$whitespaceIndex - 1];
if ($prevToken->isGivenKind([T_OPEN_TAG, T_COMMENT]) && substr($prevToken->getContent(), -1) === "\n") {
break;
}
$index = $whitespaceIndex;
}
$explodedContent = explode("\n", $whitespaceToken->getContent());
return end($explodedContent);
} | php | private function detectIndent(Tokens $tokens, $index)
{
while (true) {
$whitespaceIndex = $tokens->getPrevTokenOfKind($index, [[T_WHITESPACE]]);
if ($whitespaceIndex === null) {
return '';
}
$whitespaceToken = $tokens[$whitespaceIndex];
if (strpos($whitespaceToken->getContent(), "\n") !== false) {
break;
}
$prevToken = $tokens[$whitespaceIndex - 1];
if ($prevToken->isGivenKind([T_OPEN_TAG, T_COMMENT]) && substr($prevToken->getContent(), -1) === "\n") {
break;
}
$index = $whitespaceIndex;
}
$explodedContent = explode("\n", $whitespaceToken->getContent());
return end($explodedContent);
} | [
"private",
"function",
"detectIndent",
"(",
"Tokens",
"$",
"tokens",
",",
"$",
"index",
")",
"{",
"while",
"(",
"true",
")",
"{",
"$",
"whitespaceIndex",
"=",
"$",
"tokens",
"->",
"getPrevTokenOfKind",
"(",
"$",
"index",
",",
"[",
"[",
"T_WHITESPACE",
"]... | @param Tokens $tokens
@param int $index
@return string | [
"@param",
"Tokens",
"$tokens",
"@param",
"int",
"$index"
] | train | https://github.com/nette/coding-standard/blob/9dc1871826b76b195cd38f84cceaa5f96f4608dc/src/Fixer/Basic/BracesFixer.php#L558-L585 |
nette/coding-standard | src/Fixer/ClassNotation/LastPropertyAndFirstMethodSeparationFixer.php | LastPropertyAndFirstMethodSeparationFixer.fixSpacesBelow | private function fixSpacesBelow(Tokens $tokens, int $classEnd, int $propertyEnd): void
{
$nextNotWhitePosition = $tokens->getNextNonWhitespace($propertyEnd);
if ($nextNotWhitePosition === null) {
return;
}
$classAttributesSeparationFixer = new ClassAttributesSeparationFixer();
$classAttributesSeparationFixer->setWhitespacesConfig($this->whitespacesFixerConfig);
$arguments = [
$tokens,
$propertyEnd,
$nextNotWhitePosition,
$nextNotWhitePosition === $classEnd ? $this->configuration[self::SPACE_COUNT_OPTION] : $this->configuration[self::SPACE_COUNT_OPTION] + 1,
];
(new PrivatesCaller())->callPrivateMethod(
$classAttributesSeparationFixer,
'correctLineBreaks',
...$arguments
);
} | php | private function fixSpacesBelow(Tokens $tokens, int $classEnd, int $propertyEnd): void
{
$nextNotWhitePosition = $tokens->getNextNonWhitespace($propertyEnd);
if ($nextNotWhitePosition === null) {
return;
}
$classAttributesSeparationFixer = new ClassAttributesSeparationFixer();
$classAttributesSeparationFixer->setWhitespacesConfig($this->whitespacesFixerConfig);
$arguments = [
$tokens,
$propertyEnd,
$nextNotWhitePosition,
$nextNotWhitePosition === $classEnd ? $this->configuration[self::SPACE_COUNT_OPTION] : $this->configuration[self::SPACE_COUNT_OPTION] + 1,
];
(new PrivatesCaller())->callPrivateMethod(
$classAttributesSeparationFixer,
'correctLineBreaks',
...$arguments
);
} | [
"private",
"function",
"fixSpacesBelow",
"(",
"Tokens",
"$",
"tokens",
",",
"int",
"$",
"classEnd",
",",
"int",
"$",
"propertyEnd",
")",
":",
"void",
"{",
"$",
"nextNotWhitePosition",
"=",
"$",
"tokens",
"->",
"getNextNonWhitespace",
"(",
"$",
"propertyEnd",
... | Same as @see \PhpCsFixer\Fixer\ClassNotation\ClassAttributesSeparationFixer::correctLineBreaks().
This solution prevents BC breaks and include code updates. | [
"Same",
"as",
"@see",
"\\",
"PhpCsFixer",
"\\",
"Fixer",
"\\",
"ClassNotation",
"\\",
"ClassAttributesSeparationFixer",
"::",
"correctLineBreaks",
"()",
"."
] | train | https://github.com/nette/coding-standard/blob/9dc1871826b76b195cd38f84cceaa5f96f4608dc/src/Fixer/ClassNotation/LastPropertyAndFirstMethodSeparationFixer.php#L186-L208 |
zoujingli/ip2region | Ip2Region.php | Ip2Region.memorySearch | public function memorySearch($ip)
{
//check and load the binary string for the first time
if ( $this->dbBinStr == NULL ) {
$this->dbBinStr = file_get_contents($this->dbFile);
if ( $this->dbBinStr == false ) {
throw new Exception("Fail to open the db file {$this->dbFile}");
}
$this->firstIndexPtr = self::getLong($this->dbBinStr, 0);
$this->lastIndexPtr = self::getLong($this->dbBinStr, 4);
$this->totalBlocks = ($this->lastIndexPtr-$this->firstIndexPtr)/INDEX_BLOCK_LENGTH + 1;
}
if ( is_string($ip) ) $ip = self::safeIp2long($ip);
//binary search to define the data
$l = 0;
$h = $this->totalBlocks;
$dataPtr = 0;
while ( $l <= $h ) {
$m = (($l + $h) >> 1);
$p = $this->firstIndexPtr + $m * INDEX_BLOCK_LENGTH;
$sip = self::getLong($this->dbBinStr, $p);
if ( $ip < $sip ) {
$h = $m - 1;
} else {
$eip = self::getLong($this->dbBinStr, $p + 4);
if ( $ip > $eip ) {
$l = $m + 1;
} else {
$dataPtr = self::getLong($this->dbBinStr, $p + 8);
break;
}
}
}
//not matched just stop it here
if ( $dataPtr == 0 ) return NULL;
//get the data
$dataLen = (($dataPtr >> 24) & 0xFF);
$dataPtr = ($dataPtr & 0x00FFFFFF);
return array(
'city_id' => self::getLong($this->dbBinStr, $dataPtr),
'region' => substr($this->dbBinStr, $dataPtr + 4, $dataLen - 4)
);
} | php | public function memorySearch($ip)
{
//check and load the binary string for the first time
if ( $this->dbBinStr == NULL ) {
$this->dbBinStr = file_get_contents($this->dbFile);
if ( $this->dbBinStr == false ) {
throw new Exception("Fail to open the db file {$this->dbFile}");
}
$this->firstIndexPtr = self::getLong($this->dbBinStr, 0);
$this->lastIndexPtr = self::getLong($this->dbBinStr, 4);
$this->totalBlocks = ($this->lastIndexPtr-$this->firstIndexPtr)/INDEX_BLOCK_LENGTH + 1;
}
if ( is_string($ip) ) $ip = self::safeIp2long($ip);
//binary search to define the data
$l = 0;
$h = $this->totalBlocks;
$dataPtr = 0;
while ( $l <= $h ) {
$m = (($l + $h) >> 1);
$p = $this->firstIndexPtr + $m * INDEX_BLOCK_LENGTH;
$sip = self::getLong($this->dbBinStr, $p);
if ( $ip < $sip ) {
$h = $m - 1;
} else {
$eip = self::getLong($this->dbBinStr, $p + 4);
if ( $ip > $eip ) {
$l = $m + 1;
} else {
$dataPtr = self::getLong($this->dbBinStr, $p + 8);
break;
}
}
}
//not matched just stop it here
if ( $dataPtr == 0 ) return NULL;
//get the data
$dataLen = (($dataPtr >> 24) & 0xFF);
$dataPtr = ($dataPtr & 0x00FFFFFF);
return array(
'city_id' => self::getLong($this->dbBinStr, $dataPtr),
'region' => substr($this->dbBinStr, $dataPtr + 4, $dataLen - 4)
);
} | [
"public",
"function",
"memorySearch",
"(",
"$",
"ip",
")",
"{",
"//check and load the binary string for the first time",
"if",
"(",
"$",
"this",
"->",
"dbBinStr",
"==",
"NULL",
")",
"{",
"$",
"this",
"->",
"dbBinStr",
"=",
"file_get_contents",
"(",
"$",
"this",
... | all the db binary string will be loaded into memory
then search the memory only and this will a lot faster than disk base search
@Note:
invoke it once before put it to public invoke could make it thread safe
@param $ip | [
"all",
"the",
"db",
"binary",
"string",
"will",
"be",
"loaded",
"into",
"memory",
"then",
"search",
"the",
"memory",
"only",
"and",
"this",
"will",
"a",
"lot",
"faster",
"than",
"disk",
"base",
"search",
"@Note",
":",
"invoke",
"it",
"once",
"before",
"p... | train | https://github.com/zoujingli/ip2region/blob/944dc687304133027c4586a35ff78b57e56dd659/Ip2Region.php#L58-L106 |
zoujingli/ip2region | Ip2Region.php | Ip2Region.binarySearch | public function binarySearch( $ip )
{
//check and conver the ip address
if ( is_string($ip) ) $ip = self::safeIp2long($ip);
if ( $this->totalBlocks == 0 ) {
//check and open the original db file
if ( $this->dbFileHandler == NULL ) {
$this->dbFileHandler = fopen($this->dbFile, 'r');
if ( $this->dbFileHandler == false ) {
throw new Exception("Fail to open the db file {$this->dbFile}");
}
}
fseek($this->dbFileHandler, 0);
$superBlock = fread($this->dbFileHandler, 8);
$this->firstIndexPtr = self::getLong($superBlock, 0);
$this->lastIndexPtr = self::getLong($superBlock, 4);
$this->totalBlocks = ($this->lastIndexPtr-$this->firstIndexPtr)/INDEX_BLOCK_LENGTH + 1;
}
//binary search to define the data
$l = 0;
$h = $this->totalBlocks;
$dataPtr = 0;
while ( $l <= $h ) {
$m = (($l + $h) >> 1);
$p = $m * INDEX_BLOCK_LENGTH;
fseek($this->dbFileHandler, $this->firstIndexPtr + $p);
$buffer = fread($this->dbFileHandler, INDEX_BLOCK_LENGTH);
$sip = self::getLong($buffer, 0);
if ( $ip < $sip ) {
$h = $m - 1;
} else {
$eip = self::getLong($buffer, 4);
if ( $ip > $eip ) {
$l = $m + 1;
} else {
$dataPtr = self::getLong($buffer, 8);
break;
}
}
}
//not matched just stop it here
if ( $dataPtr == 0 ) return NULL;
//get the data
$dataLen = (($dataPtr >> 24) & 0xFF);
$dataPtr = ($dataPtr & 0x00FFFFFF);
fseek($this->dbFileHandler, $dataPtr);
$data = fread($this->dbFileHandler, $dataLen);
return array(
'city_id' => self::getLong($data, 0),
'region' => substr($data, 4)
);
} | php | public function binarySearch( $ip )
{
//check and conver the ip address
if ( is_string($ip) ) $ip = self::safeIp2long($ip);
if ( $this->totalBlocks == 0 ) {
//check and open the original db file
if ( $this->dbFileHandler == NULL ) {
$this->dbFileHandler = fopen($this->dbFile, 'r');
if ( $this->dbFileHandler == false ) {
throw new Exception("Fail to open the db file {$this->dbFile}");
}
}
fseek($this->dbFileHandler, 0);
$superBlock = fread($this->dbFileHandler, 8);
$this->firstIndexPtr = self::getLong($superBlock, 0);
$this->lastIndexPtr = self::getLong($superBlock, 4);
$this->totalBlocks = ($this->lastIndexPtr-$this->firstIndexPtr)/INDEX_BLOCK_LENGTH + 1;
}
//binary search to define the data
$l = 0;
$h = $this->totalBlocks;
$dataPtr = 0;
while ( $l <= $h ) {
$m = (($l + $h) >> 1);
$p = $m * INDEX_BLOCK_LENGTH;
fseek($this->dbFileHandler, $this->firstIndexPtr + $p);
$buffer = fread($this->dbFileHandler, INDEX_BLOCK_LENGTH);
$sip = self::getLong($buffer, 0);
if ( $ip < $sip ) {
$h = $m - 1;
} else {
$eip = self::getLong($buffer, 4);
if ( $ip > $eip ) {
$l = $m + 1;
} else {
$dataPtr = self::getLong($buffer, 8);
break;
}
}
}
//not matched just stop it here
if ( $dataPtr == 0 ) return NULL;
//get the data
$dataLen = (($dataPtr >> 24) & 0xFF);
$dataPtr = ($dataPtr & 0x00FFFFFF);
fseek($this->dbFileHandler, $dataPtr);
$data = fread($this->dbFileHandler, $dataLen);
return array(
'city_id' => self::getLong($data, 0),
'region' => substr($data, 4)
);
} | [
"public",
"function",
"binarySearch",
"(",
"$",
"ip",
")",
"{",
"//check and conver the ip address",
"if",
"(",
"is_string",
"(",
"$",
"ip",
")",
")",
"$",
"ip",
"=",
"self",
"::",
"safeIp2long",
"(",
"$",
"ip",
")",
";",
"if",
"(",
"$",
"this",
"->",
... | get the data block throught the specifield ip address or long ip numeric with binary search algorithm
@param ip
@return mixed Array or NULL for any error | [
"get",
"the",
"data",
"block",
"throught",
"the",
"specifield",
"ip",
"address",
"or",
"long",
"ip",
"numeric",
"with",
"binary",
"search",
"algorithm"
] | train | https://github.com/zoujingli/ip2region/blob/944dc687304133027c4586a35ff78b57e56dd659/Ip2Region.php#L114-L174 |
zoujingli/ip2region | Ip2Region.php | Ip2Region.btreeSearch | public function btreeSearch( $ip )
{
if ( is_string($ip) ) $ip = self::safeIp2long($ip);
//check and load the header
if ( $this->HeaderSip == NULL ) {
//check and open the original db file
if ( $this->dbFileHandler == NULL ) {
$this->dbFileHandler = fopen($this->dbFile, 'r');
if ( $this->dbFileHandler == false ) {
throw new Exception("Fail to open the db file {$this->dbFile}");
}
}
fseek($this->dbFileHandler, 8);
$buffer = fread($this->dbFileHandler, TOTAL_HEADER_LENGTH);
//fill the header
$idx = 0;
$this->HeaderSip = array();
$this->HeaderPtr = array();
for ( $i = 0; $i < TOTAL_HEADER_LENGTH; $i += 8 ) {
$startIp = self::getLong($buffer, $i);
$dataPtr = self::getLong($buffer, $i + 4);
if ( $dataPtr == 0 ) break;
$this->HeaderSip[] = $startIp;
$this->HeaderPtr[] = $dataPtr;
$idx++;
}
$this->headerLen = $idx;
}
//1. define the index block with the binary search
$l = 0; $h = $this->headerLen; $sptr = 0; $eptr = 0;
while ( $l <= $h ) {
$m = (($l + $h) >> 1);
//perfetc matched, just return it
if ( $ip == $this->HeaderSip[$m] ) {
if ( $m > 0 ) {
$sptr = $this->HeaderPtr[$m-1];
$eptr = $this->HeaderPtr[$m ];
} else {
$sptr = $this->HeaderPtr[$m ];
$eptr = $this->HeaderPtr[$m+1];
}
break;
}
//less then the middle value
if ( $ip < $this->HeaderSip[$m] ) {
if ( $m == 0 ) {
$sptr = $this->HeaderPtr[$m ];
$eptr = $this->HeaderPtr[$m+1];
break;
} else if ( $ip > $this->HeaderSip[$m-1] ) {
$sptr = $this->HeaderPtr[$m-1];
$eptr = $this->HeaderPtr[$m ];
break;
}
$h = $m - 1;
} else {
if ( $m == $this->headerLen - 1 ) {
$sptr = $this->HeaderPtr[$m-1];
$eptr = $this->HeaderPtr[$m ];
break;
} else if ( $ip <= $this->HeaderSip[$m+1] ) {
$sptr = $this->HeaderPtr[$m ];
$eptr = $this->HeaderPtr[$m+1];
break;
}
$l = $m + 1;
}
}
//match nothing just stop it
if ( $sptr == 0 ) return NULL;
//2. search the index blocks to define the data
$blockLen = $eptr - $sptr;
fseek($this->dbFileHandler, $sptr);
$index = fread($this->dbFileHandler, $blockLen + INDEX_BLOCK_LENGTH);
$dataptr = 0;
$l = 0; $h = $blockLen / INDEX_BLOCK_LENGTH;
while ( $l <= $h ) {
$m = (($l + $h) >> 1);
$p = (int)($m * INDEX_BLOCK_LENGTH);
$sip = self::getLong($index, $p);
if ( $ip < $sip ) {
$h = $m - 1;
} else {
$eip = self::getLong($index, $p + 4);
if ( $ip > $eip ) {
$l = $m + 1;
} else {
$dataptr = self::getLong($index, $p + 8);
break;
}
}
}
//not matched
if ( $dataptr == 0 ) return NULL;
//3. get the data
$dataLen = (($dataptr >> 24) & 0xFF);
$dataPtr = ($dataptr & 0x00FFFFFF);
fseek($this->dbFileHandler, $dataPtr);
$data = fread($this->dbFileHandler, $dataLen);
return array(
'city_id' => self::getLong($data, 0),
'region' => substr($data, 4)
);
} | php | public function btreeSearch( $ip )
{
if ( is_string($ip) ) $ip = self::safeIp2long($ip);
//check and load the header
if ( $this->HeaderSip == NULL ) {
//check and open the original db file
if ( $this->dbFileHandler == NULL ) {
$this->dbFileHandler = fopen($this->dbFile, 'r');
if ( $this->dbFileHandler == false ) {
throw new Exception("Fail to open the db file {$this->dbFile}");
}
}
fseek($this->dbFileHandler, 8);
$buffer = fread($this->dbFileHandler, TOTAL_HEADER_LENGTH);
//fill the header
$idx = 0;
$this->HeaderSip = array();
$this->HeaderPtr = array();
for ( $i = 0; $i < TOTAL_HEADER_LENGTH; $i += 8 ) {
$startIp = self::getLong($buffer, $i);
$dataPtr = self::getLong($buffer, $i + 4);
if ( $dataPtr == 0 ) break;
$this->HeaderSip[] = $startIp;
$this->HeaderPtr[] = $dataPtr;
$idx++;
}
$this->headerLen = $idx;
}
//1. define the index block with the binary search
$l = 0; $h = $this->headerLen; $sptr = 0; $eptr = 0;
while ( $l <= $h ) {
$m = (($l + $h) >> 1);
//perfetc matched, just return it
if ( $ip == $this->HeaderSip[$m] ) {
if ( $m > 0 ) {
$sptr = $this->HeaderPtr[$m-1];
$eptr = $this->HeaderPtr[$m ];
} else {
$sptr = $this->HeaderPtr[$m ];
$eptr = $this->HeaderPtr[$m+1];
}
break;
}
//less then the middle value
if ( $ip < $this->HeaderSip[$m] ) {
if ( $m == 0 ) {
$sptr = $this->HeaderPtr[$m ];
$eptr = $this->HeaderPtr[$m+1];
break;
} else if ( $ip > $this->HeaderSip[$m-1] ) {
$sptr = $this->HeaderPtr[$m-1];
$eptr = $this->HeaderPtr[$m ];
break;
}
$h = $m - 1;
} else {
if ( $m == $this->headerLen - 1 ) {
$sptr = $this->HeaderPtr[$m-1];
$eptr = $this->HeaderPtr[$m ];
break;
} else if ( $ip <= $this->HeaderSip[$m+1] ) {
$sptr = $this->HeaderPtr[$m ];
$eptr = $this->HeaderPtr[$m+1];
break;
}
$l = $m + 1;
}
}
//match nothing just stop it
if ( $sptr == 0 ) return NULL;
//2. search the index blocks to define the data
$blockLen = $eptr - $sptr;
fseek($this->dbFileHandler, $sptr);
$index = fread($this->dbFileHandler, $blockLen + INDEX_BLOCK_LENGTH);
$dataptr = 0;
$l = 0; $h = $blockLen / INDEX_BLOCK_LENGTH;
while ( $l <= $h ) {
$m = (($l + $h) >> 1);
$p = (int)($m * INDEX_BLOCK_LENGTH);
$sip = self::getLong($index, $p);
if ( $ip < $sip ) {
$h = $m - 1;
} else {
$eip = self::getLong($index, $p + 4);
if ( $ip > $eip ) {
$l = $m + 1;
} else {
$dataptr = self::getLong($index, $p + 8);
break;
}
}
}
//not matched
if ( $dataptr == 0 ) return NULL;
//3. get the data
$dataLen = (($dataptr >> 24) & 0xFF);
$dataPtr = ($dataptr & 0x00FFFFFF);
fseek($this->dbFileHandler, $dataPtr);
$data = fread($this->dbFileHandler, $dataLen);
return array(
'city_id' => self::getLong($data, 0),
'region' => substr($data, 4)
);
} | [
"public",
"function",
"btreeSearch",
"(",
"$",
"ip",
")",
"{",
"if",
"(",
"is_string",
"(",
"$",
"ip",
")",
")",
"$",
"ip",
"=",
"self",
"::",
"safeIp2long",
"(",
"$",
"ip",
")",
";",
"//check and load the header",
"if",
"(",
"$",
"this",
"->",
"Head... | get the data block associated with the specifield ip with b-tree search algorithm
@Note: not thread safe
@param ip
@return Mixed Array for NULL for any error | [
"get",
"the",
"data",
"block",
"associated",
"with",
"the",
"specifield",
"ip",
"with",
"b",
"-",
"tree",
"search",
"algorithm",
"@Note",
":",
"not",
"thread",
"safe"
] | train | https://github.com/zoujingli/ip2region/blob/944dc687304133027c4586a35ff78b57e56dd659/Ip2Region.php#L183-L302 |
zoujingli/ip2region | Ip2Region.php | Ip2Region.safeIp2long | public static function safeIp2long($ip)
{
$ip = ip2long($ip);
// convert signed int to unsigned int if on 32 bit operating system
if ($ip < 0 && PHP_INT_SIZE == 4) {
$ip = sprintf("%u", $ip);
}
return $ip;
} | php | public static function safeIp2long($ip)
{
$ip = ip2long($ip);
// convert signed int to unsigned int if on 32 bit operating system
if ($ip < 0 && PHP_INT_SIZE == 4) {
$ip = sprintf("%u", $ip);
}
return $ip;
} | [
"public",
"static",
"function",
"safeIp2long",
"(",
"$",
"ip",
")",
"{",
"$",
"ip",
"=",
"ip2long",
"(",
"$",
"ip",
")",
";",
"// convert signed int to unsigned int if on 32 bit operating system",
"if",
"(",
"$",
"ip",
"<",
"0",
"&&",
"PHP_INT_SIZE",
"==",
"4"... | safe self::safeIp2long function
@param ip | [
"safe",
"self",
"::",
"safeIp2long",
"function"
] | train | https://github.com/zoujingli/ip2region/blob/944dc687304133027c4586a35ff78b57e56dd659/Ip2Region.php#L310-L320 |
zoujingli/ip2region | Ip2Region.php | Ip2Region.getLong | public static function getLong( $b, $offset )
{
$val = (
(ord($b[$offset++])) |
(ord($b[$offset++]) << 8) |
(ord($b[$offset++]) << 16) |
(ord($b[$offset ]) << 24)
);
// convert signed int to unsigned int if on 32 bit operating system
if ($val < 0 && PHP_INT_SIZE == 4) {
$val = sprintf("%u", $val);
}
return $val;
} | php | public static function getLong( $b, $offset )
{
$val = (
(ord($b[$offset++])) |
(ord($b[$offset++]) << 8) |
(ord($b[$offset++]) << 16) |
(ord($b[$offset ]) << 24)
);
// convert signed int to unsigned int if on 32 bit operating system
if ($val < 0 && PHP_INT_SIZE == 4) {
$val = sprintf("%u", $val);
}
return $val;
} | [
"public",
"static",
"function",
"getLong",
"(",
"$",
"b",
",",
"$",
"offset",
")",
"{",
"$",
"val",
"=",
"(",
"(",
"ord",
"(",
"$",
"b",
"[",
"$",
"offset",
"++",
"]",
")",
")",
"|",
"(",
"ord",
"(",
"$",
"b",
"[",
"$",
"offset",
"++",
"]",... | read a long from a byte buffer
@param b
@param offset | [
"read",
"a",
"long",
"from",
"a",
"byte",
"buffer"
] | train | https://github.com/zoujingli/ip2region/blob/944dc687304133027c4586a35ff78b57e56dd659/Ip2Region.php#L330-L345 |
yooper/php-text-analysis | src/NGrams/NGramFactory.php | NGramFactory.create | static public function create(array $tokens, $nGramSize = self::BIGRAM, $separator = ' ') : array
{
$separatorLength = strlen($separator);
$length = count($tokens) - $nGramSize + 1;
if($length < 1) {
return [];
}
$ngrams = array_fill(0, $length, ''); // initialize the array
for($index = 0; $index < $length; $index++)
{
for($jindex = 0; $jindex < $nGramSize; $jindex++)
{
$ngrams[$index] .= $tokens[$index + $jindex];
//alterado a condição, pois não considera-se o tamanho do separador e sim a posição do ponteiro em relação ao tamanho do Ngram
if($jindex < $nGramSize - 1) {
$ngrams[$index] .= $separator;
}
}
}
return $ngrams;
} | php | static public function create(array $tokens, $nGramSize = self::BIGRAM, $separator = ' ') : array
{
$separatorLength = strlen($separator);
$length = count($tokens) - $nGramSize + 1;
if($length < 1) {
return [];
}
$ngrams = array_fill(0, $length, ''); // initialize the array
for($index = 0; $index < $length; $index++)
{
for($jindex = 0; $jindex < $nGramSize; $jindex++)
{
$ngrams[$index] .= $tokens[$index + $jindex];
//alterado a condição, pois não considera-se o tamanho do separador e sim a posição do ponteiro em relação ao tamanho do Ngram
if($jindex < $nGramSize - 1) {
$ngrams[$index] .= $separator;
}
}
}
return $ngrams;
} | [
"static",
"public",
"function",
"create",
"(",
"array",
"$",
"tokens",
",",
"$",
"nGramSize",
"=",
"self",
"::",
"BIGRAM",
",",
"$",
"separator",
"=",
"' '",
")",
":",
"array",
"{",
"$",
"separatorLength",
"=",
"strlen",
"(",
"$",
"separator",
")",
";"... | Generate Ngrams from the tokens
@param array $tokens
@param int $nGramSize
@return array return an array of the ngrams | [
"Generate",
"Ngrams",
"from",
"the",
"tokens"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/NGramFactory.php#L26-L47 |
yooper/php-text-analysis | src/NGrams/NGramFactory.php | NGramFactory.getFreq | static public function getFreq(array $ngrams, string $sep = ' ') : array
{
//getting the frequencies of the ngrams array and an array with no repetition
$ngramsUnique = array_count_values($ngrams);
//array to be the product of this function
$ngramsFinal = array();
//creates an array of tokens per ngram
$ngramsArray = self::ngramsAsArray($sep, $ngrams);
$ngramSize = count($ngramsArray[0]);
$tokens_frequencies = self::readFreq($sep, $ngrams);
$combo_frequencies = self::readCombFreq($sep, $ngrams);
//interate the array with no repeated ngrams
foreach ($ngramsUnique as $ngramString => $ngramFrequency) {
$ngramsFinal[$ngramString] = array($ngramFrequency); //putting into the final array an array of frequencies (first, the ngram frequency)
$ngramArray = explode($sep, $ngramString); //getting an array of tokens of the ngram
foreach ($ngramArray as $kToken => $token) { //iterating the array of tokens of the ngram
$ngramsFinal[$ngramString][$kToken+1] = $tokens_frequencies[$token][$kToken]; //getting the frequency of the token
if($ngramSize > 2) {
//getting the combined frequency of the tokens
for ($i = $kToken+1; $i < $ngramSize; $i++) {
$ngramsFinal[$ngramString][$ngramSize+$kToken+$i] = $combo_frequencies[$token.$sep.$ngramArray[$i]][$kToken][$i];
}
}
}
}
return $ngramsFinal;
} | php | static public function getFreq(array $ngrams, string $sep = ' ') : array
{
//getting the frequencies of the ngrams array and an array with no repetition
$ngramsUnique = array_count_values($ngrams);
//array to be the product of this function
$ngramsFinal = array();
//creates an array of tokens per ngram
$ngramsArray = self::ngramsAsArray($sep, $ngrams);
$ngramSize = count($ngramsArray[0]);
$tokens_frequencies = self::readFreq($sep, $ngrams);
$combo_frequencies = self::readCombFreq($sep, $ngrams);
//interate the array with no repeated ngrams
foreach ($ngramsUnique as $ngramString => $ngramFrequency) {
$ngramsFinal[$ngramString] = array($ngramFrequency); //putting into the final array an array of frequencies (first, the ngram frequency)
$ngramArray = explode($sep, $ngramString); //getting an array of tokens of the ngram
foreach ($ngramArray as $kToken => $token) { //iterating the array of tokens of the ngram
$ngramsFinal[$ngramString][$kToken+1] = $tokens_frequencies[$token][$kToken]; //getting the frequency of the token
if($ngramSize > 2) {
//getting the combined frequency of the tokens
for ($i = $kToken+1; $i < $ngramSize; $i++) {
$ngramsFinal[$ngramString][$ngramSize+$kToken+$i] = $combo_frequencies[$token.$sep.$ngramArray[$i]][$kToken][$i];
}
}
}
}
return $ngramsFinal;
} | [
"static",
"public",
"function",
"getFreq",
"(",
"array",
"$",
"ngrams",
",",
"string",
"$",
"sep",
"=",
"' '",
")",
":",
"array",
"{",
"//getting the frequencies of the ngrams array and an array with no repetition",
"$",
"ngramsUnique",
"=",
"array_count_values",
"(",
... | Set the frenquecies of the ngrams and their respective tokens
@param array $ngrams
@param string $sep
@return array return an array of the ngrams with frequencies | [
"Set",
"the",
"frenquecies",
"of",
"the",
"ngrams",
"and",
"their",
"respective",
"tokens"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/NGramFactory.php#L55-L90 |
yooper/php-text-analysis | src/NGrams/NGramFactory.php | NGramFactory.readFreq | static public function readFreq(string $sep, array $ngrams) : array
{
$ngrams = self::ngramsAsArray($sep, $ngrams);
$frequencies = array();
foreach ($ngrams as $ngram) {
foreach ($ngram as $pos => $token) {
if(isset($frequencies[$token][$pos])) { //checks if the token in that position was already counted
$frequencies[$token][$pos] += 1;
} else {
$frequencies[$token][$pos] = 1;
}
}
}
return $frequencies;
} | php | static public function readFreq(string $sep, array $ngrams) : array
{
$ngrams = self::ngramsAsArray($sep, $ngrams);
$frequencies = array();
foreach ($ngrams as $ngram) {
foreach ($ngram as $pos => $token) {
if(isset($frequencies[$token][$pos])) { //checks if the token in that position was already counted
$frequencies[$token][$pos] += 1;
} else {
$frequencies[$token][$pos] = 1;
}
}
}
return $frequencies;
} | [
"static",
"public",
"function",
"readFreq",
"(",
"string",
"$",
"sep",
",",
"array",
"$",
"ngrams",
")",
":",
"array",
"{",
"$",
"ngrams",
"=",
"self",
"::",
"ngramsAsArray",
"(",
"$",
"sep",
",",
"$",
"ngrams",
")",
";",
"$",
"frequencies",
"=",
"ar... | Counts the frequency of each token of an ngram array
@param string $sep
@param array $ngrams
@return array $frequencies Return an array of tokens with its frequencies by its positions | [
"Counts",
"the",
"frequency",
"of",
"each",
"token",
"of",
"an",
"ngram",
"array"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/NGramFactory.php#L98-L112 |
yooper/php-text-analysis | src/NGrams/NGramFactory.php | NGramFactory.readCombFreq | static public function readCombFreq(string $sep, array $ngrams) : array
{
$ngrams = self::ngramsAsArray($sep, $ngrams);
$frequencies = array();
foreach ($ngrams as $ngram) {
foreach ($ngram as $posToken => $token) {
for ($i = $posToken+1; $i < count($ngram); $i++) {
if(isset($frequencies[$token.$sep.$ngram[$i]][$posToken][$i])) { //checks if the combo already exists
$frequencies[$token.$sep.$ngram[$i]][$posToken][$i] += 1;
} else {
$frequencies[$token.$sep.$ngram[$i]][$posToken][$i] = 1;
}
}
}
}
return $frequencies;
} | php | static public function readCombFreq(string $sep, array $ngrams) : array
{
$ngrams = self::ngramsAsArray($sep, $ngrams);
$frequencies = array();
foreach ($ngrams as $ngram) {
foreach ($ngram as $posToken => $token) {
for ($i = $posToken+1; $i < count($ngram); $i++) {
if(isset($frequencies[$token.$sep.$ngram[$i]][$posToken][$i])) { //checks if the combo already exists
$frequencies[$token.$sep.$ngram[$i]][$posToken][$i] += 1;
} else {
$frequencies[$token.$sep.$ngram[$i]][$posToken][$i] = 1;
}
}
}
}
return $frequencies;
} | [
"static",
"public",
"function",
"readCombFreq",
"(",
"string",
"$",
"sep",
",",
"array",
"$",
"ngrams",
")",
":",
"array",
"{",
"$",
"ngrams",
"=",
"self",
"::",
"ngramsAsArray",
"(",
"$",
"sep",
",",
"$",
"ngrams",
")",
";",
"$",
"frequencies",
"=",
... | Counts the frequency of combo of tokens of an ngram array
@param string $sep
@param array $ngrams
@return array $frequencies Return an array of a combo of tokens with its frequencies by its positions | [
"Counts",
"the",
"frequency",
"of",
"combo",
"of",
"tokens",
"of",
"an",
"ngram",
"array"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/NGramFactory.php#L120-L137 |
yooper/php-text-analysis | src/NGrams/NGramFactory.php | NGramFactory.ngramsAsArray | static private function ngramsAsArray(string $sep, array $ngrams) : array {
$ngramsArray = array();
foreach($ngrams as $key => $ngram) {
$ngramsArray[] = explode($sep, $ngram);
}
return $ngramsArray;
} | php | static private function ngramsAsArray(string $sep, array $ngrams) : array {
$ngramsArray = array();
foreach($ngrams as $key => $ngram) {
$ngramsArray[] = explode($sep, $ngram);
}
return $ngramsArray;
} | [
"static",
"private",
"function",
"ngramsAsArray",
"(",
"string",
"$",
"sep",
",",
"array",
"$",
"ngrams",
")",
":",
"array",
"{",
"$",
"ngramsArray",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"ngrams",
"as",
"$",
"key",
"=>",
"$",
"ngram",
")... | Transform the ngram array to an array of their tokens
@param string $sep
@param array $ngrams
@return array $ngramsArray | [
"Transform",
"the",
"ngram",
"array",
"to",
"an",
"array",
"of",
"their",
"tokens"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/NGramFactory.php#L145-L151 |
yooper/php-text-analysis | src/Corpus/TextCorpus.php | TextCorpus.getDispersion | public function getDispersion(array $needles) : array
{
$found = array_fill_keys($needles, []);
foreach(array_keys($needles) as $needle)
{
$found[$needle] = $this->findAll($needle);
}
return $found;
} | php | public function getDispersion(array $needles) : array
{
$found = array_fill_keys($needles, []);
foreach(array_keys($needles) as $needle)
{
$found[$needle] = $this->findAll($needle);
}
return $found;
} | [
"public",
"function",
"getDispersion",
"(",
"array",
"$",
"needles",
")",
":",
"array",
"{",
"$",
"found",
"=",
"array_fill_keys",
"(",
"$",
"needles",
",",
"[",
"]",
")",
";",
"foreach",
"(",
"array_keys",
"(",
"$",
"needles",
")",
"as",
"$",
"needle"... | Return a list of positions that the needs were found in the text
@param array $needles
@return int[] | [
"Return",
"a",
"list",
"of",
"positions",
"that",
"the",
"needs",
"were",
"found",
"in",
"the",
"text"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Corpus/TextCorpus.php#L54-L62 |
yooper/php-text-analysis | src/Corpus/TextCorpus.php | TextCorpus.concordance | public function concordance(string $needle, int $contextLength = 20, bool $ignorecase = true, string $position = 'contain', bool $mark = false) : array
{
// temporary solution to handle unicode chars
$text = utf8_decode($this->text);
$text = trim(preg_replace('/[\s\t\n\r\s]+/', ' ', $text));
$needle = utf8_decode($needle);
$needleLength = strlen($needle);
$found = [];
$positions = $this->concordancePositions($text, $needle, $contextLength, $ignorecase, $position);
// Getting excerpts
foreach($positions as $needlePosition) {
//marking the term
$text_marked = ($mark) ? Text::markString($text, $needlePosition, $needleLength, ['{{','}}']) : $text;
$needleLength_marked = ($mark) ? $needleLength+4 : $needleLength;
$found[] = utf8_encode(Text::getExcerpt($text_marked, $needlePosition, $needleLength_marked, $contextLength));
}
return $found;
} | php | public function concordance(string $needle, int $contextLength = 20, bool $ignorecase = true, string $position = 'contain', bool $mark = false) : array
{
// temporary solution to handle unicode chars
$text = utf8_decode($this->text);
$text = trim(preg_replace('/[\s\t\n\r\s]+/', ' ', $text));
$needle = utf8_decode($needle);
$needleLength = strlen($needle);
$found = [];
$positions = $this->concordancePositions($text, $needle, $contextLength, $ignorecase, $position);
// Getting excerpts
foreach($positions as $needlePosition) {
//marking the term
$text_marked = ($mark) ? Text::markString($text, $needlePosition, $needleLength, ['{{','}}']) : $text;
$needleLength_marked = ($mark) ? $needleLength+4 : $needleLength;
$found[] = utf8_encode(Text::getExcerpt($text_marked, $needlePosition, $needleLength_marked, $contextLength));
}
return $found;
} | [
"public",
"function",
"concordance",
"(",
"string",
"$",
"needle",
",",
"int",
"$",
"contextLength",
"=",
"20",
",",
"bool",
"$",
"ignorecase",
"=",
"true",
",",
"string",
"$",
"position",
"=",
"'contain'",
",",
"bool",
"$",
"mark",
"=",
"false",
")",
... | See https://stackoverflow.com/questions/15737408/php-find-all-occurrences-of-a-substring-in-a-string
@param string $needle
@param int $contextLength The amount of space left and right of the found needle
@param bool $ignorecase
@param int $position. Available options: contain, begin, end, equal.
@param bool $mark Option to mark the needle
@return array | [
"See",
"https",
":",
"//",
"stackoverflow",
".",
"com",
"/",
"questions",
"/",
"15737408",
"/",
"php",
"-",
"find",
"-",
"all",
"-",
"occurrences",
"-",
"of",
"-",
"a",
"-",
"substring",
"-",
"in",
"-",
"a",
"-",
"string"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Corpus/TextCorpus.php#L83-L104 |
yooper/php-text-analysis | src/Corpus/TextCorpus.php | TextCorpus.concordancePositions | public function concordancePositions(string $text, string $needle, int $contextLength = 20, bool $ignorecase = true, string $position = 'contain') : array
{
$found = [];
$needleLength = strlen($needle);
$textLength = strlen($text);
$bufferLength = $needleLength + 2 * $contextLength;
// \p{L} or \p{Letter}: any kind of letter from any language.
$special_chars = "\/\-_\'";
$word_part = '\p{L}'.$special_chars;
switch ($position) {
case 'equal':
$pattern = "/(?<![$word_part])($needle)(?![$word_part])/";
break;
case 'begin':
$pattern = "/(?<![$word_part])($needle)[$special_chars]?[\p{L}]*|^($needle)/";
break;
case 'end':
$pattern = "/[\p{L}]*[$special_chars]?[\p{L}]*($needle)(?![$word_part])/";
break;
case 'contain':
$pattern = "/($needle)/";
break;
default:
$pattern = "/($needle)/";
break;
}
$case = $ignorecase ? 'i' : '';
preg_match_all($pattern.$case, $text, $matches, PREG_OFFSET_CAPTURE);
$positions = array_column($matches[1], 1);
return $positions;
} | php | public function concordancePositions(string $text, string $needle, int $contextLength = 20, bool $ignorecase = true, string $position = 'contain') : array
{
$found = [];
$needleLength = strlen($needle);
$textLength = strlen($text);
$bufferLength = $needleLength + 2 * $contextLength;
// \p{L} or \p{Letter}: any kind of letter from any language.
$special_chars = "\/\-_\'";
$word_part = '\p{L}'.$special_chars;
switch ($position) {
case 'equal':
$pattern = "/(?<![$word_part])($needle)(?![$word_part])/";
break;
case 'begin':
$pattern = "/(?<![$word_part])($needle)[$special_chars]?[\p{L}]*|^($needle)/";
break;
case 'end':
$pattern = "/[\p{L}]*[$special_chars]?[\p{L}]*($needle)(?![$word_part])/";
break;
case 'contain':
$pattern = "/($needle)/";
break;
default:
$pattern = "/($needle)/";
break;
}
$case = $ignorecase ? 'i' : '';
preg_match_all($pattern.$case, $text, $matches, PREG_OFFSET_CAPTURE);
$positions = array_column($matches[1], 1);
return $positions;
} | [
"public",
"function",
"concordancePositions",
"(",
"string",
"$",
"text",
",",
"string",
"$",
"needle",
",",
"int",
"$",
"contextLength",
"=",
"20",
",",
"bool",
"$",
"ignorecase",
"=",
"true",
",",
"string",
"$",
"position",
"=",
"'contain'",
")",
":",
... | Return all positions of the needle in the text according to the position of the needle in a word.
@param string $text
@param int $needle
@param int $contextLength The amount of space left and right of the found needle
@param bool $ignorecase
@param int $position. Available options: contain, begin, end, equal.
@return array | [
"Return",
"all",
"positions",
"of",
"the",
"needle",
"in",
"the",
"text",
"according",
"to",
"the",
"position",
"of",
"the",
"needle",
"in",
"a",
"word",
"."
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Corpus/TextCorpus.php#L115-L150 |
yooper/php-text-analysis | src/Corpus/TextCorpus.php | TextCorpus.percentage | public function percentage(string $needle) : float
{
$freqDist = freq_dist($this->getTokens());
return $freqDist->getKeyValuesByFrequency()[$needle] / $freqDist->getTotalTokens();
} | php | public function percentage(string $needle) : float
{
$freqDist = freq_dist($this->getTokens());
return $freqDist->getKeyValuesByFrequency()[$needle] / $freqDist->getTotalTokens();
} | [
"public",
"function",
"percentage",
"(",
"string",
"$",
"needle",
")",
":",
"float",
"{",
"$",
"freqDist",
"=",
"freq_dist",
"(",
"$",
"this",
"->",
"getTokens",
"(",
")",
")",
";",
"return",
"$",
"freqDist",
"->",
"getKeyValuesByFrequency",
"(",
")",
"[... | Get percentage of times the needle shows up in the text
@param string $needle
@return float | [
"Get",
"percentage",
"of",
"times",
"the",
"needle",
"shows",
"up",
"in",
"the",
"text"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Corpus/TextCorpus.php#L157-L161 |
yooper/php-text-analysis | src/Corpus/TextCorpus.php | TextCorpus.count | public function count(string $needle) : int
{
return substr_count(strtolower($this->getText()), strtolower($needle));
} | php | public function count(string $needle) : int
{
return substr_count(strtolower($this->getText()), strtolower($needle));
} | [
"public",
"function",
"count",
"(",
"string",
"$",
"needle",
")",
":",
"int",
"{",
"return",
"substr_count",
"(",
"strtolower",
"(",
"$",
"this",
"->",
"getText",
"(",
")",
")",
",",
"strtolower",
"(",
"$",
"needle",
")",
")",
";",
"}"
] | Performs a case insensitive search for the needle
@param string $needle
@return int | [
"Performs",
"a",
"case",
"insensitive",
"search",
"for",
"the",
"needle"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Corpus/TextCorpus.php#L168-L171 |
yooper/php-text-analysis | src/Corpus/TextCorpus.php | TextCorpus.findAll | public function findAll(string $needle) : array
{
$lastPos = 0;
$positions = [];
$needle = strtolower($needle);
$text = strtolower($this->getText());
$needleLength = strlen($needle);
while (($lastPos = stripos($text, $needle, $lastPos))!== false)
{
$positions[] = $lastPos;
$lastPos += $needleLength;
}
return $positions;
} | php | public function findAll(string $needle) : array
{
$lastPos = 0;
$positions = [];
$needle = strtolower($needle);
$text = strtolower($this->getText());
$needleLength = strlen($needle);
while (($lastPos = stripos($text, $needle, $lastPos))!== false)
{
$positions[] = $lastPos;
$lastPos += $needleLength;
}
return $positions;
} | [
"public",
"function",
"findAll",
"(",
"string",
"$",
"needle",
")",
":",
"array",
"{",
"$",
"lastPos",
"=",
"0",
";",
"$",
"positions",
"=",
"[",
"]",
";",
"$",
"needle",
"=",
"strtolower",
"(",
"$",
"needle",
")",
";",
"$",
"text",
"=",
"strtolowe... | Return all the position of the needle found in the text
@param string $needle
@return array | [
"Return",
"all",
"the",
"position",
"of",
"the",
"needle",
"found",
"in",
"the",
"text"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Corpus/TextCorpus.php#L178-L191 |
yooper/php-text-analysis | src/Comparisons/JaroWinklerComparison.php | JaroWinklerComparison.similarity | public function similarity($text1, $text2)
{
if($text1 === $text2) {
return 1.0;
}
// ensure that s1 is shorter than or same length as s2
if (strlen($text1) > strlen($text2)) {
$tmp = $text1;
$text1 = $text2;
$text2 = $tmp;
}
$strLen1 = strlen($text1);
$strLen2 = strlen($text2);
$maxDistance = (int)$strLen2 / 2;
$commonCounter = 0; // count of common characters
$transpositionCounter = 0; // count of transpositions
$prevPosition = -1;
for ($index = 0; $index < $strLen1; $index++)
{
$char = $text1[$index];
// init inner loop
$jindex = max(0, $index - $maxDistance);
while($jindex < min($strLen2, $index + $maxDistance))
{
if ($char === $text2[$jindex]) {
$commonCounter++; // common char found
if ($prevPosition != -1 && $jindex < $prevPosition) {
$transpositionCounter++;
}
$prevPosition = $jindex;
break;
}
$jindex++;
}
}
// no common characters between strings
if($commonCounter === 0) {
return 0.0;
}
// first compute the score
$score = (
($commonCounter / $strLen1) +
($commonCounter / $strLen2) +
(($commonCounter - $transpositionCounter) / $commonCounter)) / 3.0;
//init values
$prefixLength = 0; // length of prefix
$last = min($this->minPrefixLength, $strLen1);
while($prefixLength < $last && $text1[$prefixLength] == $text2[$prefixLength])
{
$prefixLength++;
}
return $score + (($prefixLength * (1 - $score)) / 10);
} | php | public function similarity($text1, $text2)
{
if($text1 === $text2) {
return 1.0;
}
// ensure that s1 is shorter than or same length as s2
if (strlen($text1) > strlen($text2)) {
$tmp = $text1;
$text1 = $text2;
$text2 = $tmp;
}
$strLen1 = strlen($text1);
$strLen2 = strlen($text2);
$maxDistance = (int)$strLen2 / 2;
$commonCounter = 0; // count of common characters
$transpositionCounter = 0; // count of transpositions
$prevPosition = -1;
for ($index = 0; $index < $strLen1; $index++)
{
$char = $text1[$index];
// init inner loop
$jindex = max(0, $index - $maxDistance);
while($jindex < min($strLen2, $index + $maxDistance))
{
if ($char === $text2[$jindex]) {
$commonCounter++; // common char found
if ($prevPosition != -1 && $jindex < $prevPosition) {
$transpositionCounter++;
}
$prevPosition = $jindex;
break;
}
$jindex++;
}
}
// no common characters between strings
if($commonCounter === 0) {
return 0.0;
}
// first compute the score
$score = (
($commonCounter / $strLen1) +
($commonCounter / $strLen2) +
(($commonCounter - $transpositionCounter) / $commonCounter)) / 3.0;
//init values
$prefixLength = 0; // length of prefix
$last = min($this->minPrefixLength, $strLen1);
while($prefixLength < $last && $text1[$prefixLength] == $text2[$prefixLength])
{
$prefixLength++;
}
return $score + (($prefixLength * (1 - $score)) / 10);
} | [
"public",
"function",
"similarity",
"(",
"$",
"text1",
",",
"$",
"text2",
")",
"{",
"if",
"(",
"$",
"text1",
"===",
"$",
"text2",
")",
"{",
"return",
"1.0",
";",
"}",
"// ensure that s1 is shorter than or same length as s2",
"if",
"(",
"strlen",
"(",
"$",
... | Return the similarity using the JaroWinkler algorithm
@param string $text1
@param string $text2
@return real | [
"Return",
"the",
"similarity",
"using",
"the",
"JaroWinkler",
"algorithm"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Comparisons/JaroWinklerComparison.php#L30-L89 |
yooper/php-text-analysis | src/Analysis/Summarize/Simple.php | Simple.summarize | public function summarize(array $wordTokens, array $sentenceTokens) : array
{
$tokenCounts = array_count_values($wordTokens);
$scoreKeepers = [];
for($index = 0; $index < count($sentenceTokens); $index++)
{
$scoreKeepers[] = new ScoreKeeper($sentenceTokens[$index], $index);
}
foreach($tokenCounts as $token => $freq)
{
foreach($scoreKeepers as $sentenceKeeper)
{
if(strpos($sentenceKeeper->getToken(), $token) !== false) {
$sentenceKeeper->addToScore($freq);
}
}
}
usort($scoreKeepers, 'score_keeper_sort');
return $scoreKeepers;
} | php | public function summarize(array $wordTokens, array $sentenceTokens) : array
{
$tokenCounts = array_count_values($wordTokens);
$scoreKeepers = [];
for($index = 0; $index < count($sentenceTokens); $index++)
{
$scoreKeepers[] = new ScoreKeeper($sentenceTokens[$index], $index);
}
foreach($tokenCounts as $token => $freq)
{
foreach($scoreKeepers as $sentenceKeeper)
{
if(strpos($sentenceKeeper->getToken(), $token) !== false) {
$sentenceKeeper->addToScore($freq);
}
}
}
usort($scoreKeepers, 'score_keeper_sort');
return $scoreKeepers;
} | [
"public",
"function",
"summarize",
"(",
"array",
"$",
"wordTokens",
",",
"array",
"$",
"sentenceTokens",
")",
":",
"array",
"{",
"$",
"tokenCounts",
"=",
"array_count_values",
"(",
"$",
"wordTokens",
")",
";",
"$",
"scoreKeepers",
"=",
"[",
"]",
";",
"for"... | Returns each sentenced scored.
@param array $wordTokens
@param array $sentenceTokens
@return array | [
"Returns",
"each",
"sentenced",
"scored",
"."
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Analysis/Summarize/Simple.php#L20-L42 |
yooper/php-text-analysis | src/Collections/DocumentArrayCollection.php | DocumentArrayCollection.applyExtract | public function applyExtract(IExtractStrategy $extract)
{
/* @var $document \TextAnalysis\Documents\TokensDocument */
$found = [];
foreach($this->documents as $document)
{
$found = array_merge($document->applyExtract($extract), $found);
}
return $found;
} | php | public function applyExtract(IExtractStrategy $extract)
{
/* @var $document \TextAnalysis\Documents\TokensDocument */
$found = [];
foreach($this->documents as $document)
{
$found = array_merge($document->applyExtract($extract), $found);
}
return $found;
} | [
"public",
"function",
"applyExtract",
"(",
"IExtractStrategy",
"$",
"extract",
")",
"{",
"/* @var $document \\TextAnalysis\\Documents\\TokensDocument */",
"$",
"found",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"documents",
"as",
"$",
"document",
")",
... | Apply extract to the document to pull out all the points of
interest
@param IExtractStrategy $extract
@return array | [
"Apply",
"extract",
"to",
"the",
"document",
"to",
"pull",
"out",
"all",
"the",
"points",
"of",
"interest"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Collections/DocumentArrayCollection.php#L82-L91 |
yooper/php-text-analysis | src/Comparisons/HammingDistanceComparison.php | HammingDistanceComparison.distance | public function distance($text1, $text2)
{
$distance = 0;
$strLength = strlen($text1);
for($index = 0; $index < $strLength; $index++)
{
if($text1[$index] != $text2[$index]) {
$distance++;
}
}
return $distance;
} | php | public function distance($text1, $text2)
{
$distance = 0;
$strLength = strlen($text1);
for($index = 0; $index < $strLength; $index++)
{
if($text1[$index] != $text2[$index]) {
$distance++;
}
}
return $distance;
} | [
"public",
"function",
"distance",
"(",
"$",
"text1",
",",
"$",
"text2",
")",
"{",
"$",
"distance",
"=",
"0",
";",
"$",
"strLength",
"=",
"strlen",
"(",
"$",
"text1",
")",
";",
"for",
"(",
"$",
"index",
"=",
"0",
";",
"$",
"index",
"<",
"$",
"st... | Return the hamming distance, expects the strings to be equal length
@param string $text1
@param string $text2
@return int | [
"Return",
"the",
"hamming",
"distance",
"expects",
"the",
"strings",
"to",
"be",
"equal",
"length"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Comparisons/HammingDistanceComparison.php#L20-L31 |
yooper/php-text-analysis | src/Console/Commands/StopWordsCommand.php | StopWordsCommand.toArray | protected function toArray(array $stopWords)
{
$data = [];
foreach($stopWords as $key => $value)
{
$data[] = ['token' => utf8_encode($key), 'freq' => $value];
}
return $data;
} | php | protected function toArray(array $stopWords)
{
$data = [];
foreach($stopWords as $key => $value)
{
$data[] = ['token' => utf8_encode($key), 'freq' => $value];
}
return $data;
} | [
"protected",
"function",
"toArray",
"(",
"array",
"$",
"stopWords",
")",
"{",
"$",
"data",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"stopWords",
"as",
"$",
"key",
"=>",
"$",
"value",
")",
"{",
"$",
"data",
"[",
"]",
"=",
"[",
"'token'",
"=>",
"ut... | So you can easily serialize the data to json
@return array | [
"So",
"you",
"can",
"easily",
"serialize",
"the",
"data",
"to",
"json"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Console/Commands/StopWordsCommand.php#L76-L84 |
yooper/php-text-analysis | src/Stemmers/LancasterStemmer.php | LancasterStemmer.indexRules | protected function indexRules(array $rules)
{
$this->indexedRules = array();
foreach($rules as $rule){
if(isset($this->indexedRules[$rule[self::LOOKUP_CHAR]])){
$this->indexedRules[$rule[self::LOOKUP_CHAR]][] = $rule;
} else {
$this->indexedRules[$rule[self::LOOKUP_CHAR]] = array($rule);
}
}
} | php | protected function indexRules(array $rules)
{
$this->indexedRules = array();
foreach($rules as $rule){
if(isset($this->indexedRules[$rule[self::LOOKUP_CHAR]])){
$this->indexedRules[$rule[self::LOOKUP_CHAR]][] = $rule;
} else {
$this->indexedRules[$rule[self::LOOKUP_CHAR]] = array($rule);
}
}
} | [
"protected",
"function",
"indexRules",
"(",
"array",
"$",
"rules",
")",
"{",
"$",
"this",
"->",
"indexedRules",
"=",
"array",
"(",
")",
";",
"foreach",
"(",
"$",
"rules",
"as",
"$",
"rule",
")",
"{",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"ind... | Creates an chained hashtable using the lookup char as the key
@param array $rules | [
"Creates",
"an",
"chained",
"hashtable",
"using",
"the",
"lookup",
"char",
"as",
"the",
"key"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Stemmers/LancasterStemmer.php#L65-L76 |
yooper/php-text-analysis | src/Stemmers/LancasterStemmer.php | LancasterStemmer.stem | public function stem($word)
{
if(empty(trim($word))) {
return null;
}
$this->originalToken = $word;
//only iterate out loop if a rule is applied
do {
$ruleApplied = false;
$lookupChar = $word[strlen($word)-1];
//check that the last character is in the index, if not return the origin token
if(!array_key_exists($lookupChar, $this->indexedRules)){
return $word;
}
foreach($this->indexedRules[$lookupChar] as $rule)
{
if(strrpos($word, substr($rule[self::ENDING_STRING],-1)) ===
(strlen($word)-strlen($rule[self::ENDING_STRING]))){
if(!empty($rule[self::INTACT_FLAG])){
if($this->originalToken == $word &&
$this->isAcceptable($word, (int)$rule[self::REMOVE_TOTAL])){
$word = $this->applyRule($word, $rule);
$ruleApplied = true;
if($rule[self::CONTINUE_FLAG] === '.'){
return $word;
}
break;
}
} elseif($this->isAcceptable($word, (int)$rule[self::REMOVE_TOTAL])){
$word = $this->applyRule($word, $rule);
$ruleApplied = true;
if($rule[self::CONTINUE_FLAG] === '.'){
return $word;
}
break;
}
} else {
$ruleApplied = false;
}
}
} while($ruleApplied);
return $word;
} | php | public function stem($word)
{
if(empty(trim($word))) {
return null;
}
$this->originalToken = $word;
//only iterate out loop if a rule is applied
do {
$ruleApplied = false;
$lookupChar = $word[strlen($word)-1];
//check that the last character is in the index, if not return the origin token
if(!array_key_exists($lookupChar, $this->indexedRules)){
return $word;
}
foreach($this->indexedRules[$lookupChar] as $rule)
{
if(strrpos($word, substr($rule[self::ENDING_STRING],-1)) ===
(strlen($word)-strlen($rule[self::ENDING_STRING]))){
if(!empty($rule[self::INTACT_FLAG])){
if($this->originalToken == $word &&
$this->isAcceptable($word, (int)$rule[self::REMOVE_TOTAL])){
$word = $this->applyRule($word, $rule);
$ruleApplied = true;
if($rule[self::CONTINUE_FLAG] === '.'){
return $word;
}
break;
}
} elseif($this->isAcceptable($word, (int)$rule[self::REMOVE_TOTAL])){
$word = $this->applyRule($word, $rule);
$ruleApplied = true;
if($rule[self::CONTINUE_FLAG] === '.'){
return $word;
}
break;
}
} else {
$ruleApplied = false;
}
}
} while($ruleApplied);
return $word;
} | [
"public",
"function",
"stem",
"(",
"$",
"word",
")",
"{",
"if",
"(",
"empty",
"(",
"trim",
"(",
"$",
"word",
")",
")",
")",
"{",
"return",
"null",
";",
"}",
"$",
"this",
"->",
"originalToken",
"=",
"$",
"word",
";",
"//only iterate out loop if a rule i... | Performs a Lancaster stem on the giving word
@param string $word The word that gets stemmed
@return string|null The stemmed word | [
"Performs",
"a",
"Lancaster",
"stem",
"on",
"the",
"giving",
"word"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Stemmers/LancasterStemmer.php#L83-L134 |
yooper/php-text-analysis | src/Stemmers/LancasterStemmer.php | LancasterStemmer.applyRule | protected function applyRule($word, $rule)
{
return substr_replace($word, $rule[self::APPEND_STRING], strlen($word) - $rule[self::REMOVE_TOTAL]);
} | php | protected function applyRule($word, $rule)
{
return substr_replace($word, $rule[self::APPEND_STRING], strlen($word) - $rule[self::REMOVE_TOTAL]);
} | [
"protected",
"function",
"applyRule",
"(",
"$",
"word",
",",
"$",
"rule",
")",
"{",
"return",
"substr_replace",
"(",
"$",
"word",
",",
"$",
"rule",
"[",
"self",
"::",
"APPEND_STRING",
"]",
",",
"strlen",
"(",
"$",
"word",
")",
"-",
"$",
"rule",
"[",
... | Apply the lancaster rule and return the altered string.
@param string $word word the rule is being applied on
@param array $rule An associative array containing all the data elements for applying to the word | [
"Apply",
"the",
"lancaster",
"rule",
"and",
"return",
"the",
"altered",
"string",
"."
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Stemmers/LancasterStemmer.php#L141-L144 |
yooper/php-text-analysis | src/Stemmers/LancasterStemmer.php | LancasterStemmer.isAcceptable | protected function isAcceptable($word, $removeTotal)
{
$length = strlen($word) - $removeTotal;
if($this->vowelChecker->isVowel($word, 0)&& $length >= 2){
return true;
} elseif($length >= 3 &&
($this->vowelChecker->isVowel($word, 1) || $this->vowelChecker->isVowel($word, 2))) {
return true;
}
return false;
} | php | protected function isAcceptable($word, $removeTotal)
{
$length = strlen($word) - $removeTotal;
if($this->vowelChecker->isVowel($word, 0)&& $length >= 2){
return true;
} elseif($length >= 3 &&
($this->vowelChecker->isVowel($word, 1) || $this->vowelChecker->isVowel($word, 2))) {
return true;
}
return false;
} | [
"protected",
"function",
"isAcceptable",
"(",
"$",
"word",
",",
"$",
"removeTotal",
")",
"{",
"$",
"length",
"=",
"strlen",
"(",
"$",
"word",
")",
"-",
"$",
"removeTotal",
";",
"if",
"(",
"$",
"this",
"->",
"vowelChecker",
"->",
"isVowel",
"(",
"$",
... | Check if a word is acceptable
@param string $word The word under test
@param int $removeTotal The number of characters to remove from the suffix
@return boolean True is the word is acceptable | [
"Check",
"if",
"a",
"word",
"is",
"acceptable"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Stemmers/LancasterStemmer.php#L152-L162 |
yooper/php-text-analysis | src/Stemmers/LookupStemmer.php | LookupStemmer.stem | public function stem($token)
{
if(array_key_exists($token, $this->dictionary)){
return $this->dictionary[$token];
}
return $token;
} | php | public function stem($token)
{
if(array_key_exists($token, $this->dictionary)){
return $this->dictionary[$token];
}
return $token;
} | [
"public",
"function",
"stem",
"(",
"$",
"token",
")",
"{",
"if",
"(",
"array_key_exists",
"(",
"$",
"token",
",",
"$",
"this",
"->",
"dictionary",
")",
")",
"{",
"return",
"$",
"this",
"->",
"dictionary",
"[",
"$",
"token",
"]",
";",
"}",
"return",
... | Returns a token's stemmed root
@param string $token
@return string | [
"Returns",
"a",
"token",
"s",
"stemmed",
"root"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Stemmers/LookupStemmer.php#L27-L33 |
yooper/php-text-analysis | src/Tokenizers/FixedLengthTokenizer.php | FixedLengthTokenizer.tokenize | public function tokenize($string)
{
if(!$this->length) {
return array(substr($string, $this->startPosition));
} else {
return array(substr($string, $this->startPosition, $this->length));
}
} | php | public function tokenize($string)
{
if(!$this->length) {
return array(substr($string, $this->startPosition));
} else {
return array(substr($string, $this->startPosition, $this->length));
}
} | [
"public",
"function",
"tokenize",
"(",
"$",
"string",
")",
"{",
"if",
"(",
"!",
"$",
"this",
"->",
"length",
")",
"{",
"return",
"array",
"(",
"substr",
"(",
"$",
"string",
",",
"$",
"this",
"->",
"startPosition",
")",
")",
";",
"}",
"else",
"{",
... | Return array with single element
@param string $string
@return array | [
"Return",
"array",
"with",
"single",
"element"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Tokenizers/FixedLengthTokenizer.php#L31-L38 |
yooper/php-text-analysis | src/Comparisons/LevenshteinComparison.php | LevenshteinComparison.distance | public function distance($text1, $text2)
{
return levenshtein($text1, $text2, $this->insertCost, $this->replaceCost, $this->deleteCost);
} | php | public function distance($text1, $text2)
{
return levenshtein($text1, $text2, $this->insertCost, $this->replaceCost, $this->deleteCost);
} | [
"public",
"function",
"distance",
"(",
"$",
"text1",
",",
"$",
"text2",
")",
"{",
"return",
"levenshtein",
"(",
"$",
"text1",
",",
"$",
"text2",
",",
"$",
"this",
"->",
"insertCost",
",",
"$",
"this",
"->",
"replaceCost",
",",
"$",
"this",
"->",
"del... | Return the levenshtein distance, default costs of 1 applied
@param string $text1
@param string $text2
@return int | [
"Return",
"the",
"levenshtein",
"distance",
"default",
"costs",
"of",
"1",
"applied"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Comparisons/LevenshteinComparison.php#L38-L41 |
yooper/php-text-analysis | src/NGrams/StatisticFacade.php | StatisticFacade.calculate | public static function calculate(array $ngrams, string $measure, int $nGramSize = 2) : array
{
$totalNgrams = array_sum(array_column($ngrams, 0));
return array_map( function($item) use($measure, $totalNgrams, $nGramSize) {
if ($nGramSize == 2) {
return Statistic2D::$measure($item, $totalNgrams);
} elseif ($nGramSize == 3) {
return Statistic3D::$measure($item, $totalNgrams);
} else {
throw new \Exception("Size of the ngram informed invalid", 1);
}
}, $ngrams);
} | php | public static function calculate(array $ngrams, string $measure, int $nGramSize = 2) : array
{
$totalNgrams = array_sum(array_column($ngrams, 0));
return array_map( function($item) use($measure, $totalNgrams, $nGramSize) {
if ($nGramSize == 2) {
return Statistic2D::$measure($item, $totalNgrams);
} elseif ($nGramSize == 3) {
return Statistic3D::$measure($item, $totalNgrams);
} else {
throw new \Exception("Size of the ngram informed invalid", 1);
}
}, $ngrams);
} | [
"public",
"static",
"function",
"calculate",
"(",
"array",
"$",
"ngrams",
",",
"string",
"$",
"measure",
",",
"int",
"$",
"nGramSize",
"=",
"2",
")",
":",
"array",
"{",
"$",
"totalNgrams",
"=",
"array_sum",
"(",
"array_column",
"(",
"$",
"ngrams",
",",
... | Calculate the statistic for an ngram array
@param array $ngrams Array of ngrams
@param string $measure Name of the statistic measure
@param int $nGramSize Size of the ngrams
@return array Return the ngram array with the statistic values | [
"Calculate",
"the",
"statistic",
"for",
"an",
"ngram",
"array"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/StatisticFacade.php#L24-L36 |
yooper/php-text-analysis | src/Comparisons/LongestCommonSubstringComparison.php | LongestCommonSubstringComparison.distance | public function distance($text1, $text2)
{
return max(mb_strlen($text1), mb_strlen($text2)) - mb_strlen($this->similarity($text1, $text2));
} | php | public function distance($text1, $text2)
{
return max(mb_strlen($text1), mb_strlen($text2)) - mb_strlen($this->similarity($text1, $text2));
} | [
"public",
"function",
"distance",
"(",
"$",
"text1",
",",
"$",
"text2",
")",
"{",
"return",
"max",
"(",
"mb_strlen",
"(",
"$",
"text1",
")",
",",
"mb_strlen",
"(",
"$",
"text2",
")",
")",
"-",
"mb_strlen",
"(",
"$",
"this",
"->",
"similarity",
"(",
... | Returns the string length of the longest common substring (LCS)
@param string $text1
@param string $text2
@return int | [
"Returns",
"the",
"string",
"length",
"of",
"the",
"longest",
"common",
"substring",
"(",
"LCS",
")"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Comparisons/LongestCommonSubstringComparison.php#L42-L45 |
yooper/php-text-analysis | src/Comparisons/LongestCommonSubstringComparison.php | LongestCommonSubstringComparison.similarity | public function similarity($text1, $text2)
{
if($this->useCache && !isset($this->cache[$text2])) {
$this->cache[$text2] = Text::getAllSubStrings($text2);
}
$intersection = array_intersect( Text::getAllSubStrings($text1), ($this->useCache) ? $this->cache[$text2] : Text::getAllSubStrings($text2));
$max = 0;
$lcs = '';
foreach($intersection as $substr)
{
$strlen = mb_strlen($substr);
if( $strlen > $max) {
$max = $strlen;
$lcs = $substr;
}
}
return $lcs;
} | php | public function similarity($text1, $text2)
{
if($this->useCache && !isset($this->cache[$text2])) {
$this->cache[$text2] = Text::getAllSubStrings($text2);
}
$intersection = array_intersect( Text::getAllSubStrings($text1), ($this->useCache) ? $this->cache[$text2] : Text::getAllSubStrings($text2));
$max = 0;
$lcs = '';
foreach($intersection as $substr)
{
$strlen = mb_strlen($substr);
if( $strlen > $max) {
$max = $strlen;
$lcs = $substr;
}
}
return $lcs;
} | [
"public",
"function",
"similarity",
"(",
"$",
"text1",
",",
"$",
"text2",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"useCache",
"&&",
"!",
"isset",
"(",
"$",
"this",
"->",
"cache",
"[",
"$",
"text2",
"]",
")",
")",
"{",
"$",
"this",
"->",
"cache",
... | Returns the Longest common substring
@param string $text1
@param string $text2
@return string | [
"Returns",
"the",
"Longest",
"common",
"substring"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Comparisons/LongestCommonSubstringComparison.php#L53-L71 |
yooper/php-text-analysis | src/NGrams/Statistic3D.php | Statistic3D.tmi | static public function tmi(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$tmi3 = 0;
if($var['jointFrequency']) {
$tmi3 += $var['jointFrequency']/$totalNgrams * self::computePMI( $var['jointFrequency'], $var['e111'] )/ log(2);
}
if($var['n112']) {
$tmi3 += $var['n112']/$totalNgrams * self::computePMI( $var['n112'], $var['e112'] )/ log(2);
}
if($var['n121']) {
$tmi3 += $var['n121']/$totalNgrams * self::computePMI( $var['n121'], $var['e121'] )/ log(2);
}
if($var['n122']) {
$tmi3 += $var['n122']/$totalNgrams * self::computePMI( $var['n122'], $var['e122'] )/ log(2);
}
if($var['n211']) {
$tmi3 += $var['n211']/$totalNgrams * self::computePMI( $var['n211'], $var['e211'] )/ log(2);
}
if($var['n212']) {
$tmi3 += $var['n212']/$totalNgrams * self::computePMI( $var['n212'], $var['e212'] )/ log(2);
}
if($var['n221']) {
$tmi3 += $var['n221']/$totalNgrams * self::computePMI( $var['n221'], $var['e221'] )/ log(2);
}
if($var['n222']) {
$tmi3 += $var['n222']/$totalNgrams * self::computePMI( $var['n222'], $var['e222'] )/ log(2);
}
return $tmi3;
} | php | static public function tmi(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$tmi3 = 0;
if($var['jointFrequency']) {
$tmi3 += $var['jointFrequency']/$totalNgrams * self::computePMI( $var['jointFrequency'], $var['e111'] )/ log(2);
}
if($var['n112']) {
$tmi3 += $var['n112']/$totalNgrams * self::computePMI( $var['n112'], $var['e112'] )/ log(2);
}
if($var['n121']) {
$tmi3 += $var['n121']/$totalNgrams * self::computePMI( $var['n121'], $var['e121'] )/ log(2);
}
if($var['n122']) {
$tmi3 += $var['n122']/$totalNgrams * self::computePMI( $var['n122'], $var['e122'] )/ log(2);
}
if($var['n211']) {
$tmi3 += $var['n211']/$totalNgrams * self::computePMI( $var['n211'], $var['e211'] )/ log(2);
}
if($var['n212']) {
$tmi3 += $var['n212']/$totalNgrams * self::computePMI( $var['n212'], $var['e212'] )/ log(2);
}
if($var['n221']) {
$tmi3 += $var['n221']/$totalNgrams * self::computePMI( $var['n221'], $var['e221'] )/ log(2);
}
if($var['n222']) {
$tmi3 += $var['n222']/$totalNgrams * self::computePMI( $var['n222'], $var['e222'] )/ log(2);
}
return $tmi3;
} | [
"static",
"public",
"function",
"tmi",
"(",
"array",
"$",
"ngram",
",",
"int",
"$",
"totalNgrams",
")",
":",
"float",
"{",
"$",
"var",
"=",
"self",
"::",
"setStatVariables",
"(",
"$",
"ngram",
",",
"$",
"totalNgrams",
")",
";",
"$",
"tmi3",
"=",
"0",... | Calculate the true mutual information value for trigrams
@param array $ngram Array of ngrams with frequencies
@return float Return the calculated value | [
"Calculate",
"the",
"true",
"mutual",
"information",
"value",
"for",
"trigrams"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/Statistic3D.php#L17-L58 |
yooper/php-text-analysis | src/NGrams/Statistic3D.php | Statistic3D.ll | static public function ll(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$logLikelihood = 0;
if($var['jointFrequency']) {
$logLikelihood += $var['jointFrequency'] * self::computePMI ( $var['jointFrequency'], $var['e111'] );
}
if($var['n112']) {
$logLikelihood += $var['n112'] * self::computePMI( $var['n112'], $var['e112'] );
}
if($var['n121']) {
$logLikelihood += $var['n121'] * self::computePMI( $var['n121'], $var['e121'] );
}
if($var['n122']) {
$logLikelihood += $var['n122'] * self::computePMI( $var['n122'], $var['e122'] );
}
if($var['n211']) {
$logLikelihood += $var['n211'] * self::computePMI( $var['n211'], $var['e211'] );
}
if($var['n212']) {
$logLikelihood += $var['n212'] * self::computePMI( $var['n212'], $var['e212'] );
}
if($var['n221']) {
$logLikelihood += $var['n221'] * self::computePMI( $var['n221'], $var['e221'] );
}
if($var['n222']) {
$logLikelihood += $var['n222'] * self::computePMI( $var['n222'], $var['e222'] );
}
return ($logLikelihood * 2);
} | php | static public function ll(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$logLikelihood = 0;
if($var['jointFrequency']) {
$logLikelihood += $var['jointFrequency'] * self::computePMI ( $var['jointFrequency'], $var['e111'] );
}
if($var['n112']) {
$logLikelihood += $var['n112'] * self::computePMI( $var['n112'], $var['e112'] );
}
if($var['n121']) {
$logLikelihood += $var['n121'] * self::computePMI( $var['n121'], $var['e121'] );
}
if($var['n122']) {
$logLikelihood += $var['n122'] * self::computePMI( $var['n122'], $var['e122'] );
}
if($var['n211']) {
$logLikelihood += $var['n211'] * self::computePMI( $var['n211'], $var['e211'] );
}
if($var['n212']) {
$logLikelihood += $var['n212'] * self::computePMI( $var['n212'], $var['e212'] );
}
if($var['n221']) {
$logLikelihood += $var['n221'] * self::computePMI( $var['n221'], $var['e221'] );
}
if($var['n222']) {
$logLikelihood += $var['n222'] * self::computePMI( $var['n222'], $var['e222'] );
}
return ($logLikelihood * 2);
} | [
"static",
"public",
"function",
"ll",
"(",
"array",
"$",
"ngram",
",",
"int",
"$",
"totalNgrams",
")",
":",
"float",
"{",
"$",
"var",
"=",
"self",
"::",
"setStatVariables",
"(",
"$",
"ngram",
",",
"$",
"totalNgrams",
")",
";",
"$",
"logLikelihood",
"="... | Calculate the Loglikelihood coefficient for trigrams
@param array $ngram Array of ngrams with frequencies
@return float Return the calculated value | [
"Calculate",
"the",
"Loglikelihood",
"coefficient",
"for",
"trigrams"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/Statistic3D.php#L65-L104 |
yooper/php-text-analysis | src/NGrams/Statistic3D.php | Statistic3D.setStatVariables | static public function setStatVariables(array $ngram, int $totalNgrams)
{
$var['jointFrequency'] = $ngram[0]; # n111 whole trigram freq
$var['firstFrequency'] = $ngram[1]; # n1pp single freq of first word
$var['secondFrequency'] = $ngram[2]; # np1p single freq of second word
$var['thirdFrequency'] = $ngram[3]; # npp1 single freq of third word
$var['firstSecondFrequency'] = $ngram[4]; # n11p freq of first with the second word
$var['firstThirdFrequency'] = $ngram[5]; # n1p1 freq of second with the third word
$var['secondThirdFrequency'] = $ngram[6]; # np11 freq of first with the third word
$var['n112'] = $var['firstSecondFrequency'] - $var['jointFrequency'];
$var['n211'] = $var['secondThirdFrequency'] - $var['jointFrequency'];
$var['n212'] = $var['secondFrequency'] - $var['jointFrequency'] - $var['n112'] - $var['n211'];
$var['n121'] = $var['firstThirdFrequency'] - $var['jointFrequency'];
$var['n122'] = $var['firstFrequency'] - $var['jointFrequency'] - $var['n112'] - $var['n121'];
$var['n221'] = $var['thirdFrequency'] - $var['jointFrequency'] - $var['n211'] - $var['n121'];
$var['nppp'] = $totalNgrams;
$var['n222'] = $var['nppp'] - ($var['jointFrequency'] + $var['n112'] + $var['n121'] + $var['n122'] + $var['n211'] + $var['n212'] + $var['n221']);
$var['n2pp'] = $var['nppp'] - $var['firstFrequency'];
$var['np2p'] = $var['nppp'] - $var['secondFrequency'];
$var['npp2'] = $var['nppp'] - $var['thirdFrequency'];
$var['e111'] = $var['firstFrequency'] * $var['secondFrequency'] * $var['thirdFrequency']/($var['nppp']**2);
$var['e112'] = $var['firstFrequency'] * $var['secondFrequency'] * $var['npp2']/($var['nppp']**2);
$var['e121'] = $var['firstFrequency'] * $var['np2p'] * $var['thirdFrequency']/($var['nppp']**2);
$var['e122'] = $var['firstFrequency'] * $var['np2p'] * $var['npp2']/($var['nppp']**2);
$var['e211'] = $var['n2pp'] * $var['secondFrequency'] * $var['thirdFrequency']/($var['nppp']**2);
$var['e212'] = $var['n2pp'] * $var['secondFrequency'] * $var['npp2']/($var['nppp']**2);
$var['e221'] = $var['n2pp'] * $var['np2p'] * $var['thirdFrequency']/($var['nppp']**2);
$var['e222'] = $var['n2pp'] * $var['np2p'] * $var['npp2']/($var['nppp']**2);
return $var;
} | php | static public function setStatVariables(array $ngram, int $totalNgrams)
{
$var['jointFrequency'] = $ngram[0]; # n111 whole trigram freq
$var['firstFrequency'] = $ngram[1]; # n1pp single freq of first word
$var['secondFrequency'] = $ngram[2]; # np1p single freq of second word
$var['thirdFrequency'] = $ngram[3]; # npp1 single freq of third word
$var['firstSecondFrequency'] = $ngram[4]; # n11p freq of first with the second word
$var['firstThirdFrequency'] = $ngram[5]; # n1p1 freq of second with the third word
$var['secondThirdFrequency'] = $ngram[6]; # np11 freq of first with the third word
$var['n112'] = $var['firstSecondFrequency'] - $var['jointFrequency'];
$var['n211'] = $var['secondThirdFrequency'] - $var['jointFrequency'];
$var['n212'] = $var['secondFrequency'] - $var['jointFrequency'] - $var['n112'] - $var['n211'];
$var['n121'] = $var['firstThirdFrequency'] - $var['jointFrequency'];
$var['n122'] = $var['firstFrequency'] - $var['jointFrequency'] - $var['n112'] - $var['n121'];
$var['n221'] = $var['thirdFrequency'] - $var['jointFrequency'] - $var['n211'] - $var['n121'];
$var['nppp'] = $totalNgrams;
$var['n222'] = $var['nppp'] - ($var['jointFrequency'] + $var['n112'] + $var['n121'] + $var['n122'] + $var['n211'] + $var['n212'] + $var['n221']);
$var['n2pp'] = $var['nppp'] - $var['firstFrequency'];
$var['np2p'] = $var['nppp'] - $var['secondFrequency'];
$var['npp2'] = $var['nppp'] - $var['thirdFrequency'];
$var['e111'] = $var['firstFrequency'] * $var['secondFrequency'] * $var['thirdFrequency']/($var['nppp']**2);
$var['e112'] = $var['firstFrequency'] * $var['secondFrequency'] * $var['npp2']/($var['nppp']**2);
$var['e121'] = $var['firstFrequency'] * $var['np2p'] * $var['thirdFrequency']/($var['nppp']**2);
$var['e122'] = $var['firstFrequency'] * $var['np2p'] * $var['npp2']/($var['nppp']**2);
$var['e211'] = $var['n2pp'] * $var['secondFrequency'] * $var['thirdFrequency']/($var['nppp']**2);
$var['e212'] = $var['n2pp'] * $var['secondFrequency'] * $var['npp2']/($var['nppp']**2);
$var['e221'] = $var['n2pp'] * $var['np2p'] * $var['thirdFrequency']/($var['nppp']**2);
$var['e222'] = $var['n2pp'] * $var['np2p'] * $var['npp2']/($var['nppp']**2);
return $var;
} | [
"static",
"public",
"function",
"setStatVariables",
"(",
"array",
"$",
"ngram",
",",
"int",
"$",
"totalNgrams",
")",
"{",
"$",
"var",
"[",
"'jointFrequency'",
"]",
"=",
"$",
"ngram",
"[",
"0",
"]",
";",
"# n111 whole trigram freq",
"$",
"var",
"[",
"'first... | Sets variables to calculate the statistic measures
@return array $var Return the array with the variables | [
"Sets",
"variables",
"to",
"calculate",
"the",
"statistic",
"measures"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/Statistic3D.php#L122-L155 |
yooper/php-text-analysis | src/Tokenizers/PennTreeBankTokenizer.php | PennTreeBankTokenizer.execute | protected function execute($string)
{
foreach ($this->patternsAndReplacements as $patternAndReplacement) {
$tmp = preg_replace("/".$patternAndReplacement->pattern."/s", $patternAndReplacement->replacement, $string);
if ($tmp === null) {
InvalidExpression::invalidRegex($patternAndReplacement->pattern, $patternAndReplacement->replacement);
} else {
$string = $tmp;
}
}
return $string;
} | php | protected function execute($string)
{
foreach ($this->patternsAndReplacements as $patternAndReplacement) {
$tmp = preg_replace("/".$patternAndReplacement->pattern."/s", $patternAndReplacement->replacement, $string);
if ($tmp === null) {
InvalidExpression::invalidRegex($patternAndReplacement->pattern, $patternAndReplacement->replacement);
} else {
$string = $tmp;
}
}
return $string;
} | [
"protected",
"function",
"execute",
"(",
"$",
"string",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"patternsAndReplacements",
"as",
"$",
"patternAndReplacement",
")",
"{",
"$",
"tmp",
"=",
"preg_replace",
"(",
"\"/\"",
".",
"$",
"patternAndReplacement",
"->"... | Handles the data processing
@param string $string The raw text to get parsed | [
"Handles",
"the",
"data",
"processing"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Tokenizers/PennTreeBankTokenizer.php#L37-L49 |
yooper/php-text-analysis | src/Tokenizers/PennTreeBankTokenizer.php | PennTreeBankTokenizer.initPatternReplacement | protected function initPatternReplacement()
{
$this->addPatternAndReplacement('^"', '``');
$this->addPatternAndReplacement("\([ ([{<]\)","$1 `` ");
$this->addPatternAndReplacement("\.\.\."," ... ");
$this->addPatternAndReplacement("([,;:@#$%&])", " $1 ");
$this->addPatternAndReplacement("([^.])([.])([])}>\"\']*)[ ]*$","\${1} \${2}\${3}");
$this->addPatternAndReplacement("[?!]"," $0 ");
$this->addPatternAndReplacement("[][(){}<>]"," $0 ");
$this->addPatternAndReplacement("--"," -- ");
$this->addPatternAndReplacement("\""," '' ");
$this->addPatternAndReplacement("([^'])' ","\${1} ' ");
$this->addPatternAndReplacement("'([sSmMdD]) "," '\${1} ");
$this->addPatternAndReplacement("'ll "," 'll ");
$this->addPatternAndReplacement("'re "," 're ");
$this->addPatternAndReplacement("'ve "," 've ");
$this->addPatternAndReplacement("n't "," n't ");
$this->addPatternAndReplacement("'LL "," 'LL ");
$this->addPatternAndReplacement("'RE "," 'RE ");
$this->addPatternAndReplacement("'VE "," 'VE ");
$this->addPatternAndReplacement("N'T "," N'T ");
$this->addPatternAndReplacement(" ([Cc])annot "," \1an not ");
$this->addPatternAndReplacement(" ([Dd])'ye "," \${1}' ye ");
$this->addPatternAndReplacement(" ([Gg])imme "," \${1}im me ");
$this->addPatternAndReplacement(" ([Gg])onna "," \${1}on na ");
$this->addPatternAndReplacement(" ([Gg])otta "," \${1}ot ta ");
$this->addPatternAndReplacement(" ([Ll])emme "," \${1}em me ");
$this->addPatternAndReplacement(" ([Mm])ore'n "," \${1}ore 'n ");
$this->addPatternAndReplacement(" '([Tt])is "," '\${1} is ");
$this->addPatternAndReplacement(" '([Tt])was "," '\${1} was ");
$this->addPatternAndReplacement(" ([Ww])anna "," \${1}an na ");
$this->addPatternAndReplacement(" *"," ");
$this->addPatternAndReplacement("^ *","");
} | php | protected function initPatternReplacement()
{
$this->addPatternAndReplacement('^"', '``');
$this->addPatternAndReplacement("\([ ([{<]\)","$1 `` ");
$this->addPatternAndReplacement("\.\.\."," ... ");
$this->addPatternAndReplacement("([,;:@#$%&])", " $1 ");
$this->addPatternAndReplacement("([^.])([.])([])}>\"\']*)[ ]*$","\${1} \${2}\${3}");
$this->addPatternAndReplacement("[?!]"," $0 ");
$this->addPatternAndReplacement("[][(){}<>]"," $0 ");
$this->addPatternAndReplacement("--"," -- ");
$this->addPatternAndReplacement("\""," '' ");
$this->addPatternAndReplacement("([^'])' ","\${1} ' ");
$this->addPatternAndReplacement("'([sSmMdD]) "," '\${1} ");
$this->addPatternAndReplacement("'ll "," 'll ");
$this->addPatternAndReplacement("'re "," 're ");
$this->addPatternAndReplacement("'ve "," 've ");
$this->addPatternAndReplacement("n't "," n't ");
$this->addPatternAndReplacement("'LL "," 'LL ");
$this->addPatternAndReplacement("'RE "," 'RE ");
$this->addPatternAndReplacement("'VE "," 'VE ");
$this->addPatternAndReplacement("N'T "," N'T ");
$this->addPatternAndReplacement(" ([Cc])annot "," \1an not ");
$this->addPatternAndReplacement(" ([Dd])'ye "," \${1}' ye ");
$this->addPatternAndReplacement(" ([Gg])imme "," \${1}im me ");
$this->addPatternAndReplacement(" ([Gg])onna "," \${1}on na ");
$this->addPatternAndReplacement(" ([Gg])otta "," \${1}ot ta ");
$this->addPatternAndReplacement(" ([Ll])emme "," \${1}em me ");
$this->addPatternAndReplacement(" ([Mm])ore'n "," \${1}ore 'n ");
$this->addPatternAndReplacement(" '([Tt])is "," '\${1} is ");
$this->addPatternAndReplacement(" '([Tt])was "," '\${1} was ");
$this->addPatternAndReplacement(" ([Ww])anna "," \${1}an na ");
$this->addPatternAndReplacement(" *"," ");
$this->addPatternAndReplacement("^ *","");
} | [
"protected",
"function",
"initPatternReplacement",
"(",
")",
"{",
"$",
"this",
"->",
"addPatternAndReplacement",
"(",
"'^\"'",
",",
"'``'",
")",
";",
"$",
"this",
"->",
"addPatternAndReplacement",
"(",
"\"\\([ ([{<]\\)\"",
",",
"\"$1 `` \"",
")",
";",
"$",
"this... | Initializes the patterns and replacements/ | [
"Initializes",
"the",
"patterns",
"and",
"replacements",
"/"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Tokenizers/PennTreeBankTokenizer.php#L54-L91 |
yooper/php-text-analysis | src/Tokenizers/PennTreeBankTokenizer.php | PennTreeBankTokenizer.addPatternAndReplacement | protected function addPatternAndReplacement($pattern, $replacement)
{
$instance = new \stdClass();
$instance->pattern = $pattern;
$instance->replacement = $replacement;
$this->patternsAndReplacements[] = $instance;
} | php | protected function addPatternAndReplacement($pattern, $replacement)
{
$instance = new \stdClass();
$instance->pattern = $pattern;
$instance->replacement = $replacement;
$this->patternsAndReplacements[] = $instance;
} | [
"protected",
"function",
"addPatternAndReplacement",
"(",
"$",
"pattern",
",",
"$",
"replacement",
")",
"{",
"$",
"instance",
"=",
"new",
"\\",
"stdClass",
"(",
")",
";",
"$",
"instance",
"->",
"pattern",
"=",
"$",
"pattern",
";",
"$",
"instance",
"->",
... | Appends \stdClass objects to the internal data structure $patternsAndReplacements
@param string $pattern
@param string $replacement | [
"Appends",
"\\",
"stdClass",
"objects",
"to",
"the",
"internal",
"data",
"structure",
"$patternsAndReplacements"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Tokenizers/PennTreeBankTokenizer.php#L98-L104 |
yooper/php-text-analysis | src/Adapters/PspellAdapter.php | PspellAdapter.suggest | public function suggest($word)
{
if (!pspell_check($this->pSpell, $word)) {
return pspell_suggest($this->pSpell, $word);
}
else {
return [$word];
}
} | php | public function suggest($word)
{
if (!pspell_check($this->pSpell, $word)) {
return pspell_suggest($this->pSpell, $word);
}
else {
return [$word];
}
} | [
"public",
"function",
"suggest",
"(",
"$",
"word",
")",
"{",
"if",
"(",
"!",
"pspell_check",
"(",
"$",
"this",
"->",
"pSpell",
",",
"$",
"word",
")",
")",
"{",
"return",
"pspell_suggest",
"(",
"$",
"this",
"->",
"pSpell",
",",
"$",
"word",
")",
";"... | Use pspell to get word suggestions
@param string $word
@return array | [
"Use",
"pspell",
"to",
"get",
"word",
"suggestions"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Adapters/PspellAdapter.php#L25-L33 |
yooper/php-text-analysis | src/Collocations/CollocationFinder.php | CollocationFinder.getCollocations | public function getCollocations()
{
$nGramTokens = ngrams($this->tokens, $this->nGramSize);
return freq_dist($nGramTokens)->getKeyValuesByFrequency();
} | php | public function getCollocations()
{
$nGramTokens = ngrams($this->tokens, $this->nGramSize);
return freq_dist($nGramTokens)->getKeyValuesByFrequency();
} | [
"public",
"function",
"getCollocations",
"(",
")",
"{",
"$",
"nGramTokens",
"=",
"ngrams",
"(",
"$",
"this",
"->",
"tokens",
",",
"$",
"this",
"->",
"nGramSize",
")",
";",
"return",
"freq_dist",
"(",
"$",
"nGramTokens",
")",
"->",
"getKeyValuesByFrequency",
... | Returns a naive implementation of collocations
@return array | [
"Returns",
"a",
"naive",
"implementation",
"of",
"collocations"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Collocations/CollocationFinder.php#L33-L37 |
yooper/php-text-analysis | src/Collocations/CollocationFinder.php | CollocationFinder.getCollocationsByPmi | public function getCollocationsByPmi()
{
$nGramFreqDist = freq_dist(ngrams($this->tokens, $this->nGramSize));
$unigramsFreqDist = freq_dist($this->tokens);
$dataSet = [];
foreach($nGramFreqDist->getKeys() as $nGramToken)
{
$tokens = explode(" ", $nGramToken);
$tally = 1;
foreach($tokens as $unigramToken)
{
$tally *= $unigramsFreqDist->getKeyValuesByWeight()[$unigramToken];
}
// get probabilities of all tokens
$dataSet[$nGramToken] = log($nGramFreqDist->getKeyValuesByWeight()[$nGramToken] / $tally );
}
arsort($dataSet);
return $dataSet;
} | php | public function getCollocationsByPmi()
{
$nGramFreqDist = freq_dist(ngrams($this->tokens, $this->nGramSize));
$unigramsFreqDist = freq_dist($this->tokens);
$dataSet = [];
foreach($nGramFreqDist->getKeys() as $nGramToken)
{
$tokens = explode(" ", $nGramToken);
$tally = 1;
foreach($tokens as $unigramToken)
{
$tally *= $unigramsFreqDist->getKeyValuesByWeight()[$unigramToken];
}
// get probabilities of all tokens
$dataSet[$nGramToken] = log($nGramFreqDist->getKeyValuesByWeight()[$nGramToken] / $tally );
}
arsort($dataSet);
return $dataSet;
} | [
"public",
"function",
"getCollocationsByPmi",
"(",
")",
"{",
"$",
"nGramFreqDist",
"=",
"freq_dist",
"(",
"ngrams",
"(",
"$",
"this",
"->",
"tokens",
",",
"$",
"this",
"->",
"nGramSize",
")",
")",
";",
"$",
"unigramsFreqDist",
"=",
"freq_dist",
"(",
"$",
... | Compute the Pointwise Mutual Information on the collocations
@return array | [
"Compute",
"the",
"Pointwise",
"Mutual",
"Information",
"on",
"the",
"collocations"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Collocations/CollocationFinder.php#L43-L63 |
yooper/php-text-analysis | src/Corpus/NameCorpus.php | NameCorpus.getPdo | public function getPdo() : PDO
{
if(empty($this->pdo)) {
$this->pdo = new PDO("sqlite:".$this->getDir().$this->getFileNames()[0]);
}
return $this->pdo;
} | php | public function getPdo() : PDO
{
if(empty($this->pdo)) {
$this->pdo = new PDO("sqlite:".$this->getDir().$this->getFileNames()[0]);
}
return $this->pdo;
} | [
"public",
"function",
"getPdo",
"(",
")",
":",
"PDO",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"pdo",
")",
")",
"{",
"$",
"this",
"->",
"pdo",
"=",
"new",
"PDO",
"(",
"\"sqlite:\"",
".",
"$",
"this",
"->",
"getDir",
"(",
")",
".",
"$",
... | Return the raw pdo
@return PDO | [
"Return",
"the",
"raw",
"pdo"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Corpus/NameCorpus.php#L137-L143 |
yooper/php-text-analysis | src/Tokenizers/GeneralTokenizer.php | GeneralTokenizer.strTokenWrapper | protected function strTokenWrapper($string)
{
$token = strtok($string, $this->tokenExpression);
$tokens = array();
while ($token !== false) {
// avoid tokenizing white spaces
if(!empty(trim($token))) {
$tokens[] = $token;
}
$token = strtok($this->tokenExpression);
}
return $tokens;
} | php | protected function strTokenWrapper($string)
{
$token = strtok($string, $this->tokenExpression);
$tokens = array();
while ($token !== false) {
// avoid tokenizing white spaces
if(!empty(trim($token))) {
$tokens[] = $token;
}
$token = strtok($this->tokenExpression);
}
return $tokens;
} | [
"protected",
"function",
"strTokenWrapper",
"(",
"$",
"string",
")",
"{",
"$",
"token",
"=",
"strtok",
"(",
"$",
"string",
",",
"$",
"this",
"->",
"tokenExpression",
")",
";",
"$",
"tokens",
"=",
"array",
"(",
")",
";",
"while",
"(",
"$",
"token",
"!... | Use the php function strtok to Tokenize simple string
@internal
@return array | [
"Use",
"the",
"php",
"function",
"strtok",
"to",
"Tokenize",
"simple",
"string"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Tokenizers/GeneralTokenizer.php#L40-L53 |
yooper/php-text-analysis | src/Adapters/EnchantAdapter.php | EnchantAdapter.suggest | public function suggest($word)
{
if(!enchant_dict_check($this->enchantBroker, $word)) {
return enchant_dict_suggest($this->enchantBroker, $word);
} else {
return [$word];
}
} | php | public function suggest($word)
{
if(!enchant_dict_check($this->enchantBroker, $word)) {
return enchant_dict_suggest($this->enchantBroker, $word);
} else {
return [$word];
}
} | [
"public",
"function",
"suggest",
"(",
"$",
"word",
")",
"{",
"if",
"(",
"!",
"enchant_dict_check",
"(",
"$",
"this",
"->",
"enchantBroker",
",",
"$",
"word",
")",
")",
"{",
"return",
"enchant_dict_suggest",
"(",
"$",
"this",
"->",
"enchantBroker",
",",
"... | Use enchant to get word suggestions
@param string $word
@return array | [
"Use",
"enchant",
"to",
"get",
"word",
"suggestions"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Adapters/EnchantAdapter.php#L26-L33 |
yooper/php-text-analysis | src/Corpus/WordnetCorpus.php | WordnetCorpus.getExceptionsMap | public function getExceptionsMap()
{
if(empty($this->exceptionsMap)) {
$fileExtToPos = array_flip($this->getPosFileMaps());
foreach($this->getExceptionFileNames() as $fileName )
{
$pos = $fileExtToPos[substr($fileName, 0, -4)];
$fh = fopen($this->getDir().$fileName,'r');
if(!$fh) {
throw new RuntimeException("wordnet file missing {$fileName}");
}
while($line = fgets($fh))
{
if($line[0] === ' ') {
continue;
}
$this->exceptionsMap[] = $this->getExceptionMapFromString(trim($line), $pos);
}
fclose($fh);
}
}
return $this->exceptionsMap;
} | php | public function getExceptionsMap()
{
if(empty($this->exceptionsMap)) {
$fileExtToPos = array_flip($this->getPosFileMaps());
foreach($this->getExceptionFileNames() as $fileName )
{
$pos = $fileExtToPos[substr($fileName, 0, -4)];
$fh = fopen($this->getDir().$fileName,'r');
if(!$fh) {
throw new RuntimeException("wordnet file missing {$fileName}");
}
while($line = fgets($fh))
{
if($line[0] === ' ') {
continue;
}
$this->exceptionsMap[] = $this->getExceptionMapFromString(trim($line), $pos);
}
fclose($fh);
}
}
return $this->exceptionsMap;
} | [
"public",
"function",
"getExceptionsMap",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"exceptionsMap",
")",
")",
"{",
"$",
"fileExtToPos",
"=",
"array_flip",
"(",
"$",
"this",
"->",
"getPosFileMaps",
"(",
")",
")",
";",
"foreach",
"(",
"... | Returns the list of exception spellings
@return ExceptionMap[]
@throws RuntimeException | [
"Returns",
"the",
"list",
"of",
"exception",
"spellings"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Corpus/WordnetCorpus.php#L94-L119 |
yooper/php-text-analysis | src/Corpus/WordnetCorpus.php | WordnetCorpus.getSynsetByOffsetAndPos | public function getSynsetByOffsetAndPos($synsetOffset, $pos)
{
// check if the synset has already been cached
if(isset($this->synsets[$pos.$synsetOffset])) {
return $this->synsets[$pos.$synsetOffset];
}
$fileName = "data.{$this->posFileMaps[$pos]}";
if(!in_array($fileName, $this->getDataFileNames())) {
throw new RuntimeException("That is not a correct wordnet file {$fileName}");
} elseif(!file_exists($this->getDir().$fileName)) {
throw new RuntimeException("Wordnet file missing {$fileName}");
}
$fh = fopen($this->getDir().$fileName,'r');
if(!$fh) {
throw new RuntimeException("Could not open wordnet file for reading {$fileName}");
}
if(fseek($fh, $synsetOffset) === -1) {
throw new RuntimeException("Could not seek to {$synsetOffset} in {$fileName}");
}
$line = trim(fgets($fh));
fclose($fh);
return $this->getSynsetFromString($line);
} | php | public function getSynsetByOffsetAndPos($synsetOffset, $pos)
{
// check if the synset has already been cached
if(isset($this->synsets[$pos.$synsetOffset])) {
return $this->synsets[$pos.$synsetOffset];
}
$fileName = "data.{$this->posFileMaps[$pos]}";
if(!in_array($fileName, $this->getDataFileNames())) {
throw new RuntimeException("That is not a correct wordnet file {$fileName}");
} elseif(!file_exists($this->getDir().$fileName)) {
throw new RuntimeException("Wordnet file missing {$fileName}");
}
$fh = fopen($this->getDir().$fileName,'r');
if(!$fh) {
throw new RuntimeException("Could not open wordnet file for reading {$fileName}");
}
if(fseek($fh, $synsetOffset) === -1) {
throw new RuntimeException("Could not seek to {$synsetOffset} in {$fileName}");
}
$line = trim(fgets($fh));
fclose($fh);
return $this->getSynsetFromString($line);
} | [
"public",
"function",
"getSynsetByOffsetAndPos",
"(",
"$",
"synsetOffset",
",",
"$",
"pos",
")",
"{",
"// check if the synset has already been cached",
"if",
"(",
"isset",
"(",
"$",
"this",
"->",
"synsets",
"[",
"$",
"pos",
".",
"$",
"synsetOffset",
"]",
")",
... | Opens the raw data file and reads the synsets in
@param int $synsetOffset
@param string $pos Part of speech
@return Synset | [
"Opens",
"the",
"raw",
"data",
"file",
"and",
"reads",
"the",
"synsets",
"in"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Corpus/WordnetCorpus.php#L171-L198 |
yooper/php-text-analysis | src/Corpus/WordnetCorpus.php | WordnetCorpus.getSynsetFromString | public function getSynsetFromString($line)
{
$row = str_getcsv($line," ");
$synset = new Synset((int)$row[0], $row[2]);
$synset->setDefinition(trim(substr($line, strpos($line,"|")+1)));
for($index = 0; $index < (int)$row[3]; $index++)
{
$synset->addWord($row[4 + $index*2], $row[5 + $index*2]);
}
$startIdx = 5 + $row[3] * 2;
$endIdx = ($row[$startIdx-1] * 4) + $startIdx;
$embeddedSynsets = array_splice($row, $startIdx, $endIdx);
for($index = 0; $index < $row[$startIdx-1] * 4; $index+=4)
{
$linkedSynset = new Synset($embeddedSynsets[$index+1], $embeddedSynsets[$index+2]);
$linkedSynset->setPtrSymbols([$embeddedSynsets[$index]]);
// set src and target word indexes
if((int)$embeddedSynsets[$index+3] === 0) {
$linkedSynset->setSrcWordIdx(0);
$linkedSynset->setTargetWordIdx(0);
} else {
$linkedSynset->setSrcWordIdx((int)($embeddedSynsets[$index+3]) % 100);
$linkedSynset->setTargetWordIdx((int) floor($embeddedSynsets[$index+3] / 100));
}
$synset->addLinkedSynset($linkedSynset);
}
return $synset;
} | php | public function getSynsetFromString($line)
{
$row = str_getcsv($line," ");
$synset = new Synset((int)$row[0], $row[2]);
$synset->setDefinition(trim(substr($line, strpos($line,"|")+1)));
for($index = 0; $index < (int)$row[3]; $index++)
{
$synset->addWord($row[4 + $index*2], $row[5 + $index*2]);
}
$startIdx = 5 + $row[3] * 2;
$endIdx = ($row[$startIdx-1] * 4) + $startIdx;
$embeddedSynsets = array_splice($row, $startIdx, $endIdx);
for($index = 0; $index < $row[$startIdx-1] * 4; $index+=4)
{
$linkedSynset = new Synset($embeddedSynsets[$index+1], $embeddedSynsets[$index+2]);
$linkedSynset->setPtrSymbols([$embeddedSynsets[$index]]);
// set src and target word indexes
if((int)$embeddedSynsets[$index+3] === 0) {
$linkedSynset->setSrcWordIdx(0);
$linkedSynset->setTargetWordIdx(0);
} else {
$linkedSynset->setSrcWordIdx((int)($embeddedSynsets[$index+3]) % 100);
$linkedSynset->setTargetWordIdx((int) floor($embeddedSynsets[$index+3] / 100));
}
$synset->addLinkedSynset($linkedSynset);
}
return $synset;
} | [
"public",
"function",
"getSynsetFromString",
"(",
"$",
"line",
")",
"{",
"$",
"row",
"=",
"str_getcsv",
"(",
"$",
"line",
",",
"\" \"",
")",
";",
"$",
"synset",
"=",
"new",
"Synset",
"(",
"(",
"int",
")",
"$",
"row",
"[",
"0",
"]",
",",
"$",
"row... | Parse the line from the synset file and turn it into a synset object
@param string $line
@return Synset | [
"Parse",
"the",
"line",
"from",
"the",
"synset",
"file",
"and",
"turn",
"it",
"into",
"a",
"synset",
"object"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Corpus/WordnetCorpus.php#L205-L235 |
yooper/php-text-analysis | src/Downloaders/NltkCorporaIndexDownloader.php | NltkCorporaIndexDownloader.getPackages | public function getPackages()
{
if(empty($this->packages)) {
$xml = $this->getXmlContent();
foreach($xml->packages->package as $package)
{
$data = (array)$package;
extract($data['@attributes']);
// checksums may not exist on some remote packages
if(!isset($checksum)) {
$checksum = null;
}
$this->packages[] = new Package($id, $checksum, $name, $subdir, $unzip, $url);
}
}
return $this->packages;
} | php | public function getPackages()
{
if(empty($this->packages)) {
$xml = $this->getXmlContent();
foreach($xml->packages->package as $package)
{
$data = (array)$package;
extract($data['@attributes']);
// checksums may not exist on some remote packages
if(!isset($checksum)) {
$checksum = null;
}
$this->packages[] = new Package($id, $checksum, $name, $subdir, $unzip, $url);
}
}
return $this->packages;
} | [
"public",
"function",
"getPackages",
"(",
")",
"{",
"if",
"(",
"empty",
"(",
"$",
"this",
"->",
"packages",
")",
")",
"{",
"$",
"xml",
"=",
"$",
"this",
"->",
"getXmlContent",
"(",
")",
";",
"foreach",
"(",
"$",
"xml",
"->",
"packages",
"->",
"pack... | Returns an array of packages available for download from the nltk project
@return array | [
"Returns",
"an",
"array",
"of",
"packages",
"available",
"for",
"download",
"from",
"the",
"nltk",
"project"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Downloaders/NltkCorporaIndexDownloader.php#L46-L64 |
yooper/php-text-analysis | src/Downloaders/NltkCorporaIndexDownloader.php | NltkCorporaIndexDownloader.getXmlContent | public function getXmlContent()
{
if($this->getUseCache() && file_exists(get_storage_path('cache').$this->getCacheFileName())) {
$contents = file_get_contents(get_storage_path('cache').$this->getCacheFileName());
} else {
$contents = file_get_contents( $this->getUrl());
file_put_contents(get_storage_path('cache').$this->getCacheFileName(), $contents);
}
return simplexml_load_string( $contents);
} | php | public function getXmlContent()
{
if($this->getUseCache() && file_exists(get_storage_path('cache').$this->getCacheFileName())) {
$contents = file_get_contents(get_storage_path('cache').$this->getCacheFileName());
} else {
$contents = file_get_contents( $this->getUrl());
file_put_contents(get_storage_path('cache').$this->getCacheFileName(), $contents);
}
return simplexml_load_string( $contents);
} | [
"public",
"function",
"getXmlContent",
"(",
")",
"{",
"if",
"(",
"$",
"this",
"->",
"getUseCache",
"(",
")",
"&&",
"file_exists",
"(",
"get_storage_path",
"(",
"'cache'",
")",
".",
"$",
"this",
"->",
"getCacheFileName",
"(",
")",
")",
")",
"{",
"$",
"c... | Uses file_get_contents to pull down the content from the url
@return SimpleXMLElement | [
"Uses",
"file_get_contents",
"to",
"pull",
"down",
"the",
"content",
"from",
"the",
"url"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Downloaders/NltkCorporaIndexDownloader.php#L79-L88 |
yooper/php-text-analysis | src/NGrams/Statistic2D.php | Statistic2D.tmi | static public function tmi(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$tmi = 0;
if($var['jointFrequency']) {
$tmi += $var['jointFrequency']/$totalNgrams * self::computePMI( $var['jointFrequency'], $var['m11'] )/ log(2);
}
if($var['LminusJ']) {
$tmi += $var['LminusJ']/$totalNgrams * self::computePMI( $var['LminusJ'], $var['m12'] )/ log(2);
}
if($var['RminusJ']) {
$tmi += $var['RminusJ']/$totalNgrams * self::computePMI( $var['RminusJ'], $var['m21'] )/ log(2);
}
if($var['n22']) {
$tmi += $var['n22']/$totalNgrams * self::computePMI( $var['n22'], $var['m22'] )/ log(2);
}
return $tmi;
} | php | static public function tmi(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$tmi = 0;
if($var['jointFrequency']) {
$tmi += $var['jointFrequency']/$totalNgrams * self::computePMI( $var['jointFrequency'], $var['m11'] )/ log(2);
}
if($var['LminusJ']) {
$tmi += $var['LminusJ']/$totalNgrams * self::computePMI( $var['LminusJ'], $var['m12'] )/ log(2);
}
if($var['RminusJ']) {
$tmi += $var['RminusJ']/$totalNgrams * self::computePMI( $var['RminusJ'], $var['m21'] )/ log(2);
}
if($var['n22']) {
$tmi += $var['n22']/$totalNgrams * self::computePMI( $var['n22'], $var['m22'] )/ log(2);
}
return $tmi;
} | [
"static",
"public",
"function",
"tmi",
"(",
"array",
"$",
"ngram",
",",
"int",
"$",
"totalNgrams",
")",
":",
"float",
"{",
"$",
"var",
"=",
"self",
"::",
"setStatVariables",
"(",
"$",
"ngram",
",",
"$",
"totalNgrams",
")",
";",
"$",
"tmi",
"=",
"0",
... | Calculate the true mutual information value
@param array $ngram Array of ngrams with frequencies
@return float Return the calculated value | [
"Calculate",
"the",
"true",
"mutual",
"information",
"value"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/Statistic2D.php#L17-L40 |
yooper/php-text-analysis | src/NGrams/Statistic2D.php | Statistic2D.ll | static public function ll(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$logLikelihood = 0;
if($var['jointFrequency']) {
$logLikelihood += $var['jointFrequency'] * self::computePMI ( $var['jointFrequency'], $var['m11'] );
}
if($var['LminusJ']) {
$logLikelihood += $var['LminusJ'] * self::computePMI( $var['LminusJ'], $var['m12'] );
}
if($var['RminusJ']) {
$logLikelihood += $var['RminusJ'] * self::computePMI( $var['RminusJ'], $var['m21'] );
}
if($var['n22']) {
$logLikelihood += $var['n22'] * self::computePMI( $var['n22'], $var['m22'] );
}
return $logLikelihood * 2;
} | php | static public function ll(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$logLikelihood = 0;
if($var['jointFrequency']) {
$logLikelihood += $var['jointFrequency'] * self::computePMI ( $var['jointFrequency'], $var['m11'] );
}
if($var['LminusJ']) {
$logLikelihood += $var['LminusJ'] * self::computePMI( $var['LminusJ'], $var['m12'] );
}
if($var['RminusJ']) {
$logLikelihood += $var['RminusJ'] * self::computePMI( $var['RminusJ'], $var['m21'] );
}
if($var['n22']) {
$logLikelihood += $var['n22'] * self::computePMI( $var['n22'], $var['m22'] );
}
return $logLikelihood * 2;
} | [
"static",
"public",
"function",
"ll",
"(",
"array",
"$",
"ngram",
",",
"int",
"$",
"totalNgrams",
")",
":",
"float",
"{",
"$",
"var",
"=",
"self",
"::",
"setStatVariables",
"(",
"$",
"ngram",
",",
"$",
"totalNgrams",
")",
";",
"$",
"logLikelihood",
"="... | Calculate the Loglikelihood coefficient
@param array $ngram Array of ngrams with frequencies
@return float Return the calculated value | [
"Calculate",
"the",
"Loglikelihood",
"coefficient"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/Statistic2D.php#L47-L70 |
yooper/php-text-analysis | src/NGrams/Statistic2D.php | Statistic2D.pmi | static public function pmi(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$temp = (($var['jointFrequency'] / $var['leftFrequency'] ) / $var['rightFrequency']) * $totalNgrams;
return(log($temp)/log(2));
} | php | static public function pmi(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$temp = (($var['jointFrequency'] / $var['leftFrequency'] ) / $var['rightFrequency']) * $totalNgrams;
return(log($temp)/log(2));
} | [
"static",
"public",
"function",
"pmi",
"(",
"array",
"$",
"ngram",
",",
"int",
"$",
"totalNgrams",
")",
":",
"float",
"{",
"$",
"var",
"=",
"self",
"::",
"setStatVariables",
"(",
"$",
"ngram",
",",
"$",
"totalNgrams",
")",
";",
"$",
"temp",
"=",
"(",... | Calculate the Mutual Information coefficient
@param array $ngram Array of ngrams with frequencies
@return float Return the calculated value | [
"Calculate",
"the",
"Mutual",
"Information",
"coefficient"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/Statistic2D.php#L77-L84 |
yooper/php-text-analysis | src/NGrams/Statistic2D.php | Statistic2D.x2 | static public function x2(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$Xsquare = 0;
$Xsquare += ( ( $var['jointFrequency'] - $var['m11'] ) ** 2 ) / $var['m11'];
$Xsquare += ( ( $var['LminusJ'] - $var['m12'] ) ** 2 ) / $var['m12'];
$Xsquare += ( ( $var['RminusJ'] - $var['m21'] ) ** 2 ) / $var['m21'];
$Xsquare += ( ( $var['n22'] - $var['m22'] ) ** 2 ) / $var['m22'];
return $Xsquare;
} | php | static public function x2(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$Xsquare = 0;
$Xsquare += ( ( $var['jointFrequency'] - $var['m11'] ) ** 2 ) / $var['m11'];
$Xsquare += ( ( $var['LminusJ'] - $var['m12'] ) ** 2 ) / $var['m12'];
$Xsquare += ( ( $var['RminusJ'] - $var['m21'] ) ** 2 ) / $var['m21'];
$Xsquare += ( ( $var['n22'] - $var['m22'] ) ** 2 ) / $var['m22'];
return $Xsquare;
} | [
"static",
"public",
"function",
"x2",
"(",
"array",
"$",
"ngram",
",",
"int",
"$",
"totalNgrams",
")",
":",
"float",
"{",
"$",
"var",
"=",
"self",
"::",
"setStatVariables",
"(",
"$",
"ngram",
",",
"$",
"totalNgrams",
")",
";",
"$",
"Xsquare",
"=",
"0... | Calculate the X squared coefficient
@param array $ngram Array of ngrams with frequencies
@return float Return the calculated value | [
"Calculate",
"the",
"X",
"squared",
"coefficient"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/Statistic2D.php#L103-L115 |
yooper/php-text-analysis | src/NGrams/Statistic2D.php | Statistic2D.tscore | static public function tscore(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$term1 = $var['jointFrequency'] - (($var['leftFrequency'] * $var['rightFrequency'])/$totalNgrams);
$term2 = sqrt(($var['jointFrequency']));
return ( $term1 / $term2 );
} | php | static public function tscore(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$term1 = $var['jointFrequency'] - (($var['leftFrequency'] * $var['rightFrequency'])/$totalNgrams);
$term2 = sqrt(($var['jointFrequency']));
return ( $term1 / $term2 );
} | [
"static",
"public",
"function",
"tscore",
"(",
"array",
"$",
"ngram",
",",
"int",
"$",
"totalNgrams",
")",
":",
"float",
"{",
"$",
"var",
"=",
"self",
"::",
"setStatVariables",
"(",
"$",
"ngram",
",",
"$",
"totalNgrams",
")",
";",
"$",
"term1",
"=",
... | Calculate the T-score
@param array $ngram Array of ngrams with frequencies
@return float Return the calculated value | [
"Calculate",
"the",
"T",
"-",
"score"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/Statistic2D.php#L122-L130 |
yooper/php-text-analysis | src/NGrams/Statistic2D.php | Statistic2D.phi | static public function phi(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$term1 = $var['jointFrequency'] * $var['n22'] - $var['RminusJ'] * $var['LminusJ'];
$term2 = $var['leftFrequency'] * $var['rightFrequency'] * $var['TminusR'] * $var['TminusL'];
$phi = ($term1 * $term1)/$term2;
return $phi;
} | php | static public function phi(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
$term1 = $var['jointFrequency'] * $var['n22'] - $var['RminusJ'] * $var['LminusJ'];
$term2 = $var['leftFrequency'] * $var['rightFrequency'] * $var['TminusR'] * $var['TminusL'];
$phi = ($term1 * $term1)/$term2;
return $phi;
} | [
"static",
"public",
"function",
"phi",
"(",
"array",
"$",
"ngram",
",",
"int",
"$",
"totalNgrams",
")",
":",
"float",
"{",
"$",
"var",
"=",
"self",
"::",
"setStatVariables",
"(",
"$",
"ngram",
",",
"$",
"totalNgrams",
")",
";",
"$",
"term1",
"=",
"$"... | Calculate the Phi Coefficient
@param array $ngram Array of ngrams with frequencies
@return float Return the calculated value | [
"Calculate",
"the",
"Phi",
"Coefficient"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/Statistic2D.php#L137-L147 |
yooper/php-text-analysis | src/NGrams/Statistic2D.php | Statistic2D.odds | static public function odds(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
if ($var['RminusJ'] == 0) {
$var['RminusJ'] = 1;
}
if ($var['LminusJ'] == 0) {
$var['LminusJ'] = 1;
}
$term1 = $var['jointFrequency'] * $var['n22'];
$term2 = $var['RminusJ'] * $var['LminusJ'];
$odds = $term1/$term2;
return $odds;
} | php | static public function odds(array $ngram, int $totalNgrams) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
if ($var['RminusJ'] == 0) {
$var['RminusJ'] = 1;
}
if ($var['LminusJ'] == 0) {
$var['LminusJ'] = 1;
}
$term1 = $var['jointFrequency'] * $var['n22'];
$term2 = $var['RminusJ'] * $var['LminusJ'];
$odds = $term1/$term2;
return $odds;
} | [
"static",
"public",
"function",
"odds",
"(",
"array",
"$",
"ngram",
",",
"int",
"$",
"totalNgrams",
")",
":",
"float",
"{",
"$",
"var",
"=",
"self",
"::",
"setStatVariables",
"(",
"$",
"ngram",
",",
"$",
"totalNgrams",
")",
";",
"if",
"(",
"$",
"var"... | Calculate the Odds Ratio
@param array $ngram Array of ngrams with frequencies
@return float Return the calculated value | [
"Calculate",
"the",
"Odds",
"Ratio"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/Statistic2D.php#L154-L172 |
yooper/php-text-analysis | src/NGrams/Statistic2D.php | Statistic2D.fisher | static public function fisher(array $ngram, int $totalNgrams, string $side) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
# we shall have two arrays one for the numerator and one for the
# denominator. the arrays will contain the factorial upper limits. we
# shall be arrange these two arrays in descending order. while doing the
# actual calculation, we shall take a numerator/denominator pair, and
# go from the lower value to the higher value, in effect doing a
# "cancellation" of sorts.
# first create the numerator
$numerator = array($var['leftFrequency'], $var['rightFrequency'], $var['TminusL'], $var['TminusR']);
arsort($numerator);
# now to the real calculation!!!
$probability = 0;
$i = 0;
$j = 0;
# we shall calculate for n11 = 0. thereafter we shall just multiply and
# divide the result for 0 with correct numbers to obtain result for i,
# i>0, i<=n11!! :o)
########### this part by Nitin O Verma
if($side == 'left') {
$finalLimit = $var['jointFrequency'];
$var['jointFrequency'] = 0;
$var['LminusJ'] = $var['leftFrequency'];
$var['RminusJ'] = $var['rightFrequency'];
$var['n22'] = $var['TminusL'] - $var['RminusJ'];
while($var['n22'] < 0) {
$var['jointFrequency']++;
$var['LminusJ'] = $var['leftFrequency'] - $var['jointFrequency'];
$var['RminusJ'] = $var['rightFrequency'] - $var['jointFrequency'];
$var['n22'] = $var['TminusL'] - $var['RminusJ'];
}
} else {
$finalLimit = ($var['leftFrequency'] < $var['rightFrequency']) ? $var['leftFrequency'] : $var['rightFrequency'];
}
########### end of part by Nitin O Verma
$denominator = array($totalNgrams, $var['n22'], $var['LminusJ'], $var['RminusJ'], $var['jointFrequency']);
arsort($denominator);
# now that we have our two arrays all nicely sorted and in place,
# lets do the calculations!
$dLimits = array();
$nLimits = array();
$dIndex = 0;
$nIndex = 0;
for($j = 0; $j < 4; $j ++) {
if ( $numerator[$j] > $denominator[$j] ) {
$nLimits[$nIndex] = $denominator[$j] + 1;
$nLimits[$nIndex+1] = $numerator[$j];
$nIndex += 2;
} elseif ($denominator[$j] > $numerator[$j]) {
$dLimits[$dIndex] = $numerator[$j] + 1;
$dLimits[$dIndex+1] = $denominator[$j];
$dIndex += 2;
}
}
$dLimits[$dIndex] = 1;
$dLimits[$dIndex+1] = $denominator[4];
$product = 1;
while(isset($nLimits[0])) {
while(($product < 10000) && (isset($nLimits[0]))) {
$product *= $nLimits[0];
$nLimits[0]++;
if ( $nLimits[0] > $nLimits[1] ) {
array_shift($nLimits);
array_shift($nLimits);
}
}
while($product > 1) {
$product /= $dLimits[0];
$dLimits[0]++;
if ( $dLimits[0] > $dLimits[1] ) {
array_shift($dLimits);
array_shift($dLimits);
}
}
}
while(isset($dLimits[0])) {
$product /= $dLimits[0];
$dLimits[0]++;
if($dLimits[0] > $dLimits[1]) {
array_shift($dLimits);
array_shift($dLimits);
}
}
# $product now has the hypergeometric probability for n11 = 0. add it to
# the cumulative probability
$probability += $product;
# Bridget Thomson McInnes October 15 2003
# I set i <= final_Limit rather than n11 because we want to sum the
# hypergeometric probabilities where the count in n11 is less and or
# equal to the observed value.
# now for the rest of n11's !!
$i = ($side == 'left') ? 1 : $var['jointFrequency']+1;
for($i; $i <= $finalLimit; $i++ ) {
$product *= $var['LminusJ'];
$var['n22']++;
if($var['n22'] <= 0) {
continue;
}
$product /= $var['n22'];
$product *= $var['RminusJ'];
$var['LminusJ']--;
$var['RminusJ']--;
$product /= $i;
# thats our new probability for n11 = i! :o)) cool eh? ;o))
# add it to the main probability! :o))
$probability += $product; # !! :o)
}
return $probability;
} | php | static public function fisher(array $ngram, int $totalNgrams, string $side) : float
{
$var = self::setStatVariables($ngram, $totalNgrams);
# we shall have two arrays one for the numerator and one for the
# denominator. the arrays will contain the factorial upper limits. we
# shall be arrange these two arrays in descending order. while doing the
# actual calculation, we shall take a numerator/denominator pair, and
# go from the lower value to the higher value, in effect doing a
# "cancellation" of sorts.
# first create the numerator
$numerator = array($var['leftFrequency'], $var['rightFrequency'], $var['TminusL'], $var['TminusR']);
arsort($numerator);
# now to the real calculation!!!
$probability = 0;
$i = 0;
$j = 0;
# we shall calculate for n11 = 0. thereafter we shall just multiply and
# divide the result for 0 with correct numbers to obtain result for i,
# i>0, i<=n11!! :o)
########### this part by Nitin O Verma
if($side == 'left') {
$finalLimit = $var['jointFrequency'];
$var['jointFrequency'] = 0;
$var['LminusJ'] = $var['leftFrequency'];
$var['RminusJ'] = $var['rightFrequency'];
$var['n22'] = $var['TminusL'] - $var['RminusJ'];
while($var['n22'] < 0) {
$var['jointFrequency']++;
$var['LminusJ'] = $var['leftFrequency'] - $var['jointFrequency'];
$var['RminusJ'] = $var['rightFrequency'] - $var['jointFrequency'];
$var['n22'] = $var['TminusL'] - $var['RminusJ'];
}
} else {
$finalLimit = ($var['leftFrequency'] < $var['rightFrequency']) ? $var['leftFrequency'] : $var['rightFrequency'];
}
########### end of part by Nitin O Verma
$denominator = array($totalNgrams, $var['n22'], $var['LminusJ'], $var['RminusJ'], $var['jointFrequency']);
arsort($denominator);
# now that we have our two arrays all nicely sorted and in place,
# lets do the calculations!
$dLimits = array();
$nLimits = array();
$dIndex = 0;
$nIndex = 0;
for($j = 0; $j < 4; $j ++) {
if ( $numerator[$j] > $denominator[$j] ) {
$nLimits[$nIndex] = $denominator[$j] + 1;
$nLimits[$nIndex+1] = $numerator[$j];
$nIndex += 2;
} elseif ($denominator[$j] > $numerator[$j]) {
$dLimits[$dIndex] = $numerator[$j] + 1;
$dLimits[$dIndex+1] = $denominator[$j];
$dIndex += 2;
}
}
$dLimits[$dIndex] = 1;
$dLimits[$dIndex+1] = $denominator[4];
$product = 1;
while(isset($nLimits[0])) {
while(($product < 10000) && (isset($nLimits[0]))) {
$product *= $nLimits[0];
$nLimits[0]++;
if ( $nLimits[0] > $nLimits[1] ) {
array_shift($nLimits);
array_shift($nLimits);
}
}
while($product > 1) {
$product /= $dLimits[0];
$dLimits[0]++;
if ( $dLimits[0] > $dLimits[1] ) {
array_shift($dLimits);
array_shift($dLimits);
}
}
}
while(isset($dLimits[0])) {
$product /= $dLimits[0];
$dLimits[0]++;
if($dLimits[0] > $dLimits[1]) {
array_shift($dLimits);
array_shift($dLimits);
}
}
# $product now has the hypergeometric probability for n11 = 0. add it to
# the cumulative probability
$probability += $product;
# Bridget Thomson McInnes October 15 2003
# I set i <= final_Limit rather than n11 because we want to sum the
# hypergeometric probabilities where the count in n11 is less and or
# equal to the observed value.
# now for the rest of n11's !!
$i = ($side == 'left') ? 1 : $var['jointFrequency']+1;
for($i; $i <= $finalLimit; $i++ ) {
$product *= $var['LminusJ'];
$var['n22']++;
if($var['n22'] <= 0) {
continue;
}
$product /= $var['n22'];
$product *= $var['RminusJ'];
$var['LminusJ']--;
$var['RminusJ']--;
$product /= $i;
# thats our new probability for n11 = i! :o)) cool eh? ;o))
# add it to the main probability! :o))
$probability += $product; # !! :o)
}
return $probability;
} | [
"static",
"public",
"function",
"fisher",
"(",
"array",
"$",
"ngram",
",",
"int",
"$",
"totalNgrams",
",",
"string",
"$",
"side",
")",
":",
"float",
"{",
"$",
"var",
"=",
"self",
"::",
"setStatVariables",
"(",
"$",
"ngram",
",",
"$",
"totalNgrams",
")"... | Calculate the Fisher's exact test
@param array $ngram Array of ngrams with frequencies
@return float Return the calculated value | [
"Calculate",
"the",
"Fisher",
"s",
"exact",
"test"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/Statistic2D.php#L179-L314 |
yooper/php-text-analysis | src/NGrams/Statistic2D.php | Statistic2D.setStatVariables | static public function setStatVariables(array $ngram, int $totalNgrams)
{
$var['jointFrequency'] = $ngram[0]; # pair freq
$var['leftFrequency'] = $ngram[1]; # single freq of first word
$var['rightFrequency'] = $ngram[2]; # single freq of second word
$var['LminusJ'] = $var['leftFrequency'] - $var['jointFrequency'];
$var['RminusJ'] = $var['rightFrequency'] - $var['jointFrequency'];
$var['TminusR'] = $totalNgrams - $var['rightFrequency'];
$var['TminusL'] = $totalNgrams - $var['leftFrequency'];
$var['n22'] = $var['TminusR'] - $var['LminusJ'];
$var['m11'] = $var['leftFrequency'] * $var['rightFrequency'] / $totalNgrams;
$var['m12'] = $var['leftFrequency'] * $var['TminusR'] / $totalNgrams;
$var['m21'] = $var['TminusL'] * $var['rightFrequency'] / $totalNgrams;
$var['m22'] = $var['TminusL'] * $var['TminusR'] / $totalNgrams;
return $var;
} | php | static public function setStatVariables(array $ngram, int $totalNgrams)
{
$var['jointFrequency'] = $ngram[0]; # pair freq
$var['leftFrequency'] = $ngram[1]; # single freq of first word
$var['rightFrequency'] = $ngram[2]; # single freq of second word
$var['LminusJ'] = $var['leftFrequency'] - $var['jointFrequency'];
$var['RminusJ'] = $var['rightFrequency'] - $var['jointFrequency'];
$var['TminusR'] = $totalNgrams - $var['rightFrequency'];
$var['TminusL'] = $totalNgrams - $var['leftFrequency'];
$var['n22'] = $var['TminusR'] - $var['LminusJ'];
$var['m11'] = $var['leftFrequency'] * $var['rightFrequency'] / $totalNgrams;
$var['m12'] = $var['leftFrequency'] * $var['TminusR'] / $totalNgrams;
$var['m21'] = $var['TminusL'] * $var['rightFrequency'] / $totalNgrams;
$var['m22'] = $var['TminusL'] * $var['TminusR'] / $totalNgrams;
return $var;
} | [
"static",
"public",
"function",
"setStatVariables",
"(",
"array",
"$",
"ngram",
",",
"int",
"$",
"totalNgrams",
")",
"{",
"$",
"var",
"[",
"'jointFrequency'",
"]",
"=",
"$",
"ngram",
"[",
"0",
"]",
";",
"# pair freq",
"$",
"var",
"[",
"'leftFrequency'",
... | Sets variables to calculate the statistic measures
The format is restricted: [int $jointFrequency, int $leftFrequency, int $rightFrequency]
@return array $var Return the array with the variables | [
"Sets",
"variables",
"to",
"calculate",
"the",
"statistic",
"measures",
"The",
"format",
"is",
"restricted",
":",
"[",
"int",
"$jointFrequency",
"int",
"$leftFrequency",
"int",
"$rightFrequency",
"]"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/NGrams/Statistic2D.php#L355-L372 |
yooper/php-text-analysis | src/Documents/TokensDocument.php | TokensDocument.applyStemmer | public function applyStemmer(IStemmer $stemmer, $removeNulls = true)
{
foreach($this->tokens as &$token)
{
$token = $stemmer->stem($token);
}
if($removeNulls) {
//filter null tokens and re-index
$this->tokens = array_values(array_filter($this->tokens));
}
return $this;
} | php | public function applyStemmer(IStemmer $stemmer, $removeNulls = true)
{
foreach($this->tokens as &$token)
{
$token = $stemmer->stem($token);
}
if($removeNulls) {
//filter null tokens and re-index
$this->tokens = array_values(array_filter($this->tokens));
}
return $this;
} | [
"public",
"function",
"applyStemmer",
"(",
"IStemmer",
"$",
"stemmer",
",",
"$",
"removeNulls",
"=",
"true",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"tokens",
"as",
"&",
"$",
"token",
")",
"{",
"$",
"token",
"=",
"$",
"stemmer",
"->",
"stem",
"(... | Apply a stemmer
@param IStemmer $stemmer
@param boolean $removeNulls
@return \TextAnalysis\Documents\TokensDocument | [
"Apply",
"a",
"stemmer"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Documents/TokensDocument.php#L75-L87 |
yooper/php-text-analysis | src/Documents/TokensDocument.php | TokensDocument.applyTransformation | public function applyTransformation(ITokenTransformation $transformer, $removeNulls = true)
{
foreach($this->tokens as &$token)
{
$token = $transformer->transform($token);
}
//filter null tokens and re-index
if($removeNulls) {
$this->tokens = array_values(array_filter($this->tokens));
}
return $this;
} | php | public function applyTransformation(ITokenTransformation $transformer, $removeNulls = true)
{
foreach($this->tokens as &$token)
{
$token = $transformer->transform($token);
}
//filter null tokens and re-index
if($removeNulls) {
$this->tokens = array_values(array_filter($this->tokens));
}
return $this;
} | [
"public",
"function",
"applyTransformation",
"(",
"ITokenTransformation",
"$",
"transformer",
",",
"$",
"removeNulls",
"=",
"true",
")",
"{",
"foreach",
"(",
"$",
"this",
"->",
"tokens",
"as",
"&",
"$",
"token",
")",
"{",
"$",
"token",
"=",
"$",
"transform... | Apply the transformation
@param ITokenTransformation $transformer
@param boolean Remove nulls, we need nulls to indictate where stop words are
@return \TextAnalysis\Documents\TokensDocument | [
"Apply",
"the",
"transformation"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Documents/TokensDocument.php#L95-L106 |
yooper/php-text-analysis | src/Documents/TokensDocument.php | TokensDocument.applyExtract | public function applyExtract(IExtractStrategy $extract)
{
$found = [];
foreach($this->tokens as $token)
{
if($extract->filter($token)) {
$found[] = $token;
}
}
return $found;
} | php | public function applyExtract(IExtractStrategy $extract)
{
$found = [];
foreach($this->tokens as $token)
{
if($extract->filter($token)) {
$found[] = $token;
}
}
return $found;
} | [
"public",
"function",
"applyExtract",
"(",
"IExtractStrategy",
"$",
"extract",
")",
"{",
"$",
"found",
"=",
"[",
"]",
";",
"foreach",
"(",
"$",
"this",
"->",
"tokens",
"as",
"$",
"token",
")",
"{",
"if",
"(",
"$",
"extract",
"->",
"filter",
"(",
"$",... | Apply an extract filter and return the results after filter
all the documents in the collection
@param IExtractStrategy $extract
@return array | [
"Apply",
"an",
"extract",
"filter",
"and",
"return",
"the",
"results",
"after",
"filter",
"all",
"the",
"documents",
"in",
"the",
"collection"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Documents/TokensDocument.php#L114-L124 |
yooper/php-text-analysis | src/Utilities/Text.php | Text.getAllSubStrings | static public function getAllSubStrings($text)
{
$splitText = str_split($text);
$splitCount = count($splitText);
$subStrings = [];
for ($i = 0; $i < $splitCount; $i++)
{
for ($j = $i; $j < $splitCount; $j++)
{
$subStrings[] = implode(array_slice($splitText, $i, $j - $i + 1));
}
}
return $subStrings;
} | php | static public function getAllSubStrings($text)
{
$splitText = str_split($text);
$splitCount = count($splitText);
$subStrings = [];
for ($i = 0; $i < $splitCount; $i++)
{
for ($j = $i; $j < $splitCount; $j++)
{
$subStrings[] = implode(array_slice($splitText, $i, $j - $i + 1));
}
}
return $subStrings;
} | [
"static",
"public",
"function",
"getAllSubStrings",
"(",
"$",
"text",
")",
"{",
"$",
"splitText",
"=",
"str_split",
"(",
"$",
"text",
")",
";",
"$",
"splitCount",
"=",
"count",
"(",
"$",
"splitText",
")",
";",
"$",
"subStrings",
"=",
"[",
"]",
";",
"... | Takes a string and produces all possible substrings
@param string $text
@return array | [
"Takes",
"a",
"string",
"and",
"produces",
"all",
"possible",
"substrings"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Utilities/Text.php#L44-L57 |
yooper/php-text-analysis | src/Utilities/Text.php | Text.findDate | static public function findDate( $string ) {
$shortenize = function( $string ) {
return substr( $string, 0, 3 );
};
// Define month name:
$month_names = array(
"january",
"february",
"march",
"april",
"may",
"june",
"july",
"august",
"september",
"october",
"november",
"december"
);
$short_month_names = array_map( $shortenize, $month_names );
// Define day name
$day_names = array(
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday"
);
$short_day_names = array_map( $shortenize, $day_names );
$day = "";
$month = "";
$year = "";
// Match dates: 01/01/2012 or 30-12-11 or 1 2 1985
preg_match( '/([0-9]?[0-9])[\.\-\/ ]+([0-1]?[0-9])[\.\-\/ ]+([0-9]{2,4})/', $string, $matches );
if ( $matches ) {
if ( $matches[1] )
$day = $matches[1];
if ( $matches[2] )
$month = $matches[2];
if ( $matches[3] )
$year = $matches[3];
}
// Match dates: Sunday 1st March 2015; Sunday, 1 March 2015; Sun 1 Mar 2015; Sun-1-March-2015
preg_match('/(?:(?:' . implode( '|', $day_names ) . '|' . implode( '|', $short_day_names ) . ')[ ,\-_\/]*)?([0-9]?[0-9])[ ,\-_\/]*(?:st|nd|th)?[ ,\-_\/]*(' . implode( '|', $month_names ) . '|' . implode( '|', $short_month_names ) . ')[ ,\-_\/]+([0-9]{4})/i', $string, $matches );
if ( $matches ) {
if ( empty( $day ) && $matches[1] )
$day = $matches[1];
if ( empty( $month ) && $matches[2] ) {
$month = array_search( strtolower( $matches[2] ), $short_month_names );
if ( ! $month )
$month = array_search( strtolower( $matches[2] ), $month_names );
$month = $month + 1;
}
if ( empty( $year ) && $matches[3] )
$year = $matches[3];
}
// Match dates: March 1st 2015; March 1 2015; March-1st-2015
preg_match('/(' . implode( '|', $month_names ) . '|' . implode( '|', $short_month_names ) . ')[ ,\-_\/]*([0-9]?[0-9])[ ,\-_\/]*(?:st|nd|th)?[ ,\-_\/]+([0-9]{4})/i', $string, $matches );
if ( $matches ) {
if ( empty( $month ) && $matches[1] ) {
$month = array_search( strtolower( $matches[1] ), $short_month_names );
if ( ! $month )
$month = array_search( strtolower( $matches[1] ), $month_names );
$month = $month + 1;
}
if ( empty( $day ) && $matches[2] )
$day = $matches[2];
if ( empty( $year ) && $matches[3] )
$year = $matches[3];
}
// Match month name:
if ( empty( $month ) ) {
preg_match( '/(' . implode( '|', $month_names ) . ')/i', $string, $matches_month_word );
if ( $matches_month_word && $matches_month_word[1] )
$month = array_search( strtolower( $matches_month_word[1] ), $month_names );
// Match short month names
if ( empty( $month ) ) {
preg_match( '/(' . implode( '|', $short_month_names ) . ')/i', $string, $matches_month_word );
if ( $matches_month_word && $matches_month_word[1] )
$month = array_search( strtolower( $matches_month_word[1] ), $short_month_names );
}
$month = $month + 1;
}
// Match 5th 1st day:
if ( empty( $day ) ) {
preg_match( '/([0-9]?[0-9])(st|nd|th)/', $string, $matches_day );
if ( $matches_day && $matches_day[1] )
$day = $matches_day[1];
}
// Match Year if not already setted:
if ( empty( $year ) ) {
preg_match( '/[0-9]{4}/', $string, $matches_year );
if ( $matches_year && $matches_year[0] )
$year = $matches_year[0];
}
if ( ! empty ( $day ) && ! empty ( $month ) && empty( $year ) ) {
preg_match( '/[0-9]{2}/', $string, $matches_year );
if ( $matches_year && $matches_year[0] )
$year = $matches_year[0];
}
// Day leading 0
if ( 1 == strlen( $day ) )
$day = '0' . $day;
// Month leading 0
if ( 1 == strlen( $month ) )
$month = '0' . $month;
// Check year:
if ( 2 == strlen( $year ) && $year > 20 )
$year = '19' . $year;
else if ( 2 == strlen( $year ) && $year < 20 )
$year = '20' . $year;
$date = array(
'year' => $year,
'month' => $month,
'day' => $day
);
// Return false if nothing found:
if ( empty( $year ) && empty( $month ) && empty( $day ) )
return false;
else
return $date;
} | php | static public function findDate( $string ) {
$shortenize = function( $string ) {
return substr( $string, 0, 3 );
};
// Define month name:
$month_names = array(
"january",
"february",
"march",
"april",
"may",
"june",
"july",
"august",
"september",
"october",
"november",
"december"
);
$short_month_names = array_map( $shortenize, $month_names );
// Define day name
$day_names = array(
"monday",
"tuesday",
"wednesday",
"thursday",
"friday",
"saturday",
"sunday"
);
$short_day_names = array_map( $shortenize, $day_names );
$day = "";
$month = "";
$year = "";
// Match dates: 01/01/2012 or 30-12-11 or 1 2 1985
preg_match( '/([0-9]?[0-9])[\.\-\/ ]+([0-1]?[0-9])[\.\-\/ ]+([0-9]{2,4})/', $string, $matches );
if ( $matches ) {
if ( $matches[1] )
$day = $matches[1];
if ( $matches[2] )
$month = $matches[2];
if ( $matches[3] )
$year = $matches[3];
}
// Match dates: Sunday 1st March 2015; Sunday, 1 March 2015; Sun 1 Mar 2015; Sun-1-March-2015
preg_match('/(?:(?:' . implode( '|', $day_names ) . '|' . implode( '|', $short_day_names ) . ')[ ,\-_\/]*)?([0-9]?[0-9])[ ,\-_\/]*(?:st|nd|th)?[ ,\-_\/]*(' . implode( '|', $month_names ) . '|' . implode( '|', $short_month_names ) . ')[ ,\-_\/]+([0-9]{4})/i', $string, $matches );
if ( $matches ) {
if ( empty( $day ) && $matches[1] )
$day = $matches[1];
if ( empty( $month ) && $matches[2] ) {
$month = array_search( strtolower( $matches[2] ), $short_month_names );
if ( ! $month )
$month = array_search( strtolower( $matches[2] ), $month_names );
$month = $month + 1;
}
if ( empty( $year ) && $matches[3] )
$year = $matches[3];
}
// Match dates: March 1st 2015; March 1 2015; March-1st-2015
preg_match('/(' . implode( '|', $month_names ) . '|' . implode( '|', $short_month_names ) . ')[ ,\-_\/]*([0-9]?[0-9])[ ,\-_\/]*(?:st|nd|th)?[ ,\-_\/]+([0-9]{4})/i', $string, $matches );
if ( $matches ) {
if ( empty( $month ) && $matches[1] ) {
$month = array_search( strtolower( $matches[1] ), $short_month_names );
if ( ! $month )
$month = array_search( strtolower( $matches[1] ), $month_names );
$month = $month + 1;
}
if ( empty( $day ) && $matches[2] )
$day = $matches[2];
if ( empty( $year ) && $matches[3] )
$year = $matches[3];
}
// Match month name:
if ( empty( $month ) ) {
preg_match( '/(' . implode( '|', $month_names ) . ')/i', $string, $matches_month_word );
if ( $matches_month_word && $matches_month_word[1] )
$month = array_search( strtolower( $matches_month_word[1] ), $month_names );
// Match short month names
if ( empty( $month ) ) {
preg_match( '/(' . implode( '|', $short_month_names ) . ')/i', $string, $matches_month_word );
if ( $matches_month_word && $matches_month_word[1] )
$month = array_search( strtolower( $matches_month_word[1] ), $short_month_names );
}
$month = $month + 1;
}
// Match 5th 1st day:
if ( empty( $day ) ) {
preg_match( '/([0-9]?[0-9])(st|nd|th)/', $string, $matches_day );
if ( $matches_day && $matches_day[1] )
$day = $matches_day[1];
}
// Match Year if not already setted:
if ( empty( $year ) ) {
preg_match( '/[0-9]{4}/', $string, $matches_year );
if ( $matches_year && $matches_year[0] )
$year = $matches_year[0];
}
if ( ! empty ( $day ) && ! empty ( $month ) && empty( $year ) ) {
preg_match( '/[0-9]{2}/', $string, $matches_year );
if ( $matches_year && $matches_year[0] )
$year = $matches_year[0];
}
// Day leading 0
if ( 1 == strlen( $day ) )
$day = '0' . $day;
// Month leading 0
if ( 1 == strlen( $month ) )
$month = '0' . $month;
// Check year:
if ( 2 == strlen( $year ) && $year > 20 )
$year = '19' . $year;
else if ( 2 == strlen( $year ) && $year < 20 )
$year = '20' . $year;
$date = array(
'year' => $year,
'month' => $month,
'day' => $day
);
// Return false if nothing found:
if ( empty( $year ) && empty( $month ) && empty( $day ) )
return false;
else
return $date;
} | [
"static",
"public",
"function",
"findDate",
"(",
"$",
"string",
")",
"{",
"$",
"shortenize",
"=",
"function",
"(",
"$",
"string",
")",
"{",
"return",
"substr",
"(",
"$",
"string",
",",
"0",
",",
"3",
")",
";",
"}",
";",
"// Define month name:",
"$",
... | Find Date in a String
@author Etienne Tremel
@license http://creativecommons.org/licenses/by/3.0/ CC by 3.0
@link http://www.etiennetremel.net
@version 0.2.0
@param string find_date( ' some text 01/01/2012 some text' ) or find_date( ' some text October 5th 86 some text' )
@return mixed false if no date found else array: array( 'day' => 01, 'month' => 01, 'year' => 2012 ) | [
"Find",
"Date",
"in",
"a",
"String"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Utilities/Text.php#L70-L217 |
yooper/php-text-analysis | src/Utilities/Text.php | Text.markString | static function markString(string $text, int $position, int $length, array $mark) : string
{
$text = substr_replace($text, $mark[0], $position, 0);
$text = substr_replace($text, $mark[1], $position + $length + strlen($mark[0]), 0);
return $text;
} | php | static function markString(string $text, int $position, int $length, array $mark) : string
{
$text = substr_replace($text, $mark[0], $position, 0);
$text = substr_replace($text, $mark[1], $position + $length + strlen($mark[0]), 0);
return $text;
} | [
"static",
"function",
"markString",
"(",
"string",
"$",
"text",
",",
"int",
"$",
"position",
",",
"int",
"$",
"length",
",",
"array",
"$",
"mark",
")",
":",
"string",
"{",
"$",
"text",
"=",
"substr_replace",
"(",
"$",
"text",
",",
"$",
"mark",
"[",
... | Mark a string
@param string $text
@param int $position
@param int $length
@param array $mark
@return string | [
"Mark",
"a",
"string"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Utilities/Text.php#L228-L234 |
yooper/php-text-analysis | src/Utilities/Text.php | Text.getExcerpt | static function getExcerpt(String $text, int $needlePosition, int $needleLength, int $contextLength) : string
{
$left = max($needlePosition - $contextLength, 0);
$bufferLength = $needleLength + (2 * $contextLength);
if($needleLength + $contextLength + $needlePosition > strlen($text)) {
$text = substr($text, $left);
} else {
$text = substr($text, $left, $bufferLength);
}
return $text;
} | php | static function getExcerpt(String $text, int $needlePosition, int $needleLength, int $contextLength) : string
{
$left = max($needlePosition - $contextLength, 0);
$bufferLength = $needleLength + (2 * $contextLength);
if($needleLength + $contextLength + $needlePosition > strlen($text)) {
$text = substr($text, $left);
} else {
$text = substr($text, $left, $bufferLength);
}
return $text;
} | [
"static",
"function",
"getExcerpt",
"(",
"String",
"$",
"text",
",",
"int",
"$",
"needlePosition",
",",
"int",
"$",
"needleLength",
",",
"int",
"$",
"contextLength",
")",
":",
"string",
"{",
"$",
"left",
"=",
"max",
"(",
"$",
"needlePosition",
"-",
"$",
... | Get a excerpt from a string by a neddle postion and its length
@param string $text
@param int $needlePosition
@param int $needleLength
@param int $contextLength
@return string | [
"Get",
"a",
"excerpt",
"from",
"a",
"string",
"by",
"a",
"neddle",
"postion",
"and",
"its",
"length"
] | train | https://github.com/yooper/php-text-analysis/blob/a0332ed4ed76bcd9fe280f82f519fa9ce8ab20c4/src/Utilities/Text.php#L245-L257 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.