anchor
stringlengths
10
14.3k
positive
stringlengths
10
14.9k
Get the value of DOCUMENT_PRODUCT_CFOP
public function getDocumentProductCfop() { return (string) $this->document_product_cfop; }
Run the database seeds.
public function run() { $title = Str::random(10); DB::table('channels')->insert([ 'title' => $title, 'slug' => Str::of($title)->slug(), 'description' => Str::random(100) ]); }
Display the specified resource.
public function show($id) { // dd($this->model->find($id)->bds->id_loaibds); return view('admin.pages.hopdong.show', [ 'auth' => \Auth::user(), 'route' => $this->model->route, 'data' => $this->model->find($id), 'customers' ...
Test Case: Validate that the project has a description.
public function shouldHaveDescription() { // Arrange $attributes = factory(Project::class)->raw([ 'description' => '' ]); // Action $response = $this->post('/projects', $attributes); // Assert $response->assertSessionHasErrors('description'); ...
Should the system run the migration tool automatically
public function shouldRunMigration() { return $this->canRunMigration() && !Mage::getStoreConfigFlag(self::MIGRATION_COMPLETE) && !Mage::getStoreConfig('payment/gene_braintree/merchant_id') && !Mage::getStoreConfig('payment/gene_braintree/sandbox_merchant_id'); }
Run the database seeds.
public function run() { Reply::truncate(); $tickets = Ticket::all(); $faker = Faker::create(); Reply::create([ 'ticket_id' => $tickets[0]->id, 'user_id' => 1, 'name' => null, 'message' => $faker->paragraphs(3, true) ]); ...
Get all records from table ordered by field
public function queryAllOrderBy($orderColumn);
This returns the grandparent of the page specified by the GUID
public function getChildrenByParent($parent, $offline=false) { global $db; $query = "SELECT guid, title FROM pages WHERE parent = '$parent' "; if (!$offline) $query.="AND offline=0"; //print "$query<br>\n"; return $db->get_results($query); }
Called when request iterated.
public function run() { $this->header('Content-Type: text/html'); ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>G...
Run the database seeds.
public function run() { // DB::statement('SET FOREIGN_KEY_CHECKS=0;'); DB::table('image_products')->truncate(); $faker = Faker\Factory::create('vi_VN'); for ($i = 0; $i < 50; $i++) { DB::table('image_products')->insert([ 'products_id' => rand(1,10), ...
Get index analysis list.
public function getIndexAnalysis() { foreach ($this->items as $item) { if ('index' == $item->getName()) { return $item; } } }
This GLA computes the page ranks of a graph given the edge set as inputs. The algorithm runs with O(V) space and O(I E) time, where V is the total number of vertices; E, the total number of edges; and I, the number of iterations. The input should be two integers specifying source and target vertices. The output is vert...
function Page_Rank($t_args, $inputs, $outputs) { // Class name is randomly generated. $className = generate_name('PageRank'); // Initializiation of argument names. $inputs_ = array_combine(['s', 't'], $inputs); $vertex = $inputs_['s']; // Processing of template arguments. $adj = $t_args['a...
Counts scalar values recursively in array.
private function countRecursiveScalars($array) { $count = 0; if (!is_array($array)) { return 1; } foreach ($array as $element) { if (is_array($element)) { $count += $this->countRecursiveScalars($element); } else { ...
Get a string including indispensable info: Use this function to add space into position str:
function addSpace($str){ $s = $str[0]; for($i=1;$i<strlen($str);$i++){ if(ctype_upper($str[$i]) == true){ $s.= ' '.$str[$i]; } else{ $s.= $str[$i]; } } return $s; }
Test a successful command run.
public function testRunsOk() { $application = new Application(); $application->add($this->command); $command = $application->find('dequeue'); $command_tester = new CommandTester($command); $this->assertEquals(0, $this->dispatcher->getQueue()->count()); $this->dispat...
Initializes context. Every scenario gets its own context instance. You can also pass arbitrary arguments to the context constructor through behat.yml.
public function __construct(UserRepository $userRepository) { $user = $userRepository->findOneBy(['name' => 'behatTestuser']); $this->user = $user; }
Logs with an arbitrary level.
public function log($level, $message, array $context = array()) { // Make sure the log level is valid if (!array_key_exists($level, $this->priorityMap)) { throw new \InvalidArgumentException('An invalid log level has been given.'); } // Map the level to Joomla's priority $priority = $this->priorityMap[...
Test that we can read and parse the email
public function testMailParse() { // Parse a simple email $email_message = new EmailParse(); $email_message->read_email(true, $this->_email); // Basics $this->assertEquals('"ElkArte Community" <elkarteforum@gmail.com>', $email_message->headers['reply-to']); $this->assertEquals('[ElkArte Community] Test Me...
The last name of the user.
public function setLastName(?string $lastName): self { $this->initialized['lastName'] = true; $this->lastName = $lastName; return $this; }
////////////////////////////////////////////////////////////////////////// GET DETAILS ON A PARTICULAR FIELD COLUMN IN THIS RESULT //////////////////////////////////////////////////////////////////////////
public function getField($column) { if (!$column) return ['QUERY']; return false; }
/ accessor method for profile creation date return string value of creation date
public function getDateCreated() { return($this->dateCreated); }
Remove the specified resource from storage.
public function destroy(Organization $organization) { // }
Show the form for creating a new resource.
public function create() { return view('trainer.create'); }
FUNCIONES DEL NUEVO FORMULARIOS //
public function validateInformation(Request $request){ $data_input = $request->get('drivingLicence'); // echo '<pre> licencia'; // print_r($data_input); // die; $message_error_expi_date = 'La fecha de vencimiento no puede ser menor a la de expedición'; $validator...
TO DO:delete all files
public function actionRestartqueue() { if (!empty($_POST['id'])) { CConvertQueue::model()->restartUserQueue($this->user_id, $_POST['id']); } }
defineHandlers Un(Install) Install module
function install() { /* * do some stuff at install db table creation/modification, email template creation etc. * * */ return parent::install(); }
Lists all Erform models.
public function actionIndex() { $searchModel = new ErformSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); $erform = Erform::find()->where(['etype' => 1])->all(); $erform2 = Erform::find()->where(['etype' => 2])->all(); $erform3 = Erform::find()...
Retrieve a single order from the database.
public function get_order_data_from_table( $order ) { global $wpdb; return $wpdb->get_row( $wpdb->prepare( "SELECT * FROM {$wpdb->prefix}woocommerce_orders WHERE order_id = %d;", $order->get_id() ) ); }
Check for SHA 256 string validity
public static function isSha256($sha1) { return preg_match('/^[a-fA-F0-9]{64}$/', $sha1); }
Get historical currency exchange rates.
protected function query($date, $base, array $targets) { $url = self::URL . $date; $query = []; if ($base != 'EUR') { $query['base'] = $base; } // add symbols to query string if (!empty($targets)) { $query['symbols'] = implode(',', $...
Create User Profile for newly registered User with given columns With User Model.
public function create(array $columns, $type, UserModelInterface $user);
Creates admin user id with status draft and redirects to update if success
public function create() { $data = ['user_role_id' => USER_ROLE_ADMINISTRATOR]; if ($id = $this->users_model->save($data)) { //if user has not access to update $this->session->set_userdata(['new_item' => ['module' => 'administrators', 'id' => $id]]); redirect("/admin/users/update/$id"); } else { ...
Display a listing of the products.
public function index() { $products = $this->products->paginate(10); return view('products.index', compact('products')); }
return a sanitize_callback for serialized data
public function sanitizeCallback($type, $k) { switch($type) { case 'boolean': return function($v) use ($k) { if (!is_array($v)) return (bool) $v; if (isset($v[$k])) $v[$k] = (bool) $v[$k]; return $v; ...
Set success message and redirect to successUrl page.
public function redirect(Event $event) { /** @var PluginController $controller */ $controller = $event->getSubject(); $controller->Flash->success(__d('users', 'Restore password confirmation was sent.')); return $controller->redirect($this->getConfig('successUrl')); }
check this option with user access
private function check_access_to_option(array $_option, int $_user_id) { $user_access_code = $this->check_user_access((int) $_user_id); if (!$user_access_code) { return false; } return true; }
Return customers who made changes
private function getCourseEditors() { return $this->entityManager->createQueryBuilder() ->select('customer') ->from(Customer::class, 'customer') ->innerJoin(ActionLog::class, 'log', Expr\Join::WITH, 'customer.id = log.user') ->where('customer.id in (:ids)') ...
Creates a client token signature When client from browser wants to connect to Centrifuge he must send his user ID and ID of project. To validate that data we use HMAC to build token.
public function get_client_token($user, $timestamp, $custom_data = false ) { if($custom_data == true) { $token = hash_hmac($this->settings['encryption'], $this->settings['project_id'] . $user . $timestamp . $custom_data, $this->settings['secret_key'], false ); } else { $token = hash_hmac($this->setting...
Return an instance of DOMDocument constructed with the property of results
protected function getDom() { if (! isset($this->dom)) { $dom = new DOMDocument(); if (is_null($this->getResults())) { throw new \RuntimeException('There doesnt appear to be any results to load'); } // suppress warning but throw Exception ...
Display a listing of the resource.
public function index() { return view('codifications.index'); }
Search in names of entities
public function search($query) { $queryBuilder = $this->db->createQueryBuilder(); $queryBuilder ->select('c.*') ->from($this->table, 'c'); $queryBuilder->where("c.`name` LIKE :query"); $queryBuilder->setParameter(':query', "%$query%"); $queryBuilder->orde...
Determine if the user is authorized to make this request.
public function authorize(): bool { return auth('api')->check(); }
A user can have many posts.
public function posts() { return $this->hasMany(Post::class); }
Transform each stream element int a tuple (array of 2 elements) where the first element is the result of the callback applied to the element value and the second is the element value.
public function keyBy(callable $callback): Stream { $generator = function (Stream $stream) use ($callback) { foreach ($stream as $value) { yield [$callback($value), $value]; } }; return new Stream($generator($this)); }
Handler to actual send replyrelated activity payload.
private function notify_forum_reply_payload( $activity, $reply_id ) { if ( defined( 'WP_IMPORTING' ) && WP_IMPORTING ) { return; } if ( ! bbp_is_site_public() ) { return; } if ( ! in_array( $activity, array( 'create-reply', 'remove-reply' ), true ) ) { return; } if ( 'create-reply' === $activi...
Adds additional entries to the specifed option field.
public function add($field, array $dependencies) { if (! file_exists($this->file)) { throw new RuntimeException("Could not add dependencies, `package.json` file do not exists."); } $packages = json_decode(file_get_contents($this->file), true); $packages[$field] = $depen...
Execute a select query and return the first entity
public function selectOne(Query\Select $query): ?Entity { return $this->db->selectOne($this->klass, $query); }
Parses pattern based on ICU grammar.
private static function parseToken(array $token, array $values, $locale) { if (!isset($values[$param = trim($token[0])])) { return '{'.$param.'}'; } $arg = $values[$param]; $type = isset($token[1]) ? trim($token[1]) : 'none'; switch ($type) { case 'da...
Return the HTML for the Categories section.
public function get_sidebar_categories(){ $html = '<tr class="wm-widget-sub-title"><td>{{categories-title}}:</td></tr><tr class="wm-widget-info"><td>'; $categories = get_the_category(); $output = ''; foreach( $categories as $category ){ $id = get_cat_ID(...
Filter the element input.
public function filterElementInputMmd($components, $args) { $db = get_db(); $element = $args['element']; $record = $args['record']; $elementName = $element->name; $elementId = $element->id; $recordId = $record->id; $index = $args['index']; $mmdManua...
Deletes a particular model. If deletion is successful, the browser will be redirected to the 'admin' page.
public function actionDelete($id) { $persona = Persona::model()->with(array('titularidad', 'cotitularidad'))->findByPk($id); if (is_null($persona->titularidad) && is_null($persona->cotitularidad)) { $persona->delete(); } else { http_response_code(400); header('Content-type: ...
parrafo a lo que venga
function parrafo($text){ return "<p>$text</p>"; }
Function to convert base64 image source to actual image (saved in folder "upload/image/") from textarea
public function convert_inline($str = '', $new_name = '', $mark = 'inline-') { $img = array(); $start = '<img'; $end = '>'; $pattern = sprintf('/%s(.+?)%s/ims', preg_quote($start, '/'), preg_quote($end, '/')); $search = true; $i = 1; while($search) { if (preg_match($pattern, $str, $matches)...
A list of inputs that should be accepted. Currently only `dtmf` is supported. All digits captured during a pay session are redacted from the logs.
public function setInput(string $input): self { $this->options['input'] = $input; return $this; }
Store a newly created ipcontaip_10 in storage.
public function store(Createipcontaip_10Request $request) { $input = $request->all(); $ipcontaip10 = $this->ipcontaip10Repository->create($input); Flash::success(__('messages.saved', ['model' => __('models/ipcontaip10s.singular')])); return redirect(route('ipcontaip10s.index')); ...
Return the type of the response as a string.
public function getType(): string;
get SessionID Returns:A unique identifier for the session in the service that raised the event.
public function getSessionID() { return $this->getKey('SessionID'); }
Gets the Relation if the embed is a valid relation to the main model. Also handles nested relationships
protected function getValidRelation($relation_models) { /** * @var Relation $actual_relation */ $manager = $this->main_model_obj->getModelsManager(); $_model = $this->main_model; $actual_relation = null; foreach ($relation_models as $model){ $re...
Update the specified resource in storage.
public function update(Request $request, $id) { $this->validate($request, [ 'name'=>'required|max:120', 'short_name'=>'required|max:10|min:3', ]); //\Auth::user()->activity; $company = Company::findOrFail($id); $company->name = $request['name']; ...
check if multiple variables exists
public static function mx() { for ($i = 0; $i < func_num_args(); $i++) { $arg = func_get_arg($i); if (self::nx(@$arg)) { return false; } } return true; }
Gets the specified package configuration
public function getConfig($package);
Store a newly created resource in storage.
public function store(Request $request) { $this->validate($request, [ 'short_description' => 'required', 'video' => 'required', ]); $lesson = new Lesson(); $lesson->title = $request->get('title'); $lesson->course_id = $request->get('id'); $lesson->s...
/ cleanAll() will clean up your session dir removing all 'sid_' files with a modified date older than the number of minutes passed in. This method is here as a convenience. You probably want to create a cron job that cleans this up on a daily basis.
function cleanAll($minutes = CLEAN_ALL_MINUTES) { $sessions = @scandir(SESSIONS_DIR); $sess_dir = rtrim(SESSIONS_DIR, '/').'/'; for($n=count($sessions),$i=0;$i<$n;$i++) { if($sessions[$i]!='.' && $sessions[$i]!='..') { $last_modified = @filemtime($sess_dir . $sessions...
Operation listsServicesServiceIdPut Update an existing Service.
public function listsServicesPut($service_id) { $input = Request::all(); $service = Services::findOrFail($service_id); $service->update(['name' => $input['name']]); if($service->save()){ return response()->json(['msg' => 'Updated service']); }else{ ...
Get the value of localisation
public function getLocalisation($localisation=null) { if ($localisation != null && is_array($this->entity) && count($this->entity)!=0) { $table_name = strtolower(get_class($this)); $query = "SELECT * FROM $table_name WHE...
curl calls the pageview pixel
protected function pixelPageView() { $url = $GLOBALS['ccttsUrl'] .'cctts_inc/ajax/ccReg.php'; $paramsArr = array('method=pixelPageView'); foreach ($this->ccttsParams as $key => $val) $paramsArr[] = "$key=$val"; $paramsStr = implode('&', $paramsArr); $result = $this->curlIt($url, $paramsStr); }
/ get_all_purchase_requests(): returns a 2D array of all purchase requests
function get_all_purchase_requests($db) { $sql = "SELECT * FROM purchase_requests"; $st= $db->prepare($sql); $st->execute(); $us = $st->fetchAll(); return $us; }
Form constructor for the Display Text configuration page.
function room_reservations_admin_settings_page($form, &$form_state) { $default_calendar_text = _room_reservations_get_variable('calendar_text'); $default_reserve_room_instructions_text = _room_reservations_get_variable('reserve_instructions'); $default_reserve_form_instructions_text = _room_reservations_g...
TODO:: make sure this is a AJAX Request
public function checkEmailExistsAjaxAction() { if(isset($_POST['Email']) && !empty($_POST['Email'])) { header('Content-type: text/plain'); if(UserModel::emailExists($this->filterString($_POST['Email'])) !== false) { echo 1; } else { echo 2;...
Get backup info by name, useful for backups with custom name.
public function get_backup_by_name( $name = '' ) { if ( ! empty( $name ) ) { return self::$dbo->querySingle( "SELECT * FROM snapshots WHERE name LIKE '$name'", true ); } return false; }
///////////////////////////// Whostage functions // /////////////////////////// Operation listsWhostageGet Fetch Drug Allergies (for select options).
public function listsWhostageget() { $response = Whostage::all(); return response()->json($response,200); }
Specifies the access control rules. This method is used by the 'accessControl' filter.
public function accessRules() { return array( array('allow', // allow all users to perform 'index' and 'view' actions 'users'=>array('admin'), ), array('deny', // deny all users 'users'=>array('*'), ), ); }
returns developer if in db, or adds and returns it if it isn't
function getOrAddDeveloper($gbDeveloper) { // get developer from db $developer = $this->getDeveloperByGBID($gbDeveloper->id); // if developer isn't in db if($developer == null) { // developer was not found, get from Giant Bomb $this->load->model('Gian...
Return the form metadata.
public static function get_big_sea_survey_definition() { return array( 'title' => 'Big Sea Survey', 'category' => 'Forms for specific surveying methods', 'description' => 'A dynamic form which allows a front page to define the number of transects to record across '. 'a set of zones and m...
check for session and cookie presence
public function view_notification() { $this->admin_header(); //check and confirm if the total url segment is 3 $url_segments = $this->uri->total_segments(); if ($url_segments == 3) { //retrieved the unreviewed property id $notification_id = $this->uri->segment(3); //retrieve from the databas...
Tests Transform_Unserialize_Serial>getReverse() with a chain
public function testGetReverse_Chain() { $mock = $this->getMock('Q\Transform', array('getReverse', 'process')); $mock->expects($this->once())->method('getReverse')->with($this->isInstanceOf('Q\Transform_Serialize_Serial'))->will($this->returnValue('reverse of mock transformer')); $...
Moves an existing list item to a new position. The position is in front of the item with the ID given in $ref or at the end of the list if $ref is null. // item ID list in database: 1, 2, 3, 4 $listManager>moveItem( 2, 4 ); // result: 1, 3, 2, 4 // item ID list in database: 1, 2, 3, 4 $listManager>moveItem( 2, null ); ...
public function moveItem( $id, $ref = null );
Finds the Follow model based on its primary key value. If the model is not found, a 404 HTTP exception will be thrown.
protected function findModel($id) { if (($model = Follow::findOne ( $id )) !== null) { return $model; } else { throw new NotFoundHttpException ( 'The requested page does not exist.' ); } }
Generate meta query for wc_get_orders.
private function get_orders_generate_customer_meta_query( $values, $relation = 'or' ) { $meta_query = array( 'relation' => strtoupper( $relation ), 'customer_emails' => array( 'key' => '_billing_email', 'value' => array(), 'compare' => 'IN', ), 'customer_ids' => array( 'key' => '...
Load JSON from master file
public function testAggregation() { $statistics = json_decode(file_get_contents(base_path('tests/database/yrkesstatistik_aggregated.json')), true); // Compare with master foreach (YrkesstatistikAggregated::all() as $count => $agg) { //dd($statistics[$count]['statistics']['entrie...
Indicates the type of answer data which Moodle expects to recieve; the scripted quesiton type always recieves the same, single answer.
public function get_expected_data() { return array('answer' => PARAM_RAW_TRIMMED); }
Manually set the result value
protected function result($value) { $this->setValue($value); return $this; }
Returns the question titles of all questions of a question block
function &getQuestionblockQuestions($questionblock_id) { global $ilDB; $titles = array(); $result = $ilDB->queryF("SELECT svy_question.title, svy_qblk_qst.question_fi, svy_qblk_qst.survey_fi FROM ". "svy_qblk, svy_qblk_qst, svy_question WHERE svy_qblk.questionblock_id = svy_qblk_qst.questionblock_fi AND " . ...
array( 'flag' => int 'flagIframe' => int )
protected function _setSearch($arr) { global $varsRequest; global $varsPluginAccountingPreference; if (FLAG_CHECK_UPDATE) { $this->checkStampReload(array( 'stampTarget' => $varsPluginAccountingPreference['jsonStampUpdate']['logFile'], 'flagSearch' => 1, )); } $vars = $this->getVars(array( ...
Alter hrefs in page if they point to nonhtmlpage files. Relative src will be made either absolute or root relative depending on the value of $base_for_relative. If root relative is used, then attempts will be made to lookup the redirect and detect the final destination.
public static function rewriteAnchorHrefsToBinaryFiles($query_path, array $url_base_alters, $file_path, $base_for_relative, $destination_base_url) { $attributes = [ 'href' => 'a[href], area[href]', 'longdesc' => 'img[longdesc]', ]; $filelink_count = 0; $report = []; foreach ($attributes ...
Add a boolean param
public function addBoolean(string $name, bool $default = false) { $this->add('boolean', $name, func_get_args()); }
Display the specified resource.
public function show(Team $team) { // generate resource $resource = new Item($team, new TeamTransformer(), 'teams'); return $this->jsonResponse($resource, 200); }
date calculation start here
function week_number($date) { return date("W", strtotime("$date + 1 day")); }
Sorts output rows according to ORDER BY fields
public function orderBy(array $fields, $order = null);
Enable / selected ad
public function enable() { $this->_access("put"); $status = $this->Assets_model->enable($this->input->post()); $this->_returnAjax($status); }
Boot real compiled field. Append children to parentroot.
public function create() { // Load only root elements. $this->loadRoots($this->elements, $this->roots); // Make sure that first element isn't child. If child then throw a exception about that. if ($this->elements[0]->isChild()) TypeRegression::cantBe('child', 'Fir...
Processes submits of the metadata entry form.
public function sendMetadataForm($data, $form) { // Specify array for the params to send to the API. Can't be associative and keyed by the xmlname // as the Dublin core specification allows for multiple of the same field. $apiParams = array(); // Loop through the defined fields grab...
Sets curl property and its settings.
private function setCurl($is_https = false) { // Init $this->curl = curl_init(); // Sets basic parameters curl_setopt($this->curl, CURLOPT_RETURNTRANSFER, 1); curl_setopt($this->curl, CURLOPT_TIMEOUT, isset($this->request->settings['timeout']) ? $this->request->settings['time...
Lists all Examination models.
public function actionIndex() { $userId = Yii::$app->user->id; $searchModel = new ExaminationSearch(); $dataProvider = $searchModel->search(Yii::$app->request->queryParams); $dataProvider->query->AndWhere(['user_id' => $userId]); $dataProvider->query->orderBy('create_a...
Return an array containing the status of any modified files in the repository.
public static function getStatus($path) { if (!file_exists($path)) { throw new Exception( "Unable to get git status of $path. Path does not exist."); } if (!is_dir($path)) { throw new Exception( "Unable to get git status of $path. Path is not a directory."); } if (!self::isRepo($path)) { th...
Get formatters from config.
protected function getFormettersFromConfig($items): array { $formatters = []; if (!is_array($items)) { $items = [$items]; } foreach ($items as $item) { $formatter = $this->getFormatter($item); if ($formatter) { $formatters[$item] ...
Logs a message with the Warning Log Level
public static function critical($msg, $method=null) { try { $method = is_null($method) ? self::_get_caller() : $method; return static::write(\Additional_Log::L_CRITICAL, $msg, $method); } catch (Exception $e) { // ignore } }
fetch then return documents
public function get() { $this->composeQuery(); $result = $this->connection->client()->search($this->queryBody); $this->scrollId = array_get($result,'_scroll_id'); return array_get($result, 'hits.hits'); }
Method to get the response (shorthand alias)
public function response() { return $this->response; }
Remove the specified resource from storage.
public function destroy($id) { $renter = Renter::findOrFail($id); $renter->prev = 'yes'; $renter->prop_id = null; $renter->save(); $this->addLog(\Auth::user()->name.' deleted a renter.'); flash('Successfully deleted')->success(); return redirect()->back(); ...