_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q241000
|
InternationalizedHelper.&
|
train
|
public function & SetView (\MvcCore\IView & $view) {
parent::SetView($view);
return $this->SetLangAndLocale($this->request->GetLang(), $this->request->GetLocale());
}
|
php
|
{
"resource": ""
}
|
q241001
|
iauAtciq.Atciq
|
train
|
public static function Atciq($rc, $dc, $pr, $pd, $px, $rv, iauASTROM $astrom,
&$ri, &$di) {
$pco = [];
$pnat = [];
$ppr = [];
$pi = [];
$w;
/* Proper motion and parallax, giving BCRS coordinate direction. */
IAU::Pmpx($rc, $dc, $pr, $pd, $px, $rv, $astrom->pmt, $astrom->eb, $pco);
/* Light deflection by the Sun, giving BCRS natural direction. */
IAU::Ldsun($pco, $astrom->eh, $astrom->em, $pnat);
/* Aberration, giving GCRS proper direction. */
IAU::Ab($pnat, $astrom->v, $astrom->em, $astrom->bm1, $ppr);
/* Bias-precession-nutation, giving CIRS proper direction. */
IAU::Rxp($astrom->bpn, $ppr, $pi);
/* CIRS RA,Dec. */
IAU::C2s($pi, $w, $di);
$ri = IAU::Anp($w);
/* Finished. */
}
|
php
|
{
"resource": ""
}
|
q241002
|
HTML.tag
|
train
|
public static function tag($tag, $attr = [], $html = '')
{
// Build attributes
$attributes = [];
foreach ($attr as $name => $value) {
$attributes[] = $name.'="'.$value.'"';
}
if (in_array($tag, self::$voidElements)) {
return '<'.$tag.(!empty($attributes) ? ' '.implode(' ', $attributes) : '').'>';
} else {
return '<'.$tag.(!empty($attributes) ? ' '.implode(' ', $attributes) : '').'>'.$html.'</'.$tag.'>';
}
}
|
php
|
{
"resource": ""
}
|
q241003
|
ParentBouncer.routeContainsParent
|
train
|
protected function routeContainsParent()
{
// get just the base url
$route = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
// lets split it into pieces
$parts = explode('/', $route);
// if a resource has a parent, it should be in the form /dogs/1/puppies
// so the parent resource should be 2 spots before the child resource
$resourcePosition = array_search($this->config->getResource(), $parts);
return isset($parts[$resourcePosition - 2]);
}
|
php
|
{
"resource": ""
}
|
q241004
|
Redis._connection
|
train
|
protected function _connection(array $config)
{
$redis = new \Redis;
$host = empty($config['host']) ? self::DEFAULT_HOST : $config['host'];
$port = empty($config['port']) ? self::DEFAULT_PORT : $config['port'];
$timeout = empty($config['timeout']) ? self::DEFAULT_TIMEOUT : $config['timeout'];
$connect = empty($config['persistent']) ? 'connect' : 'pconnect';
$redis->$connect($host, $port, $timeout);
return $redis;
}
|
php
|
{
"resource": ""
}
|
q241005
|
Redis._master
|
train
|
protected function _master()
{
if (null === $this->_master) {
$this->_master = $this->_connection($this->_config_master);
}
return $this->_master;
}
|
php
|
{
"resource": ""
}
|
q241006
|
Redis._slave
|
train
|
protected function _slave()
{
if (empty($this->_config_slaves)) {
return $this->_master();
}
if (null === $this->_slave) {
$count = count($this->_config_slaves);
$index = mt_rand(0, $count-1);
$config = $this->_config_slaves[$index];
$this->_slave = $this->_connection($config);
}
return $this->_slave;
}
|
php
|
{
"resource": ""
}
|
q241007
|
Adapter.run
|
train
|
public function run()
{
$this->init();
// Loop forever, except when a maximum number of requests is configured
$requestsHandled = 0;
while ($this->maxRequests === null || $requestsHandled < $this->maxRequests) {
$this->doStep();
$requestsHandled++;
}
}
|
php
|
{
"resource": ""
}
|
q241008
|
Adapter.init
|
train
|
private function init()
{
if ($this->encoder === null) {
// Send the adapter config as JSON payload to the host
$config = new AdapterConfig(
$this->codec->getName(),
$this->getAdapterType(),
$this->getExtraConfig()
);
Codecs::json()->newEncoder($this->output)->useNewlines(false)->encode($config);
// Set up encoder / decoder for further communication
$this->decoder = $this->codec->newDecoder($this->input);
$this->encoder = $this->codec->newEncoder($this->output);
}
}
|
php
|
{
"resource": ""
}
|
q241009
|
ClassGenerator.generateTraitMethods
|
train
|
protected function generateTraitMethods()
{
if (empty($this->_traitMethodsAliases)) {
return;
}
$this->addProperty(
'___classMocker_traitMethods',
$this->_traitMethodsAliases,
PropertyGenerator::FLAG_PRIVATE | PropertyGenerator::FLAG_STATIC
);
foreach (array_keys($this->_traitMethodsAliases) as $methodName) {
if (!$this->canGenerateMethod($methodName)) {
continue;
}
if (!$this->isValidTraitMethod($methodName)) {
throw new \RuntimeException(
sprintf(
"Trait magic method %s::%s() is not valid, use %s() instead",
$this->getName(),
$methodName,
'_' . $methodName
)
);
}
$this->generateMethod($methodName);
}
}
|
php
|
{
"resource": ""
}
|
q241010
|
ClassGenerator.canGenerateMethod
|
train
|
public function canGenerateMethod($methodName)
{
/**
* any special methods only called by the base mock class
* and therefor should not be made accessible
*
* @see \JSiefer\ClassMocker\Mock\BaseMock::__callTraitMethods()
*/
switch ($methodName) {
case BaseMock::CALL:
case BaseMock::CONSTRUCTOR:
case BaseMock::GETTER:
case BaseMock::SETTER:
case BaseMock::INIT:
return false;
}
return true;
}
|
php
|
{
"resource": ""
}
|
q241011
|
ClassGenerator.useTrait
|
train
|
public function useTrait(\ReflectionClass $trait)
{
$alias = 'trait' . ($this->_traitsIdx++);
$alias .= '_' . str_replace('\\', '__', $trait->getName());
$alias = 'Trait_' . substr(md5($alias), 0, 10) . '_' .$trait->getShortName();
$this->addUse($trait->getName(), $alias);
$this->addTrait($alias);
foreach ($trait->getMethods() as $method) {
if ($method->isAbstract()) {
continue;
}
$this->registerTraitMethod($alias, $method);
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q241012
|
ClassGenerator.registerTraitMethod
|
train
|
protected function registerTraitMethod($trait, \ReflectionMethod $method)
{
$name = $method->getName();
$this->_method[$name] = $method;
$alias = '__' . lcfirst($trait) . ucfirst($name);
$this->addTraitAlias($trait . '::' . $name, $alias);
$this->addTraitMethod($trait, $name);
if (!isset($this->_traitMethodsAliases[$name])) {
$this->_traitMethodsAliases[$name] = [];
}
$this->_traitMethodsAliases[$name][] = $alias;
}
|
php
|
{
"resource": ""
}
|
q241013
|
ClassGenerator.addTraitMethod
|
train
|
protected function addTraitMethod($trait, $method)
{
if (!isset($this->_traitMethods[$method])) {
$this->_traitMethods[$method] = [];
} else {
foreach ($this->_traitMethods[$method] as $prefTrait) {
$this->removeTraitOverride($prefTrait . '::' . $method);
}
$traits = implode(', ', $this->_traitMethods[$method]);
$this->addTraitOverride($trait . '::' . $method, $traits);
}
$this->_traitMethods[$method][] = $trait;
}
|
php
|
{
"resource": ""
}
|
q241014
|
Response.encode
|
train
|
public function encode($result)
{
if ('form' == $this->type) {
array_walk_recursive($result[0], array($this, 'utf8'));
$response = new SfResponse("<html><body><textarea>".json_encode($result[0])."</textarea></body></html>");
$response->headers->set('Content-Type', 'text/html');
return $response;
} else {
if ($this->responseEncode){
// @todo: check utf8 config option from bundle
array_walk_recursive($result, array($this, 'utf8'));
}
$response = new SfResponse(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
|
php
|
{
"resource": ""
}
|
q241015
|
Response.utf8
|
train
|
private function utf8(&$value, &$key)
{
if (is_string($value)) {
$value = utf8_encode($value);
}
if (is_array($value)) {
array_walk_recursive($value, array($this, 'utf8'));
}
}
|
php
|
{
"resource": ""
}
|
q241016
|
SourceCodeWatcher.setCompilerRoot
|
train
|
public function setCompilerRoot($path)
{
$path = realpath($path);
if (is_dir($path)) {
$this->root = $path;
}
}
|
php
|
{
"resource": ""
}
|
q241017
|
SourceCodeWatcher.addWatcher
|
train
|
public function addWatcher(Watcher\WatcherInterface $watcher)
{
$type = $watcher->getType();
$this->watchers[$type] = $watcher;
}
|
php
|
{
"resource": ""
}
|
q241018
|
SourceCodeWatcher.addConfig
|
train
|
public function addConfig($config, $watcher)
{
if (!$this->root) {
return;
}
$config = realpath($config);
$filesystem = new Filesystem();
$relativePath = $filesystem->makePathRelative($config, $this->root);
if (substr($relativePath, 0, 2) == "..") {
return;
}
if (!isset($this->configs[$watcher])) {
$this->configs[$watcher] = array();
}
$this->configs[$watcher][] = $config;
}
|
php
|
{
"resource": ""
}
|
q241019
|
SourceCodeWatcher.compile
|
train
|
public function compile()
{
if (!$this->enabled || $this->env !== "dev") {
return;
}
foreach ($this->watchers as $name => $watcher) {
if (isset($this->configs[$name])) {
foreach ($this->configs[$name] as $configPath) {
$files = $watcher->getChildren($configPath);
if ($this->cache->isFresh($configPath, $files)) {
$watcher->compile($configPath);
$this->cache->write($configPath, $files);
}
}
}
}
}
|
php
|
{
"resource": ""
}
|
q241020
|
AbstractInstallationManager.getInstaller
|
train
|
protected function getInstaller(): BaseInstaller
{
return Installer::create($this->io, $this->composer, $this->input);
}
|
php
|
{
"resource": ""
}
|
q241021
|
AbstractInstallationManager.findBestVersionForPackage
|
train
|
protected function findBestVersionForPackage(string $name): string
{
// find the latest version allowed in this pool
$package = $this->versionSelector->findBestCandidate($name, null, null, 'stable');
if ($package === false) {
throw new InvalidArgumentException(\sprintf(
'Could not find package %s at any version for your minimum-stability (%s).'
. ' Check the package spelling or your minimum-stability.',
$name,
$this->stability
));
}
return $this->versionSelector->findRecommendedRequireVersion($package);
}
|
php
|
{
"resource": ""
}
|
q241022
|
AbstractInstallationManager.updateRootComposerJson
|
train
|
protected function updateRootComposerJson(array $requires, array $devRequires, int $type): RootPackageInterface
{
$this->io->writeError('Updating root package');
$this->updateRootPackageRequire($requires, $type);
$this->updateRootPackageDevRequire($devRequires, $type);
return $this->rootPackage;
}
|
php
|
{
"resource": ""
}
|
q241023
|
AbstractInstallationManager.updateComposerJson
|
train
|
protected function updateComposerJson(array $requires, array $devRequires, int $type): void
{
$this->io->writeError('Updating composer.json');
if ($type === self::ADD) {
$jsonManipulator = new JsonManipulator(\file_get_contents($this->jsonFile->getPath()));
$sortPackages = $this->composer->getConfig()->get('sort-packages') ?? false;
foreach ($requires as $name => $version) {
$jsonManipulator->addLink('require', $name, $version, $sortPackages);
}
foreach ($devRequires as $name => $version) {
$jsonManipulator->addLink('require-dev', $name, $version, $sortPackages);
}
\file_put_contents($this->jsonFile->getPath(), $jsonManipulator->getContents());
} elseif ($type === self::REMOVE) {
$jsonFileContent = $this->jsonFile->read();
foreach ($requires as $packageName => $version) {
unset($jsonFileContent['require'][$packageName]);
}
foreach ($devRequires as $packageName => $version) {
unset($jsonFileContent['require-dev'][$packageName]);
}
$this->jsonFile->write($jsonFileContent);
}
}
|
php
|
{
"resource": ""
}
|
q241024
|
AbstractInstallationManager.runInstaller
|
train
|
protected function runInstaller(RootPackageInterface $rootPackage, array $whitelistPackages): int
{
$this->io->writeError('Running an update to install dependent packages');
$this->composer->setPackage($rootPackage);
$installer = $this->getInstaller();
$installer->setUpdateWhitelist($whitelistPackages);
return $installer->run();
}
|
php
|
{
"resource": ""
}
|
q241025
|
AbstractInstallationManager.updateRootPackageRequire
|
train
|
protected function updateRootPackageRequire(array $packages, int $type): void
{
$requires = $this->manipulateRootPackage(
$packages,
$type,
$this->rootPackage->getRequires()
);
$this->rootPackage->setRequires($requires);
}
|
php
|
{
"resource": ""
}
|
q241026
|
AbstractInstallationManager.updateRootPackageDevRequire
|
train
|
protected function updateRootPackageDevRequire(array $packages, int $type): void
{
$devRequires = $this->manipulateRootPackage(
$packages,
$type,
$this->rootPackage->getDevRequires()
);
$this->rootPackage->setDevRequires($devRequires);
}
|
php
|
{
"resource": ""
}
|
q241027
|
AbstractInstallationManager.manipulateRootPackage
|
train
|
protected function manipulateRootPackage(array $packages, int $type, array $requires): array
{
if ($type === self::ADD) {
foreach ($packages as $packageName => $version) {
$requires[$packageName] = new Link(
'__root__',
$packageName,
(new VersionParser())->parseConstraints($version),
'relates to',
$version
);
}
} elseif ($type === self::REMOVE) {
foreach ($packages as $packageName => $version) {
unset($requires[$packageName]);
}
}
return $requires;
}
|
php
|
{
"resource": ""
}
|
q241028
|
UserController.actionIndex
|
train
|
public function actionIndex()
{
$searchModel = new UserSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
$statusArray = User::getStatusArray();
$roleArray = ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'description');
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'statusArray' => $statusArray,
'roleArray' => $roleArray
]);
}
|
php
|
{
"resource": ""
}
|
q241029
|
UserController.actionUpdate
|
train
|
public function actionUpdate($id)
{
$roles = ArrayHelper::map(Yii::$app->authManager->getRoles(), 'name', 'description');
$user_permit = array_keys(Yii::$app->authManager->getRolesByUser($id));
$user = $this->findUser($id);
//return $this->render('view', [
// 'user' => $user,
// 'roles' => $roles,
// 'user_permit' => $user_permit,
// 'moduleName' => Yii::$app->controller->module->id
//]);
return $this->render('update', [
'user' => $user,
'roles' => $roles,
'user_permit' => $user_permit,
'moduleName' => Yii::$app->controller->module->id
]);
/* $user = $this->findUser($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
//роли
Yii::$app->authManager->revokeAll($user->getId());
if(Yii::$app->request->post('roles')){
foreach(Yii::$app->request->post('roles') as $role)
{
$new_role = Yii::$app->authManager->getRole($role);
Yii::$app->authManager->assign($new_role, $user->getId());
}
}
return $this->redirect(Url::to(["/".Yii::$app->controller->module->id."/user/view", 'id' => $user->getId()]));*/
}
|
php
|
{
"resource": ""
}
|
q241030
|
UserController.actionMassDelete
|
train
|
public function actionMassDelete()
{
if (($ids = Yii::$app->request->post('ids')) !== null) {
$models = $this->findUser($ids);
foreach ($models as $model) {
$model->delete($model);
}
return $this->redirect(['index']);
} else {
throw new HttpException(400);
}
}
|
php
|
{
"resource": ""
}
|
q241031
|
UserController.findUser
|
train
|
private function findUser($id)
{
if (is_array($id)) {
/** @var User $user */
$model = User::findIdentities($id);
} else {
/** @var User $user */
$model = User::findIdentity($id);
}
if ($model !== null) {
return $model;
} else {
throw new NotFoundHttpException('User not found');
}
}
|
php
|
{
"resource": ""
}
|
q241032
|
Controller.getBackLink
|
train
|
public function getBackLink($fallback = '')
{
$url = '';
if ($this->owner->Request) {
if ($this->owner->Request->requestVar('BackURL')) {
$url = $this->owner->Request->requestVar('BackURL');
} else {
if ($this->owner->Request->isAjax() && $this->owner->Request->getHeader('X-Backurl')) {
$url = $this->owner->Request->getHeader('X-Backurl');
} else {
if ($this->owner->Request->getHeader('Referer')) {
$url = $this->owner->Request->getHeader('Referer');
}
}
}
}
if (!$url) {
$url = $fallback ? $fallback : singleton('director')->baseURL();
}
return $url;
}
|
php
|
{
"resource": ""
}
|
q241033
|
Controller.displayNiceView
|
train
|
public function displayNiceView($controller = null, $url = '', $action = '')
{
if (!$controller) {
$controller = $this->owner;
}
return singleton('director')->create_view($controller, $url, $action);
}
|
php
|
{
"resource": ""
}
|
q241034
|
Controller.respondToFormAppropriately
|
train
|
public function respondToFormAppropriately(array $params, $form = null, $redirect = '')
{
if ($redirect && !isset($params['redirect'])) {
$params['redirect'] = $redirect;
}
if ($this->owner->Request->isAjax()) {
if (!isset($params['code'])) {
$params['code'] = 200;
}
if (!isset($params['code'])) {
$params['status'] = 'success';
}
return singleton('director')->ajax_response($params, $params['code'], $params['status']);
} else {
if (isset($params['redirect'])) {
$this->owner->redirect($params['redirect']);
}
if ($form && isset($params['message'])) {
$form->sessionMessage($params['message'], 'good');
}
if (!$this->owner->redirectedTo()) {
$this->owner->redirectBack();
}
}
}
|
php
|
{
"resource": ""
}
|
q241035
|
AbstractInvokable._invokeIsset
|
train
|
protected function _invokeIsset($name)
{
if (!self::__isInvokable($name)) {
return $this;
}
$is_static = self::__isStatic($name);
$property = $this->findPropertyName($name);
return !empty($property);
}
|
php
|
{
"resource": ""
}
|
q241036
|
AbstractInvokable._invokeReset
|
train
|
protected function _invokeReset($name)
{
if (!self::__isInvokable($name)) {
return $this;
}
$is_static = self::__isStatic($name);
$property = $this->findPropertyName($name);
if (!empty($property)) {
if ($is_static) {
return $this->_invokeUnset($name);
} else {
$classname = get_class($this);
$reflection = new ReflectionClass($classname);
$properties = $reflection->getDefaultProperties();
if (!empty($properties) && array_key_exists($property, $properties)) {
$this->{$property} = $properties[$property];
}
}
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q241037
|
AbstractInvokable._invokeGet
|
train
|
protected function _invokeGet($name, $default = null)
{
if (!self::__isInvokable($name)) {
return null;
}
$is_static = self::__isStatic($name);
$property = $this->findPropertyName($name);
if (!empty($property)) {
return $is_static ? @$this::${$property} : @$this->{$property};
}
return $default;
}
|
php
|
{
"resource": ""
}
|
q241038
|
AbstractInvokable._invokeSet
|
train
|
protected function _invokeSet($name, $value)
{
if (!self::__isInvokable($name)) {
return $this;
}
$is_static = self::__isStatic($name);
$property = $this->findPropertyName($name);
if (!empty($property)) {
if ($is_static) {
$this::${$property} = $value;
} else {
$this->{$property} = $value;
}
}
return $this;
}
|
php
|
{
"resource": ""
}
|
q241039
|
AbstractInvokable.__isInvokable
|
train
|
private function __isInvokable($name)
{
if (!$this->__isCalled) {
$property = $this->findPropertyName($name);
if (!empty($property)) {
$reflection = new ReflectionProperty(get_class($this), $property);
return $reflection->isPublic();
}
}
return true;
}
|
php
|
{
"resource": ""
}
|
q241040
|
AbstractInvokable.__isStatic
|
train
|
private function __isStatic($name)
{
$property = $this->findPropertyName($name);
if (!empty($property)) {
$reflection = new ReflectionProperty(get_class($this), $property);
return $reflection->isStatic();
}
return true;
}
|
php
|
{
"resource": ""
}
|
q241041
|
AbstractInvokable.__isInvokableStatic
|
train
|
private static function __isInvokableStatic($name)
{
$classname = get_called_class();
$reflection_class = new ReflectionClass($classname);
$properties = $reflection_class->getStaticProperties();
$property = self::findPropertyNameStatic($name, $classname);
if (!empty($property)) {
$reflection = new ReflectionProperty($classname, $property);
return (bool) !($reflection->isPrivate());
}
return true;
}
|
php
|
{
"resource": ""
}
|
q241042
|
AbstractInvokable.findPropertyNameStatic
|
train
|
public static function findPropertyNameStatic($name, $object)
{
$property = null;
if (property_exists($object, $name)) {
$property = $name;
} else {
// _name
$underscore_name = '_'.$name;
if (property_exists($object, $underscore_name)) {
$property = $underscore_name;
} else {
// __name
$doubleunderscore_name = '__'.$name;
if (property_exists($object, $doubleunderscore_name)) {
$property = $doubleunderscore_name;
}
}
}
return $property;
}
|
php
|
{
"resource": ""
}
|
q241043
|
NotIdentical.isValid
|
train
|
public function isValid($value, array $context = null)
{
$this->setValue($value);
$token = $this->getToken();
if (!$this->getLiteral() && $context !== null) {
if (is_array($token)) {
while (is_array($token)) {
$key = key($token);
if (!isset($context[$key])) {
break;
}
$context = $context[$key];
$token = $token[$key];
}
}
// if $token is an array it means the above loop didn't went all the way down to the leaf,
// so the $token structure doesn't match the $context structure
if (is_array($token) || !isset($context[$token])) {
$token = $this->getToken();
} else {
$token = $context[$token];
}
}
if ($token === null) {
$this->error(self::MISSING_TOKEN);
return false;
}
$strict = $this->getStrict();
if (!($strict && ($value !== $token)) || (!$strict && ($value != $token))) {
$this->error(self::SAME);
return false;
}
return true;
}
|
php
|
{
"resource": ""
}
|
q241044
|
AbstractEntityService.setEntityClass
|
train
|
public function setEntityClass($className)
{
if (
!class_exists($className) ||
!is_subclass_of($className, EntityInterface::class)
) {
throw new InvalidEntityClassException(
"Class '{$className}' does not implements the " .
"Slick\Orm\EntityInterface interface."
);
}
$this->entityClass = $className;
return $this;
}
|
php
|
{
"resource": ""
}
|
q241045
|
AbstractEntityService.getEntityClassName
|
train
|
public function getEntityClassName()
{
if (null == $this->entityClass) {
$this->setEntityClass(get_class($this->getEntity()));
}
return $this->entityClass;
}
|
php
|
{
"resource": ""
}
|
q241046
|
ClientFactory.makeFromEnvironment
|
train
|
public function makeFromEnvironment()
{
$env = new EnvUtils();
// Check that we have all variables we need
if (!$env->hasBearerKey()) {
throw new Exception(
'TUTUM_AUTH is not set. Unable to create from environment'
);
}
$client = new Client('', '');
$client->setBearerKey($env->getBearerKey());
return $client;
}
|
php
|
{
"resource": ""
}
|
q241047
|
DbExecuter.executeSQL
|
train
|
public function executeSQL($key, $query, $disable_foreign_key_checks = true, $entity=null)
{
if ($entity !== null && $entity != $this->last_entity) {
$this->log("------------------------------------------------------");
$this->log("Entity: '$entity'");
$this->log("------------------------------------------------------");
$this->last_entity = $entity;
}
$this->log(" * Sync::executeSQL '$key'...");
$total_time_start = microtime(true);
if ($disable_foreign_key_checks) {
$this->adapter->query('set foreign_key_checks=0');
$this->log(" * FK : Foreign key check disabled");
}
try {
$time_start = microtime(true);
$result = $this->adapter->query($query, ZendDb::QUERY_MODE_EXECUTE);
$affected_rows = $result->getAffectedRows();
// Log stuffs
$time_stop = microtime(true);
$time = number_format(($time_stop - $time_start), 2);
$formatted_query = preg_replace('/(\n)|(\r)|(\t)/', ' ', $query);
$formatted_query = preg_replace('/(\ )+/', ' ', $formatted_query);
$this->log(" * SQL: " . substr(trim($formatted_query), 0, 70) . '...') ;
$this->log(" * SQL: Query time $time sec(s))");
} catch (\Exception $e) {
$err = $e->getMessage();
$msg = "Error running query ({$err}) : \n--------------------\n$query\n------------------\n";
$this->log("[+] $msg\n");
if ($disable_foreign_key_checks) {
$this->log("[Error] Error restoring foreign key checks");
$this->adapter->query('set foreign_key_checks=1');
}
throw new \Exception($msg);
}
if ($disable_foreign_key_checks) {
$time_start = microtime(true);
$this->adapter->query('set foreign_key_checks=1');
$time_stop = microtime(true);
$time = number_format(($time_stop - $time_start), 2);
$this->log(" * FK : Foreign keys restored");
}
$time_stop = microtime(true);
$time = number_format(($time_stop - $total_time_start), 2);
$this->log(" * Time: $time secs, affected rows $affected_rows.");
}
|
php
|
{
"resource": ""
}
|
q241048
|
Configurable.applyConfig
|
train
|
public function applyConfig(array $config = []) {
$parent = $this;
$defaults = isset($this->_config) ? $this->_config : [];
// Inherit config from parents
while ($parent = get_parent_class($parent)) {
$props = get_class_vars($parent);
if (isset($props['_config'])) {
$defaults = Hash::merge($props['_config'], $defaults);
}
}
$this->__config = new ConfigAugment($config, $defaults);
return $this;
}
|
php
|
{
"resource": ""
}
|
q241049
|
UserAbstract.setEmail
|
train
|
public function setEmail($email)
{
$email = (string) $email;
if ($this->exists() && $this->email !== $email) {
$this->updated['email'] = true;
}
$this->email = $email;
return $this;
}
|
php
|
{
"resource": ""
}
|
q241050
|
UserAbstract.setPassword
|
train
|
public function setPassword($password)
{
$password = (string) $password;
if ($this->exists() && $this->password !== $password) {
$this->updated['password'] = true;
}
$this->password = $password;
return $this;
}
|
php
|
{
"resource": ""
}
|
q241051
|
UserAbstract.setPseudo
|
train
|
public function setPseudo($pseudo)
{
$pseudo = (string) $pseudo;
if ($this->exists() && $this->pseudo !== $pseudo) {
$this->updated['pseudo'] = true;
}
$this->pseudo = $pseudo;
return $this;
}
|
php
|
{
"resource": ""
}
|
q241052
|
UserAbstract.setFirstname
|
train
|
public function setFirstname($firstname)
{
$firstname = ($firstname === null ? $firstname : (string) $firstname);
if ($this->exists() && $this->firstname !== $firstname) {
$this->updated['firstname'] = true;
}
$this->firstname = $firstname;
return $this;
}
|
php
|
{
"resource": ""
}
|
q241053
|
UserAbstract.setLastname
|
train
|
public function setLastname($lastname)
{
$lastname = ($lastname === null ? $lastname : (string) $lastname);
if ($this->exists() && $this->lastname !== $lastname) {
$this->updated['lastname'] = true;
}
$this->lastname = $lastname;
return $this;
}
|
php
|
{
"resource": ""
}
|
q241054
|
UserAbstract.setDateRegister
|
train
|
public function setDateRegister($dateRegister)
{
$dateRegister = ($dateRegister === null ? $dateRegister : (string) $dateRegister);
if ($this->exists() && $this->dateRegister !== $dateRegister) {
$this->updated['dateRegister'] = true;
}
$this->dateRegister = $dateRegister;
return $this;
}
|
php
|
{
"resource": ""
}
|
q241055
|
UserAbstract.setIsActivated
|
train
|
public function setIsActivated($isActivated)
{
$isActivated = (int) $isActivated;
if ($this->exists() && $this->isActivated !== $isActivated) {
$this->updated['isActivated'] = true;
}
$this->isActivated = $isActivated;
return $this;
}
|
php
|
{
"resource": ""
}
|
q241056
|
UserAbstract.setDateActivation
|
train
|
public function setDateActivation($dateActivation)
{
$dateActivation = ($dateActivation === null ? $dateActivation : (string) $dateActivation);
if ($this->exists() && $this->dateActivation !== $dateActivation) {
$this->updated['dateActivation'] = true;
}
$this->dateActivation = $dateActivation;
return $this;
}
|
php
|
{
"resource": ""
}
|
q241057
|
UserAbstract.setCodeActivation
|
train
|
public function setCodeActivation($codeActivation)
{
$codeActivation = ($codeActivation === null ? $codeActivation : (string) $codeActivation);
if ($this->exists() && $this->codeActivation !== $codeActivation) {
$this->updated['codeActivation'] = true;
}
$this->codeActivation = $codeActivation;
return $this;
}
|
php
|
{
"resource": ""
}
|
q241058
|
UserAbstract.setAvatar
|
train
|
public function setAvatar($avatar)
{
$avatar = (string) $avatar;
if ($this->exists() && $this->avatar !== $avatar) {
$this->updated['avatar'] = true;
}
$this->avatar = $avatar;
return $this;
}
|
php
|
{
"resource": ""
}
|
q241059
|
Bierdopje.getShowById
|
train
|
public function getShowById($showId)
{
$response = $this->request('/GetShowById/' . $showId);
if ( $response->response->status == 'false' )
return null;
$show = $response->response;
$show = $this->formatShow($show);
return $show;
}
|
php
|
{
"resource": ""
}
|
q241060
|
Bierdopje.findShowByName
|
train
|
public function findShowByName($showName)
{
$response = $this->request('/FindShowByName/' . $showName);
if ( $response->response->status == 'false' )
return null;
$shows = $response->response->results->result;
if ( count($shows) <= 0 )
return null;
$show = $shows[0];
$show = $this->formatShow($show);
return $show;
}
|
php
|
{
"resource": ""
}
|
q241061
|
Bierdopje.getShowByName
|
train
|
public function getShowByName($showName, $isLinkName = false)
{
$response = $this->request('/GetShowByName/' . $showName . '/' . $isLinkName);
if ( $response->response->status == 'false' )
return null;
$show = $response->response;
$show = $this->formatShow($show);
return $show;
}
|
php
|
{
"resource": ""
}
|
q241062
|
Bierdopje.getShowByTvdbId
|
train
|
public function getShowByTvdbId($tvdbId)
{
$response = $this->request('/GetShowByTVDBID/' . $tvdbId);
if ( $response->response->status == 'false' )
return null;
$show = $this->formatShow($response->response);
return $show;
}
|
php
|
{
"resource": ""
}
|
q241063
|
Bierdopje.getEpisodesOfSeason
|
train
|
public function getEpisodesOfSeason($showId, $season)
{
$response = $this->request('/GetEpisodesForSeason/' . $showId . '/' . $season);
if ( $response->response->status == 'false' )
return null;
$episodes = $response->response->results->result;
if ( count($episodes) <= 0 )
return null;
$episodeList = [];
foreach ( $episodes as $episode )
$episodeList[] = $this->formatEpisode($episode);
return $episodeList;
}
|
php
|
{
"resource": ""
}
|
q241064
|
Bierdopje.getEpisodeById
|
train
|
public function getEpisodeById($episodeId)
{
$response = $this->request('/GetEpisodeById/' . $episodeId);
if ( $response->response->status == 'false' )
return null;
if ($response->response->cached == 'false') {
$episode = $response->response;
} else {
$episode = $response->response->results;
}
$episode = $this->formatEpisode($episode);
return $episode;
}
|
php
|
{
"resource": ""
}
|
q241065
|
Bierdopje.formatEpisode
|
train
|
private function formatEpisode($original)
{
$show = new \stdClass();
$show->id = (int) $original->episodeid;
$show->tvdbId = (int) $original->tvdbid;
$show->title = (string) $original->title;
$show->showlink = (string) $original->showlink;
$show->episodelink = (string) $original->episodelink;
$show->airDate = strlen($original->airdate)
? Carbon::createFromFormat("d-m-Y", (string) $original->airdate)
: null;
$show->season = (int) $original->season;
$show->episode = (int) $original->episode;
$show->epNumber = (int) $original->epnumber;
$show->score = (float) str_replace(',', '.', $original->score);
$show->votes = (int) $original->votes;
$show->formatted = (string) $original->formatted;
$show->is_special = ((string) $original->is_special) === "true";
$show->summary = (string) $original->summary;
$show->updated = Carbon::createFromTimestamp((int) $original->updated);
return $show;
}
|
php
|
{
"resource": ""
}
|
q241066
|
Bierdopje.formatShow
|
train
|
private function formatShow($original)
{
$show = new \stdClass();
$show->id = (int) $original->showid;
$show->tvdbId = (int) $original->tvdbid;
$show->name = (string) $original->showname;
$show->link = (string) $original->showlink;
$show->firstAired = strlen($original->firstaired)
? Carbon::createFromFormat('Y-m-d', (string) $original->firstaired)
: null;
$show->lastAired = strlen($original->lastaired)
? Carbon::createFromFormat('Y-m-d', (string) $original->lastaired)
: null;
$show->nextEpisode = strlen($original->nextepisode)
? Carbon::createFromFormat('Y-m-d', (string) $original->nextepisode)
: null;
$show->seasons = (int) $original->seasons;
$show->episodes = (int) $original->episodes;
$show->genres = $original->genres->result;
$show->score = (float) str_replace(',', '.', $original->score);
$show->runtime = (float) str_replace(',', '.', $original->runtime);
$show->favorites = (int) $original->favorites;
$show->showstatus = (string) $original->showstatus;
$show->airtime = (string) $original->airtime;
$show->summary = (string) $original->summary;
$show->updated = Carbon::createFromTimestamp((int) $original->updated);
$genres = [];
foreach ( $show->genres as $key => $genre ) {
$genre = (string) $genre;
$genre = ucfirst($genre);
$genres[] = $genre;
}
$show->genres = $genres;
return $show;
}
|
php
|
{
"resource": ""
}
|
q241067
|
Bierdopje.request
|
train
|
protected function request($path)
{
$response = $this->client->get($this->url . $path);
if ( $response->getStatusCode() != 200 )
throw new \Exception('Bierdopje.com not available');
$response = $this->xmlToObj($response->getBody());
return $response;
}
|
php
|
{
"resource": ""
}
|
q241068
|
Bierdopje.xmlToObj
|
train
|
private function xmlToObj($fileContents)
{
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
$simpleXml = simplexml_load_string($fileContents, null, LIBXML_NOCDATA);
return $simpleXml;
}
|
php
|
{
"resource": ""
}
|
q241069
|
Binary.slice
|
train
|
public static function slice($string, $start, $length = null)
{
if (function_exists('mb_substr')) {
return mb_substr($string, $start, $length, '8bit');
}
return substr($string, $start, $length);
}
|
php
|
{
"resource": ""
}
|
q241070
|
Binary.base64Encode
|
train
|
public static function base64Encode($data, $url = false)
{
if ($url) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
} else {
return base64_encode($data);
}
}
|
php
|
{
"resource": ""
}
|
q241071
|
Binary.base64Decode
|
train
|
public static function base64Decode($data, $url = true)
{
if ($url) {
return base64_decode(strtr($data, '-_', '+/'));
} else {
return base64_decode($data);
}
}
|
php
|
{
"resource": ""
}
|
q241072
|
OTPAuthenticate.generateCode
|
train
|
public function generateCode($secret, $counter, $algorithm = 'sha512')
{
$key = $this->base32->decode($secret);
if (empty($counter))
{
return '';
}
$hash = hash_hmac($algorithm, $this->getBinaryCounter($counter), $key, true);
return str_pad($this->truncate($hash), $this->code_length, '0', STR_PAD_LEFT);
}
|
php
|
{
"resource": ""
}
|
q241073
|
OTPAuthenticate.checkTOTP
|
train
|
public function checkTOTP($secret, $code, $hash_type = 'sha512')
{
$time = $this->getTimestampCounter(time());
for ($i = -1; $i <= 1; $i++)
{
if ($this->stringCompare($code, $this->generateCode($secret, $time + $i, $hash_type)) === true)
{
return true;
}
}
return false;
}
|
php
|
{
"resource": ""
}
|
q241074
|
OTPAuthenticate.checkHOTP
|
train
|
public function checkHOTP($secret, $counter, $code, $hash_type = 'sha512')
{
return $this->stringCompare($code, $this->generateCode($secret, $counter, $hash_type));
}
|
php
|
{
"resource": ""
}
|
q241075
|
OTPAuthenticate.truncate
|
train
|
protected function truncate($hash)
{
$truncated_hash = 0;
$offset = ord(substr($hash, -1)) & 0xF;
// Truncate hash using supplied sha1 hash
for ($i = 0; $i < 4; ++$i)
{
$truncated_hash <<= 8;
$truncated_hash |= ord($hash[$offset + $i]);
}
// Truncate to a smaller number of digits.
$truncated_hash &= 0x7FFFFFFF;
$truncated_hash %= self::VERIFICATION_CODE_MODULUS;
return $truncated_hash;
}
|
php
|
{
"resource": ""
}
|
q241076
|
OTPAuthenticate.stringCompare
|
train
|
public function stringCompare($string_a, $string_b)
{
$diff = strlen($string_a) ^ strlen($string_b);
for ($i = 0; $i < strlen($string_a) && $i < strlen($string_b); $i++)
{
$diff |= ord($string_a[$i]) ^ ord($string_b[$i]);
}
return $diff === 0;
}
|
php
|
{
"resource": ""
}
|
q241077
|
OTPAuthenticate.generateSecret
|
train
|
public function generateSecret($length = 10)
{
$strong_secret = false;
// Try to get $crypto_strong to evaluate to true. Give it 5 tries.
for ($i = 0; $i < 5; $i++)
{
$secret = openssl_random_pseudo_bytes($length, $strong_secret);
if ($strong_secret === true)
{
return $this->base32->encode($secret);
}
}
return '';
}
|
php
|
{
"resource": ""
}
|
q241078
|
Dependency.getIdentifier
|
train
|
public function getIdentifier()
{
$identifier = $this->getFromNode()->getIdentifier()
. '-'
. $this->getType()
. '-'
. $this->getToNode()->getIdentifier();
return $identifier;
}
|
php
|
{
"resource": ""
}
|
q241079
|
Translator.addSource
|
train
|
public function addSource( string $sourceName, ISource $source ) : Translator
{
$source->setLocale( $this->_locale );
$this->_sources[ $sourceName ] = $source;
return $this;
}
|
php
|
{
"resource": ""
}
|
q241080
|
Translator.read
|
train
|
public function read( $identifier, ?string $sourceName = null, $defaultTranslation = false )
{
if ( null !== $sourceName && isset( $this->_sources[ $sourceName ] ) )
{
// read from specific source
return $this->_sources[ $sourceName ]->read( $identifier, $defaultTranslation );
}
foreach ( $this->_sources as $source )
{
$result = $source->read( $identifier, static::USS );
if ( static::USS !== $result )
{
return $result;
}
}
return $defaultTranslation;
}
|
php
|
{
"resource": ""
}
|
q241081
|
Translator.GetInstance
|
train
|
public static function GetInstance() : Translator
{
if ( null === self::$_instance )
{
self::$_instance = new Translator();
}
return self::$_instance;
}
|
php
|
{
"resource": ""
}
|
q241082
|
ORM.emptyConstruct
|
train
|
private function emptyConstruct()
{
$this->getModel();
$this->getTable();
$this->columns();
$this->key();
$this->_state = CRUD::CREATE_STAT;
}
|
php
|
{
"resource": ""
}
|
q241083
|
ORM.mainConstruct
|
train
|
private function mainConstruct($key = null, $fail = false)
{
$this->getModel();
$this->getTable();
$this->columns();
$this->key();
if (!is_null($key)) {
$this->struct($key, $fail);
$this->_state = CRUD::UPDATE_STAT;
} else {
$this->_state = CRUD::CREATE_STAT;
}
}
|
php
|
{
"resource": ""
}
|
q241084
|
ORM.secondConstruct
|
train
|
private function secondConstruct($data)
{
$this->getModel($data);
$this->getTable($data);
$this->columns($data);
$this->key($data);
$this->fill($data);
$this->_state = CRUD::UPDATE_STAT;
}
|
php
|
{
"resource": ""
}
|
q241085
|
ORM.getTable
|
train
|
protected function getTable($data = null)
{
if (is_null($data)) {
$this->_table = static::$table;
$this->_prifixTable = (Config::get('database.prefixing') ? Config::get('database.prefixe') : '').static::$table;
//
if (!$this->checkTable()) {
throw new TableNotFoundException(static::$table);
}
//
return $this->_prifixTable;
} else {
$this->_prifixTable = $data['prifixTable'];
$this->_table = static::$table;
}
}
|
php
|
{
"resource": ""
}
|
q241086
|
ORM.checkTable
|
train
|
protected function checkTable()
{
$data = Query::from('information_schema.tables', false)
->select('*')
->where('TABLE_SCHEMA', '=', Config::get('database.database'))
->andwhere('TABLE_NAME', '=', $this->_prifixTable)
->get(Query::GET_ARRAY);
//
return (Table::count($data) > 0) ? true : false;
}
|
php
|
{
"resource": ""
}
|
q241087
|
ORM.columns
|
train
|
protected function columns($data = null)
{
if (is_null($data)) {
$this->_columns = $this->extruct(
Query::from('INFORMATION_SCHEMA.COLUMNS', false)
->select('COLUMN_NAME')
->where('TABLE_SCHEMA', '=', Config::get('database.database'))
->andwhere('TABLE_NAME', '=', $this->_prifixTable)
->get(Query::GET_ARRAY)
);
//
return $this->_columns;
} else {
$this->_columns = $data['columns'];
}
}
|
php
|
{
"resource": ""
}
|
q241088
|
ORM.key
|
train
|
protected function key($data = null)
{
if (is_null($data)) {
$data = $this->getPK();
//
if (Table::count($data) > 1) {
throw new ManyPrimaryKeysException();
} elseif (Table::count($data) == 0) {
throw new PrimaryKeyNotFoundException(static::$table);
}
//
$this->_keyName = $data[0]['Column_name'];
$this->_key['name'] = $data[0]['Column_name'];
} else {
$this->_keyName = $data['key'];
$this->_key['name'] = $data['key'];
}
}
|
php
|
{
"resource": ""
}
|
q241089
|
ORM.struct
|
train
|
protected function struct($key, $fail)
{
$data = $this->dig($key);
//
if (Table::count($data) == 1) {
if ($this->_canKept && $this->keptAt($data)) {
$this->_kept = true;
}
if ($this->_canStashed && $this->stashedAt($data)) {
$this->_stashed = true;
}
//
$this->convert($data);
} elseif ($fail && Table::count($data) == 0) {
throw new ModelNotFoundException($key, $this->_model);
}
}
|
php
|
{
"resource": ""
}
|
q241090
|
ORM.fill
|
train
|
protected function fill($data)
{
if ($this->_canKept && $this->keptAt($data['values'])) {
$this->_kept = true;
}
if ($this->_canStashed && $this->stashedAt($data['values'])) {
$this->_stashed = true;
}
//
$this->convert($data['values']);
}
|
php
|
{
"resource": ""
}
|
q241091
|
ORM.dig
|
train
|
protected function dig($key)
{
return Query::from(static::$table)
->select('*')
->where($this->_keyName, '=', $key)
->get(Query::GET_ARRAY);
}
|
php
|
{
"resource": ""
}
|
q241092
|
ORM.convert
|
train
|
protected function convert($data)
{
foreach ($data[0] as $key => $value) {
if (!$this->_kept && !$this->_stashed) {
$this->$key = $value;
$this->setKey($key, $value);
} else {
if ($this->_kept) {
$this->_keptData[$key] = $value;
}
if ($this->_stashed) {
$this->_stashedData[$key] = $value;
}
}
$this->data[$key] = $value;
}
}
|
php
|
{
"resource": ""
}
|
q241093
|
ORM.save
|
train
|
public function save()
{
if ($this->_state == CRUD::CREATE_STAT) {
$this->add();
} elseif ($this->_state == CRUD::UPDATE_STAT) {
$this->edit();
}
}
|
php
|
{
"resource": ""
}
|
q241094
|
ORM.add
|
train
|
private function add()
{
$columns = [];
$values = [];
//
if ($this->_tracked) {
$this->created_at = Time::current();
}
//
foreach ($this->_columns as $value) {
if ($value != $this->_keyName && isset($this->$value) && !empty($this->$value)) {
$columns[] = $value;
$values[] = $this->$value;
}
}
//
return $this->insert($columns, $values);
}
|
php
|
{
"resource": ""
}
|
q241095
|
ORM.insert
|
train
|
private function insert($columns, $values)
{
return Query::table(static::$table)
->column($columns)
->value($values)
->insert();
}
|
php
|
{
"resource": ""
}
|
q241096
|
ORM.edit
|
train
|
private function edit()
{
$columns = [];
$values = [];
//
if ($this->_tracked) {
$this->edited_at = Time::current();
}
//
foreach ($this->_columns as $value) {
if ($value != $this->_keyName) {
$columns[] = $value;
$values[] = empty($this->$value) ? null : $this->$value;
}
}
//
return $this->update($columns, $values);
}
|
php
|
{
"resource": ""
}
|
q241097
|
ORM.update
|
train
|
private function update($columns, $values)
{
$query = Query::table(static::$table);
//
for ($i = 0; $i < Table::count($columns); $i++) {
$query = !empty($values[$i]) ? $query->set($columns[$i], $values[$i]) : $query->set($columns[$i], 'null', false);
}
//
$query->where($this->_keyName, '=', $this->_keyValue)
->update();
//
return $query;
}
|
php
|
{
"resource": ""
}
|
q241098
|
ORM.delete
|
train
|
public function delete()
{
if (!$this->_canKept) {
$this->forceDelete();
} else {
Query::table(static::$table)
->set('deleted_at', Time::current())
->where($this->_keyName, '=', $this->_keyValue)
->update();
}
}
|
php
|
{
"resource": ""
}
|
q241099
|
ORM.forceDelete
|
train
|
public function forceDelete()
{
$key = $this->_kept ? $this->_keptData[$this->_keyName] : $this->_keyValue;
//
Query::table(static::$table)
->where($this->_keyName, '=', $key)
->delete();
//
$this->reset();
}
|
php
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.