Programs & Examples On #Codeigniter

CodeIgniter is an open-source PHP web development framework created by EllisLab Inc and it has been adopted by British Columbia Institute of Technology. The framework implements a modified version of the Model-View-Controller design pattern. Use this tag for questions about CodeIgniter classes, methods, functions, syntax and use.

Error : ORA-01704: string literal too long

The split work until 4000 chars depending on the characters that you are inserting. If you are inserting special characters it can fail. The only secure way is to declare a variable.

How to execute my SQL query in CodeIgniter

 return $this->db->select('(CASE 
            enter code hereWHEN orderdetails.ProductID = 0   THEN dealmaster.deal_name
            WHEN orderdetails.DealID = 0 THEN products.name
            END) as product_name')

CodeIgniter activerecord, retrieve last insert id?

After your insert query, use this command $this->db->insert_id(); to return the last inserted id.

For example:

$this->db->insert('Your_tablename', $your_data);

$last_id =  $this->db->insert_id();

echo $last_id // assume that the last id from the table is 1, after the insert query this value will be 2.

"SELECT ... IN (SELECT ...)" query in CodeIgniter

Note that these solutions use the Code Igniter Active Records Class

This method uses sub queries like you wish but you should sanitize $countryId yourself!

$this->db->select('username')
         ->from('user')
         ->where('`locationId` in', '(select `locationId` from `locations` where `countryId` = '.$countryId.')', false)
         ->get();

Or this method would do it using joins and will sanitize the data for you (recommended)!

$this->db->select('username')
         ->from('users')
         ->join('locations', 'users.locationid = locations.locationid', 'inner')
         ->where('countryid', $countryId)
         ->get();

CodeIgniter: "Unable to load the requested class"

I had a similar issue when deploying from OSx on my local to my Linux live site.

It ran fine on OSx, but on Linux I was getting:

An Error Was Encountered

Unable to load the requested class: Ckeditor

The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".

I also changed my load call to match the capitalization:

$this->load->library('CKEditor');

CodeIgniter 500 Internal Server Error

The problem with 500 errors (with CodeIgniter), with different apache settings, it displays 500 error when there's an error with PHP configuration.

Here's how it can trigger 500 error with CodeIgniter:

  1. Error in script (PHP misconfigurations, missing packages, etc...)
  2. PHP "Fatal Errors"

Please check your apache error logs, there should be some interesting information in there.

Header and footer in CodeIgniter

This question has been answered properly, but I would like to add my approach, it's not that different than what the others have mentioned.

I use different layouts pages to call different headers/footers, some call this layout, some call it template etc.

  1. Edit core/Loader.php and add your own function to load your layout, I called the function e.g.layout.

  2. Create your own template page and make it call header/footer for you, I called it default.php and put in a new directory e.g. view/layout/default.php

  3. Call your own view page from your controller as you would normally. But instead of calling $this-load->view use $this->load->layout, layout function will call the default.php and default.php will call your header and footer.

1) In core/Loader.php under view() function I duplicated it and added mine

   public function layout($view, $vars = array(), $return = FALSE)
   {
       $vars["display_page"] = $view;//will be called from the layout page
       $layout               = isset($vars["layout"]) ? $vars["layout"] : "default";
       return $this->_ci_load(array('_ci_view' => "layouts/$layout", '_ci_vars' =>  $this->_ci_object_to_array($vars), '_ci_return' => $return));
   }

2) Create layout folder and put default.php in it in view/layout/default.php

   $this->load->view('parts/header');//or wherever your header is
   $this->load->view($display_page);
   $this->load->view('parts/footer');or wherever your footer is

3) From your controller, call your layout

 $this->load->layout('projects');// will use 'view/layout/default.php' layout which in return will call header and footer as well. 

To use another layout, include the new layout name in your $data array

 $data["layout"] = "full_width";
 $this->load->layout('projects', $data);// will use full_width.php layout

and of course you must have your new layout in the layout directory as in:

view/layout/full_width.php 

CodeIgniter - accessing $config variable in view

$this->config->item('config_var') did not work for my case.

I could only use the config_item('config_var'); to echo variables in the view

Pass array to where in Codeigniter Active Record

Use where_in()

$ids = array('20', '15', '22', '46', '86');
$this->db->where_in('id', $ids );

insert data into database with codeigniter

function order_summary_insert()
$OrderLines=$this->input->post('orderlines');
$CustomerName=$this->input->post('customer');
$data = array(
'OrderLines'=>$OrderLines,
'CustomerName'=>$CustomerName
);

$this->db->insert('Customer_Orders',$data);
}

codeigniter model error: Undefined property

function user() { 

       parent::Model(); 

} 

=> class name is User, construct name is User.

function User() { 

       parent::Model(); 

} 

difference between $query>num_rows() and $this->db->count_all_results() in CodeIgniter & which one is recommended

$sql = "select count(*) as row from login WHERE firstname = '" . $username . "' AND password = '" . $password . "'";
    $query = $this->db->query($sql);
    print_r($query);exit;
    if ($query->num_rows() == 1) {
    return true;
    } else {
    return false;
    }

CodeIgniter - Correct way to link to another page in a view

The best way is to use the following code:

<a href="<?php echo base_url() ?>directory_name/filename.php">Link</a>

GET parameters in the URL with CodeIgniter

You simply need to enable it in the config.php and you can use $this->input->get('param_name'); to get parameters.

Codeigniter - no input file specified

RewriteEngine, DirectoryIndex in .htaccess file of CodeIgniter apps

I just changed the .htaccess file contents and as shown in the following links answer. And tried refreshing the page (which didn't work, and couldn't find the request to my controller) it worked.

Then just because of my doubt I undone the changes I did to my .htaccess inside my public_html folder back to original .htaccess content. So it's now as follows (which is originally it was):

DirectoryIndex index.php
RewriteEngine on
RewriteCond $1 !^(index\.php|images|css|js|robots\.txt|favicon\.ico)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ ./index.php?/$1 [L,QSA]

And now also it works.

Hint: Seems like before the Rewrite Rules haven't been clearly setup within the Server context.

My file structure is as follows:

/
|- gheapp
|    |- application
|    L- system
|
|- public_html
|    |- .htaccess
|    L- index.php

And in the index.php I have set up the following paths to the system and the application:

$system_path = '../gheapp/system';
$application_folder = '../gheapp/application';

Note: by doing so, our application source code becomes hidden to the public at first.

Please, if you guys find anything wrong with my answer, comment and re-correct me!
Hope beginners would find this answer helpful.

Thanks!

Only variable references should be returned by reference - Codeigniter

Edit filename: core/Common.php, line number: 257

Before

return $_config[0] =& $config; 

After

$_config[0] =& $config;
return $_config[0]; 

Update

Added by NikiC

In PHP assignment expressions always return the assigned value. So $_config[0] =& $config returns $config - but not the variable itself, but a copy of its value. And returning a reference to a temporary value wouldn't be particularly useful (changing it wouldn't do anything).

Update

This fix has been merged into CI 2.2.1 (https://github.com/bcit-ci/CodeIgniter/commit/69b02d0f0bc46e914bed1604cfbd9bf74286b2e3). It's better to upgrade rather than modifying core framework files.

how to get last insert id after insert query in codeigniter active record

From the documentation:

$this->db->insert_id()

The insert ID number when performing database inserts.

Therefore, you could use something like this:

$lastid = $this->db->insert_id();

DataTables: Cannot read property 'length' of undefined

It can happen when your view property name and name inside column section of data table is not matching . Make sure that property name and column data name are matching

Codeigniter - multiple database connections

It works fine for me...

This is default database :

$db['default'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'mydatabase',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => TRUE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

Add another database at the bottom of database.php file

$db['second'] = array(
    'dsn'   => '',
    'hostname' => 'localhost',
    'username' => 'root',
    'password' => '',
    'database' => 'mysecond',
    'dbdriver' => 'mysqli',
    'dbprefix' => '',
    'pconnect' => TRUE,
    'db_debug' => (ENVIRONMENT !== 'production'),
    'cache_on' => FALSE,
    'cachedir' => '',
    'char_set' => 'utf8',
    'dbcollat' => 'utf8_general_ci',
    'swap_pre' => '',
    'encrypt' => FALSE,
    'compress' => FALSE,
    'stricton' => FALSE,
    'failover' => array(),
    'save_queries' => TRUE
);

In autoload.php config file

$autoload['libraries'] = array('database', 'email', 'session');

The default database is worked fine by autoload the database library but second database load and connect by using constructor in model and controller...

<?php
    class Seconddb_model extends CI_Model {
        function __construct(){
            parent::__construct();
            //load our second db and put in $db2
            $this->db2 = $this->load->database('second', TRUE);
        }

        public function getsecondUsers(){
            $query = $this->db2->get('members');
            return $query->result(); 
        }

    }
?>

CodeIgniter: How To Do a Select (Distinct Fieldname) MySQL Query

You can also run ->select('DISTINCT `field`', FALSE) and the second parameter tells CI not to escape the first argument.

With the second parameter as false, the output would be SELECT DISTINCT `field` instead of without the second parameter, SELECT `DISTINCT` `field`

COUNT / GROUP BY with active record?

I think you should count the results with FOUND_ROWS() and SQL_CALC_FOUND_ROWS. You'll need two queries: select, group_by, etc. You'll add a plus select: SQL_CALC_FOUND_ROWS user_id. After this query run a query: SELECT FOUND_ROWS(). This will return the desired number.

Send email by using codeigniter library via localhost

I had the same problem and I solved by using the postcast server. You can install it locally and use it.

Sending email with gmail smtp with codeigniter email library

send html email via codeiginater

    $this->load->library('email');
    $this->load->library('parser');



    $this->email->clear();
    $config['mailtype'] = "html";
    $this->email->initialize($config);
    $this->email->set_newline("\r\n");
    $this->email->from('[email protected]', 'Website');
    $list = array('[email protected]', '[email protected]');
    $this->email->to($list);
    $data = array();
    $htmlMessage = $this->parser->parse('messages/email', $data, true);
    $this->email->subject('This is an email test');
    $this->email->message($htmlMessage);



    if ($this->email->send()) {
        echo 'Your email was sent, thanks chamil.';
    } else {
        show_error($this->email->print_debugger());
    }

Updating records codeigniter

In your_controller write this...

public function update_title() 
{   
    $data = array
      (
        'table_id' => $this->input->post('table_id'),
        'table_title' => $this->input->post('table_title')
      );

    $this->load->model('your_model'); // First load the model
    if($this->your_model->update_title($data)) // call the method from the controller
    {
        // update successful...
    }
    else
    {
        // update not successful...
    }

}

While in your_model...

public function update_title($data)
{
   $this->db->set('table_title',$data['title'])
         ->where('table_id',$data['table_id'])
        ->update('your_table');
}

This will works fine...

How to upload image in CodeIgniter?

Simple Image upload in codeigniter

Find below code for easy image upload

public function doupload()
     {
        $upload_path="https://localhost/project/profile"  
        $uid='10'; //creare seperate folder for each user 
        $upPath=upload_path."/".$uid;
        if(!file_exists($upPath)) 
        {
                   mkdir($upPath, 0777, true);
        }
        $config = array(
        'upload_path' => $upPath,
        'allowed_types' => "gif|jpg|png|jpeg",
        'overwrite' => TRUE,
        'max_size' => "2048000", 
        'max_height' => "768",
        'max_width' => "1024"
        );
        $this->load->library('upload', $config);
        if(!$this->upload->do_upload('userpic'))
        { 
            $data['imageError'] =  $this->upload->display_errors();

        }
        else
        {
            $imageDetailArray = $this->upload->data();
            $image =  $imageDetailArray['file_name'];
        }

     }

Hope this helps you to upload image

CodeIgniter: How to use WHERE clause and OR clause

Active record method or_where is to be used:

$this->db->select("*")
->from("table_name")
->where("first", $first)
->or_where("second", $second);

How to print SQL statement in codeigniter model

I'm using xdebug for watch this values in VSCode with the respective extension and CI v2.x. I add the expresion $this->db->last_query() in the watch section, and I add xdebugSettings node like these lines for get non truncate value in the launch.json.

{
  "name": "Launch currently open script",
  "type": "php",
  "request": "launch",
  "program": "${file}",
  "cwd": "${fileDirname}",
  "port": 9000,
  "xdebugSettings": {
    "max_data": -1,
    "max_children": -1
  }
},

And run my debuger with the breakpoint and finally just select my expresion and do click right > copy value.

Sending XML data using HTTP POST with PHP

you can use cURL library for posting data: http://www.php.net/curl

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);

where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

(CI 3) For me, what worked was changing:

'hostname' => 'localhost' to 'hostname' => '127.0.0.1'

Codeigniter's `where` and `or_where`

You can change your code to this:

$where_au = "(library.available_until >= '{date('Y-m-d H:i:s)}' OR library.available_until = '00-00-00 00:00:00')";
$this->db
    ->select('*')
    ->from('library')
    ->where('library.rating >=', $form['slider'])
    ->where('library.votes >=', '1000')
    ->where('library.language !=', 'German')
    ->where($where_au)
    ->where('library.release_year >=', $year_start)
    ->where('library.release_year <=', $year_end)
    ->join('rating_repo', 'library.id = rating_repo.id');

Tip: to watch the generated query you can use

echo $this->db->last_query(); die();

How to JOIN three tables in Codeigniter

try this

In your model

If u want get all album data use

  function get_all_album_data() {

    $this->db->select ( '*' ); 
    $this->db->from ( 'Album' );
    $this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
    $this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
    $query = $this->db->get ();
    return $query->result ();
 }

if u want to get specific album data use

  function get_album_data($album_id) {

    $this->db->select ( '*' ); 
    $this->db->from ( 'Album' );
    $this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
    $this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
    $this->db->where ( 'Album.album_id', $album_id);
    $query = $this->db->get ();
    return $query->result ();
 }

CodeIgniter: How to get Controller, Action, URL information

Last segment of URL will always be the action. Please get like this:

$this->uri->segment('last_segment');

How to remove "index.php" in codeigniter's path

Ensure you have enabled mod_rewrite (I hadn't).
To enable:

sudo a2enmod rewrite  

Also, replace AllowOverride None by AllowOverride All

sudo gedit /etc/apache2/sites-available/default  

Finaly...

sudo /etc/init.d/apache2 restart  

My .htaccess is

RewriteEngine on  
RewriteCond $1 !^(index\.php|[assets/css/js/img]|robots\.txt)  
RewriteRule ^(.*)$ index.php/$1 [L]  

how to get the base url in javascript

One way is to use a script tag to import the variables you want to your views:

<script type="text/javascript">
window.base_url = <?php echo json_encode(base_url()); ?>;
</script>

Here, I wrapped the base_url with json_encode so that it'll automatically escape any characters to valid Javascript. I put base_url to the global Window so you can use it anywhere just by calling base_url, but make sure to put the script tag above any Javascript that calls it. With your given example:

...
$('#style_color').attr("href", base_url + "assets/css/themes/" + color_ + ".css");

SELECT with LIMIT in Codeigniter

I don't know what version of CI you were using back in 2013, but I am using CI3 and I just tested with two null parameters passed to limit() and there was no LIMIT or OFFSET in the rendered query (I checked by using get_compiled_select()).

This means that -- assuming your have correctly posted your coding attempt -- you don't need to change anything (or at least the old issue is no longer a CI issue).

If this was my project, this is how I would write the method to return an indexed array of objects or an empty array if there are no qualifying rows in the result set.

function nationList($limit = null, $start = null) {
    // assuming the language value is sanitized/validated/whitelisted
    return $this->db
        ->select('nation.id, nation.name_' . $this->session->userdata('language') . ' AS name')
        ->from('nation')
        ->order_by("name")
        ->limit($limit, $start)
        ->get()
        ->result();
}

These refinements remove unnecessary syntax, conditions, and the redundant loop.

For reference, here is the CI core code:

/**
 * LIMIT
 *
 * @param   int $value  LIMIT value
 * @param   int $offset OFFSET value
 * @return  CI_DB_query_builder
 */
public function limit($value, $offset = 0)
{
    is_null($value) OR $this->qb_limit = (int) $value;
    empty($offset) OR $this->qb_offset = (int) $offset;

    return $this;
}

So the $this->qb_limit and $this->qb_offset class objects are not updated because null evaluates as true when fed to is_null() or empty().

CodeIgniter Active Record not equal

$this->db->where('emailsToCampaigns.campaignId !=' , $campaignId);

This should work (which you have tried)

To debug you might place this code just after you execute your query to see what exact SQL it is producing, this might give you clues, you might add that to the question to allow for further help.

$this->db->get();              // your query executing

echo '<pre>';                  // to preserve formatting
die($this->db->last_query());  // halt execution and print last ran query.

subquery in codeigniter active record

I think this code will work. I dont know if this is acceptable query style in CI but it works perfectly in my previous problem. :)

$subquery = 'SELECT id_cer FROM revokace';

$this->db->select('*');
$this->db->where_not_in(id, $subquery);
$this->db->from('certs');
$query = $this->db->get();

CodeIgniter 404 Page Not Found, but why?

I had the same issue after migrating to a new environment and it was simply that the server didn't run mod_rewrite

a quick sudo a2enmod rewrite then sudo systemctl restart apache2

and problem solved...

Thanks @fanis who pointed that out in his comment on the question.

Multiple files upload (Array) with CodeIgniter 2.0

Save, then redefine the variable $_FILES to whatever you need. maybe not the best solution, but this worked for me.

function do_upload()
{

    $this->load->library('upload');
    $this->upload->initialize($this->set_upload_options());

    $quantFiles = count($_FILES['userfile']['name']);


    for($i = 0; $i < $quantFiles ; $i++)
    {
        $arquivo[$i] = array
                    (
                        'userfile' => array 
                                        (
                                            'name' => $_FILES['userfile']['name'][$i],
                                            'type' => $_FILES['userfile']['type'][$i],
                                            'tmp_name' => $_FILES['userfile']['tmp_name'][$i],
                                            'error' => $_FILES['userfile']['error'][$i],
                                            'size' => $_FILES['userfile']['size'][$i]
                                        )
                    );
    }


    for($i = 0; $i < $quantFiles ; $i++)
    {
        $_FILES = '';
        $_FILES = $arquivo[$i];



        if ( ! $this->upload->do_upload())
        {
            $error[$i] = array('error' => $this->upload->display_errors());


            return FALSE;
        }
        else
        {

            $data[$i] = array('upload_data' => $this->upload->data());

            var_dump($this->upload->data());
        }


    }





    if(isset($error))
        {
            $this->index($error);
        }
        else
        {
            $this->index($data);
        }

}

the separate function to establish the config..

private function set_upload_options()
{   
    $config['upload_path'] = './uploads/';
    $config['allowed_types'] = 'xml|pdf';
    $config['max_size'] = '10000';

    return $config;
}

Display alert message and redirect after click on accept

use this code to redirect the page

echo "<script>alert('There are no fields to generate a report');document.location='admin/ahm/panel'</script>";

CodeIgniter removing index.php from url

Try the following

Open config.php and do following replaces

$config['index_page'] = "index.php"

to

$config['index_page'] = ""

In some cases the default setting for uri_protocol does not work properly. Just replace

$config['uri_protocol'] ="AUTO"

by

$config['uri_protocol'] = "REQUEST_URI"

.htaccess

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA] 

Note: .htaccess code vary depending on hosting server. In some hosting server (e.g.: Godaddy) need to use an extra ? in the last line of above code. The following line will be replaced with last line in applicable case:

// Replace last .htaccess line with this line
RewriteRule ^(.*)$ index.php?/$1 [L,QSA] 

CodeIgniter Disallowed Key Characters

In Ubuntu, you can solve the problem by clearing the cookies of your browser. I had the same problem and solved it this way.

what is the use of $this->uri->segment(3) in codeigniter pagination

This provides you to retrieve information from your URI strings

$this->uri->segment(n); // n=1 for controller, n=2 for method, etc

Consider this example:

http://example.com/index.php/controller/action/1stsegment/2ndsegment

it will return

$this->uri->segment(1); // controller
$this->uri->segment(2); // action
$this->uri->segment(3); // 1stsegment
$this->uri->segment(4); // 2ndsegment

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

Just add a ini_set('memory_limit', '-1'); line at the top of your web page.

And you can set your memory as per your need in the place of -1, to 16M, etc..

php codeigniter count rows

To count all rows in a table:

Controller:

function id_cont() {
   $news_data = new news_model();
   $ids=$news_data->data_model();
   print_r($ids);
}

Model:

function data_model() {
    $this->db->select('*');
    $this->db->from('news_data');
    $id = $this->db->get()->num_rows();
    return $id;
}

Getting data posted in between two dates

This worked great for me

$this->db->where('sell_date BETWEEN "'. date('Y-m-d', strtotime($start_date)). '" and "'. date('Y-m-d', strtotime($end_date)).'"');

CodeIgniter Select Query

echo $this->db->select('title, content, date')->get_compiled_select();

Codeigniter $this->input->post() empty while $_POST is working correctly

The problem is that $this->input->post() does not support getting all POST data, only specific data, for example $this->input->post('my_post_var'). This is why var_dump($this->input->post()); is empty.

A few solutions, stick to $_POST for retrieving all POST data, or assign variables from each POST item that you need, for example:

// variables will be false if not post data exists
$var_1 = $this->input->post('my_post_var_1');
$var_2 = $this->input->post('my_post_var_2');
$var_3 = $this->input->post('my_post_var_3');

However, since the above code is not very DRY, I like to do the following:

if(!empty($_POST)) 
{
    // get all post data in one nice array
    foreach ($_POST as $key => $value) 
    {
        $insert[$key] = $value;
    }
}
else
{
    // user hasen't submitted anything yet!
}

codeigniter, result() vs. result_array()

in my experince the problem using result() and result_array() in my JSON if using result() there no problem its works but if using result_array() i got error "Trying to get property of non-object" so im not search into deep the problem so i just using result() if using JSON and using result_array() if not using JSON

How to add an ORDER BY clause using CodeIgniter's Active Record methods?

Simple and easy:

$this->db->order_by("name", "asc");
$query = $this->db->get($this->table_name);
return $query->result();

How to insert multiple rows from array using CodeIgniter framework?

Although it is too late to answer this question. Here are my answer on the same.

If you are using CodeIgniter then you can use inbuilt methods defined in query_builder class.

$this->db->insert_batch()

Generates an insert string based on the data you supply, and runs the query. You can either pass an array or an object to the function. Here is an example using an array:

$data = array(
    array(
            'title' => 'My title',
            'name' => 'My Name',
            'date' => 'My date'
    ),
    array(
            'title' => 'Another title',
            'name' => 'Another Name',
            'date' => 'Another date'
    )
);

$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'),  ('Another title', 'Another name', 'Another date')

The first parameter will contain the table name, the second is an associative array of values.

You can find more details about query_builder here

How should I choose an authentication library for CodeIgniter?

Also take a look at BackendPro

Ultimately you will probably end up writing something custom, but there's nothing wrong with borrowing concepts from DX Auth, Freak Auth, BackendPro, etc.

My experiences with the packaged apps is they are specific to certain structures and I have had problems integrating them into my own applications without requiring hacks, then if the pre-package has an update, I have to migrate them in.

I also use Smarty and ADOdb in my CI code, so no matter what I would always end up making major code changes.

CodeIgniter query: How to move a column value to another column in the same row and save the current time in the original column?

Yes, this is possible and I would like to provide a slight alternative to Rajeev's answer that does not pass a php-generated datetime formatted string to the query.

The important distinction about how to declare the values to be SET in the UPDATE query is that they must not be quoted as literal strings.

To prevent CodeIgniter from doing this "favor" automatically, use the set() method with a third parameter of false.

$userId = 444;
$this->db->set('Last', 'Current', false);
$this->db->set('Current', 'NOW()', false);
$this->db->where('Id', $userId);
// return $this->db->get_compiled_update('Login');  // uncomment to see the rendered query
$this->db->update('Login');
return $this->db->affected_rows();  // this is expected to return the integer: 1

The generated query (depending on your database adapter) would be like this:

UPDATE `Login` SET Last = Current, Current = NOW() WHERE `Id` = 444

Demonstrated proof that the query works: https://www.db-fiddle.com/f/vcc6PfMcYhDD87wZE5gBtw/0

In this case, Last and Current ARE MySQL Keywords, but they are not Reserved Keywords, so they don't need to be backtick-wrapped.

If your precise query needs to have properly quoted identifiers (table/column names), then there is always protectIdentifiers().

JQuery Ajax POST in Codeigniter

$(document).ready(function(){   

    $("#send").click(function()
    {       
     $.ajax({
         type: "POST",
         url: base_url + "chat/post_action", 
         data: {textbox: $("#textbox").val()},
         dataType: "text",  
         cache:false,
         success: 
              function(data){
                alert(data);  //as a debugging message.
              }
          });// you have missed this bracket
     return false;
 });
 });

How to disable PHP Error reporting in CodeIgniter?

Here is the typical structure of new Codeigniter project:

- application/
- system/
- user_guide/
- index.php <- this is the file you need to change

I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.

With this code you can deploy your site to your production server without changing index.php each time.

// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
    define('ENVIRONMENT', 'development');
} else {
    define('ENVIRONMENT', 'production');
}

/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 *
 * Different environments will require different levels of error reporting.
 * By default development will show errors but testing and live will hide them.
 */

if (defined('ENVIRONMENT')) {
    switch (ENVIRONMENT) {
        case 'development':
            error_reporting(E_ALL);
            break;
        case 'testing':
        case 'production':
            error_reporting(0);
            ini_set('display_errors', 0);  
            break;
        default:
            exit('The application environment is not set correctly.');
    }
}

Redirect with CodeIgniter

If you want to redirect previous location or last request then you have to include user_agent library:

$this->load->library('user_agent');

and then use at last in a function that you are using:

redirect($this->agent->referrer());

its working for me.

Which version of CodeIgniter am I currently using?

Please check the file "system/core/CodeIgniter.php". It is defined in const CI_VERSION = '3.1.10';

How to save and extract session data in codeigniter

CI Session Class track information about each user while they browse site.Ci Session class generates its own session data, offering more flexibility for developers.

Initializing a Session

To initialize the Session class manually in our controller constructor use following code.

Adding Custom Session Data

We can add our custom data in session array.To add our data to the session array involves passing an array containing your new data to this function.

$this->session->set_userdata($newarray);

Where $newarray is an associative array containing our new data.

$newarray = array( 'name' => 'manish', 'email' => '[email protected]'); $this->session->set_userdata($newarray); 

Retrieving Session

$session_id = $this->session->userdata('session_id');

Above function returns FALSE (boolean) if the session array does not exist.

Retrieving All Session Data

$this->session->all_userdata()

I have taken reference from http://www.tutsway.com/codeigniter-session.php.

Directory index forbidden by Options directive

In my case, it's a typo caused this issue:

<VirtualHost *.8080>

should be

<VirtualHost *:8080>

Using Mysql WHERE IN clause in codeigniter

$data = $this->db->get_where('columnname',array('code' => 'B'));
$this->db->where_in('columnname',$data);
$this->db->where('code !=','B');
$query =  $this->db->get();
return $query->result_array();

CodeIgniter - return only one row?

To make the code clear that you are intending to get the first row, CodeIgniter now allows you to use:

if ($query->num_rows() > 0) {
    return $query->first_row();
}

To retrieve the first row.

how to delete a specific row in codeigniter?

**multiple delete not working**

function delete_selection() 
{
        $id_array = array();
        $selection = $this->input->post("selection", TRUE);
        $id_array = explode("|", $selection);

        foreach ($id_array as $item):
            if ($item != ''):
                //DELETE ROW
                $this->db->where('entry_id', $item);
                $this->db->delete('helpline_entry');
            endif;
        endforeach;
    }

Codeigniter displays a blank page instead of error messages

after installation of xamp/wamp you may notice few errors of similar nature. If your website was already running dont worry, it is a configuration related issue.

1) check database connections in database.php file inside application folder 2) check config.php file check url is correct or not? 3) by default short tags are off in new installations then follow the procedure below

in php.ini file change "short_open_tag=Off" to "short_open_tag=On"

Make sure to restart apache after doing this.

hope this helps.

Codeigniter: does $this->db->last_query(); execute a query?

The query execution happens on all get methods like

$this->db->get('table_name');
$this->db->get_where('table_name',$array);

While last_query contains the last query which was run

$this->db->last_query();

If you want to get query string without execution you will have to do this. Go to system/database/DB_active_rec.php Remove public or protected keyword from these functions

public function _compile_select($select_override = FALSE)
public function _reset_select()

Now you can write query and get it in a variable

$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();

Now reset query so if you want to write another query the object will be cleared.

$this->db->_reset_select();

And the thing is done. Cheers!!! Note : While using this way you must use

$this->db->from('myTable')

instead of

$this->db->get('myTable')

which runs the query.

Take a look at this example

PHP - get base64 img string decode and save as jpg (resulting empty image )

Here's what finally worked for me. You'll have to convert the code to suit your own needs, but this will do it.

$fname = filter_input(INPUT_POST, "name");
$img = filter_input(INPUT_POST, "image");
$img = str_replace('data:image/png;base64,', '', $img);
$img = str_replace(' ', '+', $img);
$img = base64_decode($img);

file_put_contents($fname, $img);

print "Image has been saved!";

How do I get the project basepath in CodeIgniter

Following are the build-in constants you can use as per your requirements for getting the paths in Codeigniter:

EXT: The PHP file extension

FCPATH: Path to the front controller (this file) (root of CI)

SELF: The name of THIS file (index.php)

BASEPATH: Path to the system folder

APPPATH: The path to the “application” folder

Thanks.

Object of class stdClass could not be converted to string

In General to get rid of

Object of class stdClass could not be converted to string.

try to use echo '<pre>'; print_r($sql_query); for my SQL Query got the result as

stdClass Object
(
    [num_rows] => 1
    [row] => Array
        (
            [option_id] => 2
            [type] => select
            [sort_order] => 0
        )

    [rows] => Array
        (
            [0] => Array
                (
                    [option_id] => 2
                    [type] => select
                    [sort_order] => 0
                )

        )

)

In order to acces there are different methods E.g.: num_rows, row, rows

echo $query2->row['option_id'];

Will give the result as 2

Codeigniter LIKE with wildcard(%)

$this->db->like() automatically adds the %s and escapes the string. So all you need is

$this->db->like('title', $query);
$res = $this->db->get('film');

See the CI documentation for reference: CI 2, CI 3, CI 4

PHP Parse error: syntax error, unexpected end of file in a CodeIgniter View

Unexpected end of file means that something else was expected before the PHP parser reached the end of the script.

Judging from your HUGE file, it's probably that you're missing a closing brace (}) from an if statement.

Please at least attempt the following things:

  1. Separate your code from your view logic.
  2. Be consistent, you're using an end ; in some of your embedded PHP statements, and not in others, ie. <?php echo base_url(); ?> vs <?php echo $this->layouts->print_includes() ?>. It's not required, so don't use it (or do, just do one or the other).
  3. Repeated because it's important, separate your concerns. There's no need for all of this code.
  4. Use an IDE, it will help you with errors such as this going forward.

Fatal error: Call to undefined function base_url() in C:\wamp\www\Test-CI\application\views\layout.php on line 5

you have to use echo before base_url() function. otherwise it woudn't print the base url.

Showing all session data at once?

print_r($this->session->userdata); 

or

print_r($this->session->all_userdata());

Codeigniter unset session

$session_data = array('username' =>"shashikant");
$this->session->set_userdata('logged_in', $session_data);

$this->session->unset_userdata('logged_in');

Inserting NOW() into Database with CodeIgniter's Active Record

aspirinemaga, just replace:

$this->db->set('time', 'NOW()', FALSE);
$this->db->insert('mytable', $data);

for it:

$this->db->set('time', 'NOW() + INTERVAL 1 DAY', FALSE);
$this->db->insert('mytable', $data);

CodeIgniter: 404 Page Not Found on Live Server

Try to add following line in root folder index.php after php starts:

ob_start();

This works for me.

How to get id from URL in codeigniter?

A bit late but this worked for me

  $data_id = $this->input->get('name_of_field');

How to INNER JOIN 3 tables using CodeIgniter

function fetch_comments($ticket_id){
    $this->db->select('tbl_tickets_replies.comments, 
           tbl_users.username,tbl_roles.role_name');
    $this->db->where('tbl_tickets_replies.ticket_id',$ticket_id);
    $this->db->join('tbl_users','tbl_users.id = tbl_tickets_replies.user_id');
    $this->db->join('tbl_roles','tbl_roles.role_id=tbl_tickets_replies.role_id');
    return $this->db->get('tbl_tickets_replies');
}

How to call codeigniter controller function from view

Go to the top of your View code and do it like this :

  <?php
     $this->load->model('MyModelName');
     $MyFunctionReturnValue = $this->MyModelName->MyFunctionName($param));
?>

<div class="row">
    Your HTML CODE
</div>

CodeIgniter - How to return Json response from controller

//do the edit in your javascript

$('.signinform').submit(function() { 
   $(this).ajaxSubmit({ 
       type : "POST",
       //set the data type
       dataType:'json',
       url: 'index.php/user/signin', // target element(s) to be updated with server response 
       cache : false,
       //check this in Firefox browser
       success : function(response){ console.log(response); alert(response)},
       error: onFailRegistered
   });        
   return false; 
}); 


//controller function

public function signin() {
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);    

   //add the header here
    header('Content-Type: application/json');
    echo json_encode( $arr );
}

How to do error logging in CodeIgniter (PHP)

In config.php add or edit the following lines to this:
------------------------------------------------------
$config['log_threshold'] = 4; // (1/2/3)
$config['log_path'] = '/home/path/to/application/logs/';

Run this command in the terminal:
----------------------------------
sudo chmod -R 777 /home/path/to/application/logs/

How to load a controller from another controller in codeigniter?

You can't load a controller from a controller in CI - unless you use HMVC or something.

You should think about your architecture a bit. If you need to call a controller method from another controller, then you should probably abstract that code out to a helper or library and call it from both controllers.

UPDATE

After reading your question again, I realize that your end goal is not necessarily HMVC, but URI manipulation. Correct me if I'm wrong, but it seems like you're trying to accomplish URLs with the first section being the method name and leave out the controller name altogether.

If this is the case, you'd get a cleaner solution by getting creative with your routes.

For a really basic example, say you have two controllers, controller1 and controller2. Controller1 has a method method_1 - and controller2 has a method method_2.

You can set up routes like this:

$route['method_1'] = "controller1/method_1";
$route['method_2'] = "controller2/method_2";

Then, you can call method 1 with a URL like http://site.com/method_1 and method 2 with http://site.com/method_2.

Albeit, this is a hard-coded, very basic, example - but it could get you to where you need to be if all you need to do is remove the controller from the URL.


You could also go with remapping your controllers.

From the docs: "If your controller contains a function named _remap(), it will always get called regardless of what your URI contains.":

public function _remap($method)
{
    if ($method == 'some_method')
    {
        $this->$method();
    }
    else
    {
        $this->default_method();
    }
}

CodeIgniter Active Record - Get number of returned rows

If you only need the number of rows in a query and don't need the actual row data, use count_all_results

echo $this->db
       ->where('active',1)
       ->count_all_results('table_name');

How to pass a parameter like title, summary and image in a Facebook sharer URL

The only parameter you need right now is ?u=<YOUR_URL>. All other data will be fetched from page or (better) from your open graph meta tags:

<meta property="og:url"                content="http://www.nytimes.com/2015/02/19/arts/international/when-great-minds-dont-think-alike.html" />
<meta property="og:type"               content="article" />
<meta property="og:title"              content="When Great Minds Don’t Think Alike" />
<meta property="og:description"        content="How much does culture influence creative thinking?" />
<meta property="og:image"              content="http://static01.nyt.com/images/2015/02/19/arts/international/19iht-btnumbers19A/19iht-btnumbers19A-facebookJumbo-v2.jpg" />

Example & description here

You can test your page for accordance in the debugger.

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

And just to give you yet another option, you can use NOT ISNULL(archived) as your WHERE filter.

Codeigniter $this->db->order_by(' ','desc') result is not complete

$this->db1->where('tennant_id', $tennant_id);
$this->db1->order_by('id', 'DESC');
return $this->db1->get('courses')->result();

$this->session->set_flashdata() and then $this->session->flashdata() doesn't work in codeigniter

Displaying a flash message after redirect in Codeigniter

In Your Controller set this

<?php

public function change_password(){







if($this->input->post('submit')){
$change = $this->common_register->change_password();

if($change == true){
$messge = array('message' => 'Password chnage successfully','class' => 'alert alert-success fade in');
$this->session->set_flashdata('item', $messge);
}else{
$messge = array('message' => 'Wrong password enter','class' => 'alert alert-danger fade in');
$this->session->set_flashdata('item',$messge );
}
$this->session->keep_flashdata('item',$messge);



redirect('controllername/methodname','refresh');
}

?>

In Your View File Set this
<script type="application/javascript">
/** After windod Load */
$(window).bind("load", function() {
  window.setTimeout(function() {
    $(".alert").fadeTo(500, 0).slideUp(500, function(){
        $(this).remove();
    });
}, 4000);
});
</script>

<?php

if($this->session->flashdata('item')) {
$message = $this->session->flashdata('item');
?>
<div class="<?php echo $message['class'] ?>"><?php echo $message['message']; ?>

</div>
<?php
}

?>

Please check below link for Displaying a flash message after redirect in Codeigniter

Codeigniter how to create PDF

Create new pdf helper file in application\helpers folder and name it pdf_helper.php. Add below code in pdf_helper.php file:

        function tcpdf()
      {
        require_once('tcpdf/config/lang/eng.php');
        require_once('tcpdf/tcpdf.php');
      }
     ?>

For more Please follow the below link:

 http://www.ccode4u.com/how-to-generate-pdf-file-in-codeigniter.html

How to set time zone in codeigniter?

Add it to your project/application/config/config.php file, and it will work on all over your site.

date_default_timezone_set('Asia/Kolkata');

CodeIgniter - how to catch DB errors?

Maybe this:

$db_debug = $this->db->db_debug; //save setting

$this->db->db_debug = FALSE; //disable debugging for queries

$result = $this->db->query($sql); //run query

//check for errors, etc

$this->db->db_debug = $db_debug; //restore setting

PostgreSQL next value of the sequences?

To answer your question literally, here's how to get the next value of a sequence without incrementing it:

SELECT
 CASE WHEN is_called THEN
   last_value + 1
 ELSE
   last_value
 END
FROM sequence_name

Obviously, it is not a good idea to use this code in practice. There is no guarantee that the next row will really have this ID. However, for debugging purposes it might be interesting to know the value of a sequence without incrementing it, and this is how you can do it.

How to get base url in CodeIgniter 2.*

I know this is very late, but is useful for newbies. We can atuload url helper and it will be available throughout the application. For this in application\config\autoload.php modify as follows -

$autoload['helper'] = array('url'); 

base_url() function not working in codeigniter

Question -I wanted to load my css file but it was not working even though i autoload and manual laod why ? i found the solution => here is my solution : application>config>config.php $config['base_url'] = 'http://localhost/CodeIgniter/'; //paste the link to base url

question explanation:

" > i had my bootstrap.min.css file inside assets/css folder where assets is root directory which i was created.But it was not working even though when i loaded ? 1. $autoload['helper'] = array('url'); 2. $this->load->helper('url'); in my controllar then i go to my

CodeIgniter - File upload required validation

you can solve it by overriding the Run function of CI_Form_Validation

copy this function in a class which extends CI_Form_Validation .

This function will override the parent class function . Here i added only a extra check which can handle file also

/**
 * Run the Validator
 *
 * This function does all the work.
 *
 * @access  public
 * @return  bool
 */
function run($group = '') {
    // Do we even have any data to process?  Mm?
    if (count($_POST) == 0) {
        return FALSE;
    }

    // Does the _field_data array containing the validation rules exist?
    // If not, we look to see if they were assigned via a config file
    if (count($this->_field_data) == 0) {
        // No validation rules?  We're done...
        if (count($this->_config_rules) == 0) {
            return FALSE;
        }

        // Is there a validation rule for the particular URI being accessed?
        $uri = ($group == '') ? trim($this->CI->uri->ruri_string(), '/') : $group;

        if ($uri != '' AND isset($this->_config_rules[$uri])) {
            $this->set_rules($this->_config_rules[$uri]);
        } else {
            $this->set_rules($this->_config_rules);
        }

        // We're we able to set the rules correctly?
        if (count($this->_field_data) == 0) {
            log_message('debug', "Unable to find validation rules");
            return FALSE;
        }
    }

    // Load the language file containing error messages
    $this->CI->lang->load('form_validation');

    // Cycle through the rules for each field, match the
    // corresponding $_POST or $_FILES item and test for errors
    foreach ($this->_field_data as $field => $row) {
        // Fetch the data from the corresponding $_POST or $_FILES array and cache it in the _field_data array.
        // Depending on whether the field name is an array or a string will determine where we get it from.

        if ($row['is_array'] == TRUE) {

            if (isset($_FILES[$field])) {
                $this->_field_data[$field]['postdata'] = $this->_reduce_array($_FILES, $row['keys']);
            } else {
                $this->_field_data[$field]['postdata'] = $this->_reduce_array($_POST, $row['keys']);
            }
        } else {
            if (isset($_POST[$field]) AND $_POST[$field] != "") {
                $this->_field_data[$field]['postdata'] = $_POST[$field];
            } else if (isset($_FILES[$field]) AND $_FILES[$field] != "") {
                $this->_field_data[$field]['postdata'] = $_FILES[$field];
            }
        }

        $this->_execute($row, explode('|', $row['rules']), $this->_field_data[$field]['postdata']);
    }

    // Did we end up with any errors?
    $total_errors = count($this->_error_array);

    if ($total_errors > 0) {
        $this->_safe_form_data = TRUE;
    }

    // Now we need to re-set the POST data with the new, processed data
    $this->_reset_post_array();

    // No errors, validation passes!
    if ($total_errors == 0) {
        return TRUE;
    }

    // Validation fails
    return FALSE;
}

How to prevent the "Confirm Form Resubmission" dialog?

Quick Answer

Use different methods to load the form and save/process form.

Example.

Login.php

Load login form at Login/index Validate login at Login/validate

On Success

Redirect the user to User/dashboard

On failure

Redirect the user to login/index

multiple where condition codeigniter

Try this

$data = array(
               'email' =>$email,
               'last_ip' => $last_ip
            );

$where = array('username ' => $username , 'status ' => $status);
$this->db->where($where);
$this->db->update('table_user ', $data); 

Trying to get property of non-object - CodeIgniter

In my case, I was looping through a series of objects from an XML file, but some of the instances apparently were not objects which was causing the error. Checking if the object was empty before processing it fixed the problem.

In other words, without checking if the object was empty, the script would error out on any empty object with the error as given below.

Trying to get property of non-object

For Example:

if (!empty($this->xml_data->thing1->thing2))
{
   foreach ($this->xml_data->thing1->thing2 as $thing)
   {

   }
}

CodeIgniter : Unable to load the requested file:

File names are case sensitive - please check your file name. it should be in same case in view folder

Where do I put image files, css, js, etc. in Codeigniter?

Hi our sturucture is like Application, system, user_guide

create a folder name assets just near all the folders and then inside this assets folder create css and javascript and images folder put all your css js insiide the folders

now go to header.php and call the css just like this.

<link rel="stylesheet" href="<?php echo base_url();?>assets/css/touchTouch.css">
  <link rel="stylesheet" href="<?php echo base_url();?>assets/css/style.css">
  <link rel="stylesheet" href="<?php echo base_url();?>assets/css/camera.css"> 

Fatal error: Cannot use object of type stdClass as array in

Sorry.Though it is a bit late but hope it would help others as well . Always use the stdClass object.e.g

 $getvidids = $ci->db->query("SELECT * FROM videogroupids WHERE videogroupid='$videogroup'   AND used='0' LIMIT 10");

foreach($getvidids->result() as $key=>$myids)
{

  $vidid[$key] = $myids->videoid;  // better methodology to retrieve and store multiple records in arrays in loop
 }

Angular Material: mat-select not selecting default

I did this.

<div>
    <mat-select [(ngModel)]="selected">
        <mat-option *ngFor="let option of options" 
            [value]="option.id === selected.id ? selected : option">
            {{ option.name }}
        </mat-option>
    </mat-select>
</div>

Normally you can do [value]="option", unless you get your options from some database?? I think either the delay of getting the data causes it not to work, or the objects gotten are different in some way even though they are the same?? Weirdly enough it's most likely the later one, as I also tried [value]="option === selected ? selected : option" and it didn't work.

How to fix "could not find a base address that matches schema http"... in WCF

There should be a way to solve this pretty easily with external config sections and an extra deployment step that drops a deployment specific external .config file into a known location. We typically use this solution to handle the different server configurations for our different deployment environments (Staging, QA, production, etc) with our "dev box" being the default if no special copy occurs.

Why emulator is very slow in Android Studio?

In my case, the problem was coming from the execution of WinSAT.exe (located in System32 folder). I disabled it and issue solved.

To turn it off:

  1. Start > Task Scheduler (taskschd.msc)
  2. Find Task Scheduler (Local)
  3. Task Scheduler Library
  4. Microsoft > Windows > Maintenance
  5. Right click WinSAT
  6. Select disable.

The Reference

Also, suppress it from Task Manager or simply reboot your machine.


Point: In this situation (when the problem comes from WinSAT) emulator works (with poor performance) when you use Software - GLES 2.0 and works with very very poor performance when you use Hardware - GLES 2.0.

Form content type for a json HTTP POST?

I have wondered the same thing. Basically it appears that the html spec has different content types for html and form data. Json only has a single content type.

According to the spec, a POST of json data should have the content-type:
application/json

Relevant portion of the HTML spec

6.7 Content types (MIME types)
...
Examples of content types include "text/html", "image/png", "image/gif", "video/mpeg", "text/css", and "audio/basic".

17.13.4 Form content types
...
application/x-www-form-urlencoded
This is the default content type. Forms submitted with this content type must be encoded as follows

Relevant portion of the JSON spec

  1. IANA Considerations
    The MIME media type for JSON text is application/json.

Upgrade Node.js to the latest version on Mac OS

Go to http://nodejs.org and download and run the installer. It works now - for me at least.

Finding Key associated with max Value in a Java Map

For my project, I used a slightly modified version of Jon's and Fathah's solution. In the case of multiple entries with the same value, it returns the last entry it finds:

public static Entry<String, Integer> getMaxEntry(Map<String, Integer> map) {        
    Entry<String, Integer> maxEntry = null;
    Integer max = Collections.max(map.values());

    for(Entry<String, Integer> entry : map.entrySet()) {
        Integer value = entry.getValue();

        if(null != value && max == value) {
            maxEntry = entry;
        }
    }

    return maxEntry;
}

Parsing JSON in Java without knowing JSON format

JSON of unknown format to HashMap

writing JSON And reading Json

public static JsonParser parser = new JsonParser();
public static void main(String args[]) {
     writeJson("JsonFile.json");
     readgson("JsonFile.json");
}
public static void readgson(String file) {
    try {
        System.out.println( "Reading JSON file from Java program" );

        FileReader fileReader = new FileReader( file );
        com.google.gson.JsonObject object = (JsonObject) parser.parse( fileReader );

        Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys = object.entrySet();
        if ( keys.isEmpty() ) {
            System.out.println( "Empty JSON Object" );
        }else {
            Map<String, Object> map = json_UnKnown_Format( keys );
            System.out.println("Json 2 Map : "+map);
        }

    } catch (IOException ex) {
        System.out.println("Input File Does not Exists.");
    }
}
public static Map<String, Object> json_UnKnown_Format( Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> keys ){
    Map<String, Object> jsonMap = new HashMap<String, Object>();
    for (Entry<String, JsonElement> entry : keys) {
        String keyEntry = entry.getKey();
        System.out.println(keyEntry + " : ");
        JsonElement valuesEntry =  entry.getValue();
        if (valuesEntry.isJsonNull()) {
            System.out.println(valuesEntry);
            jsonMap.put(keyEntry, valuesEntry);
        }else if (valuesEntry.isJsonPrimitive()) {
            System.out.println("P - "+valuesEntry);
            jsonMap.put(keyEntry, valuesEntry);
        }else if (valuesEntry.isJsonArray()) {
            JsonArray array = valuesEntry.getAsJsonArray();
            List<Object> array2List = new ArrayList<Object>();
            for (JsonElement jsonElements : array) {
                System.out.println("A - "+jsonElements);
                array2List.add(jsonElements);
            }
            jsonMap.put(keyEntry, array2List);
        }else if (valuesEntry.isJsonObject()) {             
             com.google.gson.JsonObject obj = (JsonObject) parser.parse(valuesEntry.toString());                    
             Set <java.util.Map.Entry<String, com.google.gson.JsonElement>> obj_key = obj.entrySet();
             jsonMap.put(keyEntry, json_UnKnown_Format(obj_key));
        }
    }
    return jsonMap;
}
@SuppressWarnings("unchecked")
public static void writeJson( String file ) {

    JSONObject json = new JSONObject();

    json.put("Key1", "Value");
    json.put("Key2", 777); // Converts to "777"
    json.put("Key3", null);
    json.put("Key4", false);

        JSONArray jsonArray = new JSONArray();
        jsonArray.put("Array-Value1");
        jsonArray.put(10); 
        jsonArray.put("Array-Value2");

    json.put("Array : ", jsonArray); // "Array":["Array-Value1", 10,"Array-Value2"]

        JSONObject jsonObj = new JSONObject();
        jsonObj.put("Obj-Key1", 20);
        jsonObj.put("Obj-Key2", "Value2");
        jsonObj.put(4, "Value2"); // Converts to "4"

    json.put("InnerObject", jsonObj);

        JSONObject jsonObjArray = new JSONObject();
            JSONArray objArray = new JSONArray();
            objArray.put("Obj-Array1");
            objArray.put(0, "Obj-Array3");
        jsonObjArray.put("ObjectArray", objArray);

    json.put("InnerObjectArray", jsonObjArray);

        Map<String, Integer> sortedTree = new TreeMap<String, Integer>();
        sortedTree.put("Sorted1", 10);
        sortedTree.put("Sorted2", 103);
        sortedTree.put("Sorted3", 14);

    json.put("TreeMap", sortedTree);        

    try {
        System.out.println("Writting JSON into file ...");
        System.out.println(json);
        FileWriter jsonFileWriter = new FileWriter(file);
        jsonFileWriter.write(json.toJSONString());
        jsonFileWriter.flush();
        jsonFileWriter.close();
        System.out.println("Done");

    } catch (IOException e) { 
        e.printStackTrace();
    }

}

Oracle Add 1 hour in SQL

Use an interval:

select some_date_column + interval '1' hour 
from your_table;

Use string value from a cell to access worksheet of same name

Here is a solution using INDIRECT, which if you drag the formula, it will pick up different cells from the target sheet accordingly. It uses R1C1 notation and is not limited to working only on columns A-Z.

=INDIRECT("'"&$A$5&"'!R"&ROW()&"C"&COLUMN(),FALSE)

This version picks up the value from the target cell corresponding to the cell where the formula is placed. For example, if you place the formula in 'Summary'!B5 then it will pick up the value from 'SERVER-ONE'!B5, not 'SERVER-ONE'!G7 as specified in the original question. But you could easily add in offsets to the row and column to achieve the desired mapping in any case.

How can I install packages using pip according to the requirements.txt file from a local directory?

This works for me:

$ pip install -r requirements.txt --no-index --find-links file:///tmp/packages

--no-index - Ignore package index (only looking at --find-links URLs instead).

-f, --find-links <URL> - If a URL or path to an HTML file, then parse for links to archives.

If a local path or file:// URL that's a directory, then look for archives in the directory listing.

Example to use shared_ptr?

Learning to use smart pointers is in my opinion one of the most important steps to become a competent C++ programmer. As you know whenever you new an object at some point you want to delete it.

One issue that arise is that with exceptions it can be very hard to make sure a object is always released just once in all possible execution paths.

This is the reason for RAII: http://en.wikipedia.org/wiki/RAII

Making a helper class with purpose of making sure that an object always deleted once in all execution paths.

Example of a class like this is: std::auto_ptr

But sometimes you like to share objects with other. It should only be deleted when none uses it anymore.

In order to help with that reference counting strategies have been developed but you still need to remember addref and release ref manually. In essence this is the same problem as new/delete.

That's why boost has developed boost::shared_ptr, it's reference counting smart pointer so you can share objects and not leak memory unintentionally.

With the addition of C++ tr1 this is now added to the c++ standard as well but its named std::tr1::shared_ptr<>.

I recommend using the standard shared pointer if possible. ptr_list, ptr_dequeue and so are IIRC specialized containers for pointer types. I ignore them for now.

So we can start from your example:

std::vector<gate*> G; 
G.push_back(new ANDgate);  
G.push_back(new ORgate); 
for(unsigned i=0;i<G.size();++i) 
{ 
  G[i]->Run(); 
} 

The problem here is now that whenever G goes out scope we leak the 2 objects added to G. Let's rewrite it to use std::tr1::shared_ptr

// Remember to include <memory> for shared_ptr
// First do an alias for std::tr1::shared_ptr<gate> so we don't have to 
// type that in every place. Call it gate_ptr. This is what typedef does.
typedef std::tr1::shared_ptr<gate> gate_ptr;    
// gate_ptr is now our "smart" pointer. So let's make a vector out of it.
std::vector<gate_ptr> G; 
// these smart_ptrs can't be implicitly created from gate* we have to be explicit about it
// gate_ptr (new ANDgate), it's a good thing:
G.push_back(gate_ptr (new ANDgate));  
G.push_back(gate_ptr (new ORgate)); 
for(unsigned i=0;i<G.size();++i) 
{ 
   G[i]->Run(); 
} 

When G goes out of scope the memory is automatically reclaimed.

As an exercise which I plagued newcomers in my team with is asking them to write their own smart pointer class. Then after you are done discard the class immedietly and never use it again. Hopefully you acquired crucial knowledge on how a smart pointer works under the hood. There's no magic really.

Importing CSV File to Google Maps

GPS Visualizer has an interface by which you can cut and paste a CSV file and convert it to kml:

http://www.gpsvisualizer.com/map_input?form=googleearth

Then use Google Earth. If you don't have Google Earth and want to display it online I found another nifty service that will plot kml files online:

http://display-kml.appspot.com/

How to display binary data as image - extjs 4

In ExtJs, you can use

xtype: 'image'

to render a image.

Here is a fiddle showing rendering of binary data with extjs.

atob -- > converts ascii to binary

btoa -- > converts binary to ascii

Ext.application({
    name: 'Fiddle',

    launch: function () {
        var srcBase64 = "data:image/jpeg;base64," + btoa(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8H8hYDwAFegHS8+X7mgAAAABJRU5ErkJggg=="));

        Ext.create("Ext.panel.Panel", {
            title: "Test",
            renderTo: Ext.getBody(),
            height: 400,
            items: [{
                xtype: 'image',
                width: 100,
                height: 100,
                src: srcBase64
            }]
        })
    }
});

https://fiddle.sencha.com/#view/editor&fiddle/28h0

How do I POST XML data to a webservice with Postman?

Send XML requests with the raw data type, then set the Content-Type to text/xml.


  1. After creating a request, use the dropdown to change the request type to POST.

    Set request type to POST

  2. Open the Body tab and check the data type for raw.

    Setting data type to raw

  3. Open the Content-Type selection box that appears to the right and select either XML (application/xml) or XML (text/xml)

    Selecting content-type text/xml

  4. Enter your raw XML data into the input field below

    Example of XML request in Postman

  5. Click Send to submit your XML Request to the specified server.

    Clicking the Send button

Declaring a variable and setting its value from a SELECT query in Oracle

For storing a single row output into a variable from the select into query :

declare v_username varchare(20); SELECT username into v_username FROM users WHERE user_id = '7';

this will store the value of a single record into the variable v_username.


For storing multiple rows output into a variable from the select into query :

you have to use listagg function. listagg concatenate the resultant rows of a coloumn into a single coloumn and also to differentiate them you can use a special symbol. use the query as below SELECT listagg(username || ',' ) within group (order by username) into v_username FROM users;

When to use AtomicReference in Java?

When do we use AtomicReference?

AtomicReference is flexible way to update the variable value atomically without use of synchronization.

AtomicReference support lock-free thread-safe programming on single variables.

There are multiple ways of achieving Thread safety with high level concurrent API. Atomic variables is one of the multiple options.

Lock objects support locking idioms that simplify many concurrent applications.

Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.

Concurrent collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.

Atomic variables have features that minimize synchronization and help avoid memory consistency errors.

Provide a simple example where AtomicReference should be used.

Sample code with AtomicReference:

String initialReference = "value 1";

AtomicReference<String> someRef =
    new AtomicReference<String>(initialReference);

String newReference = "value 2";
boolean exchanged = someRef.compareAndSet(initialReference, newReference);
System.out.println("exchanged: " + exchanged);

Is it needed to create objects in all multithreaded programs?

You don't have to use AtomicReference in all multi threaded programs.

If you want to guard a single variable, use AtomicReference. If you want to guard a code block, use other constructs like Lock /synchronized etc.

C++ floating point to integer type conversions

For most cases (long for floats, long long for double and long double):

long a{ std::lround(1.5f) }; //2l
long long b{ std::llround(std::floor(1.5)) }; //1ll

includes() not working in all browsers

If you look at the documentation of includes(), most of the browsers don't support this property.

You can use widely supported indexOf() after converting the property to string using toString():

if ($(".right-tree").css("background-image").indexOf("stage1") > -1) {
//                                           ^^^^^^^^^^^^^^^^^^^^^^

You can also use the polyfill from MDN.

if (!String.prototype.includes) {
    String.prototype.includes = function() {
        'use strict';
        return String.prototype.indexOf.apply(this, arguments) !== -1;
    };
}

How to send email attachments?

Here's another:

import smtplib
from os.path import basename
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate


def send_mail(send_from, send_to, subject, text, files=None,
              server="127.0.0.1"):
    assert isinstance(send_to, list)

    msg = MIMEMultipart()
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)
    msg['Date'] = formatdate(localtime=True)
    msg['Subject'] = subject

    msg.attach(MIMEText(text))

    for f in files or []:
        with open(f, "rb") as fil:
            part = MIMEApplication(
                fil.read(),
                Name=basename(f)
            )
        # After the file is closed
        part['Content-Disposition'] = 'attachment; filename="%s"' % basename(f)
        msg.attach(part)


    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

It's much the same as the first example... But it should be easier to drop in.

How can I submit a form using JavaScript?

You can use...

document.getElementById('theForm').submit();

...but don't replace the innerHTML. You could hide the form and then insert a processing... span which will appear in its place.

var form = document.getElementById('theForm');

form.style.display = 'none';

var processing = document.createElement('span');

processing.appendChild(document.createTextNode('processing ...'));

form.parentNode.insertBefore(processing, form);

Intellij JAVA_HOME variable

In my case I needed a lower JRE, so I had to tell IntelliJ to use a different one in "Platform Settings"

  • Platform Settings > SDKs ( +; )
  • Click the + button to add a new SDK (or rename and load an existing one)
  • Choose the /Contents/Home directory from the appropriate SDK
    (i.e. /Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home)

Java Regex Replace with Capturing Group

Source: java-implementation-of-rubys-gsub

Usage:

// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
    public String replacement() {
        float inches = Float.parseFloat(group(1));
        return Float.toString(2.54f * inches) + " cm";
    }
}.rewrite("a 17 inch display");
System.out.println(result);

// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
    public String replacement() {
        return group(1).toUpperCase();
    }
}.rewrite("ab12 cd efg34");
System.out.println(result);

Implementation (redesigned):

import static java.lang.String.format;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class Rewriter {
    private Pattern pattern;
    private Matcher matcher;

    public Rewriter(String regularExpression) {
        this.pattern = Pattern.compile(regularExpression);
    }

    public String group(int i) {
        return matcher.group(i);
    }

    public abstract String replacement() throws Exception;

    public String rewrite(CharSequence original) {
        return rewrite(original, new StringBuffer(original.length())).toString();
    }

    public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
        try {
            this.matcher = pattern.matcher(original);
            while (matcher.find()) {
                matcher.appendReplacement(destination, "");
                destination.append(replacement());
            }
            matcher.appendTail(destination);
            return destination;
        } catch (Exception e) {
            throw new RuntimeException("Cannot rewrite " + toString(), e);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(pattern.pattern());
        for (int i = 0; i <= matcher.groupCount(); i++)
            sb.append(format("\n\t(%s) - %s", i, group(i)));
        return sb.toString();
    }
}

Android: Color To Int conversion

All the methods and variables in Color are static. You can not instantiate a Color object.

Official Color Docs

The Color class defines methods for creating and converting color ints.

Colors are represented as packed ints, made up of 4 bytes: alpha, red, green, blue.

The values are unpremultiplied, meaning any transparency is stored solely in the alpha component, and not in the color components.

The components are stored as follows (alpha << 24) | (red << 16) | (green << 8) | blue.

Each component ranges between 0..255 with 0 meaning no contribution for that component, and 255 meaning 100% contribution.

Thus opaque-black would be 0xFF000000 (100% opaque but no contributions from red, green, or blue), and opaque-white would be 0xFFFFFFFF

How to randomize two ArrayLists in the same fashion?

Not totally sure what you mean by "automatically" - you can create a container object that holds both objects:

public class FileImageHolder { String fileName; String imageName; //TODO: insert stuff here }

And then put that in an array list and randomize that array list.

Otherwise, you would need to keep track of where each element moved in one list, and move it in the other one as well.

Best way to get the max value in a Spark dataframe column

To just get the value use any of these

  1. df1.agg({"x": "max"}).collect()[0][0]
  2. df1.agg({"x": "max"}).head()[0]
  3. df1.agg({"x": "max"}).first()[0]

Alternatively we could do these for 'min'

from pyspark.sql.functions import min, max
df1.agg(min("id")).collect()[0][0]
df1.agg(min("id")).head()[0]
df1.agg(min("id")).first()[0]

What's the difference between interface and @interface in java?

The interface keyword indicates that you are declaring a traditional interface class in Java.
The @interface keyword is used to declare a new annotation type.

See docs.oracle tutorial on annotations for a description of the syntax.
See the JLS if you really want to get into the details of what @interface means.

Create a table without a header in Markdown

Omitting the header above the divider produces a headerless table in at least Perl Text::MultiMarkdown and in FletcherPenney MultiMarkdown

|-------------|--------|
|**Name:**    |John Doe|
|**Position:**|CEO     |

See PHP Markdown feature request


Empty headers in PHP Parsedown produce tables with empty headers that are usually invisible (depending on your CSS) and so look like headerless tables.

|     |     |
|-----|-----|
|Foo  |37   |
|Bar  |101  |

What's the environment variable for the path to the desktop?

Multilingual Version, tested on Japanese OS
Batch File

set getdesk=REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" /v Desktop
FOR /f "delims=(=" %%G IN ('%getdesk% ^|find "_SZ"') DO set desktop=%%G
set desktop1=%desktop:*USERPROFILE%\=%
cd "%userprofile%\%desktop1%"
set getdesk=
set desktop1=
set desktop=

Storing images in SQL Server?

I fell into this dilemma once, and researched quite a bit on google for opinions. What I found was that indeed many see saving images to disk better for larger images, while mySQL allows for easier access, specially from languages like PHP.

I found a similar question

MySQL BLOB vs File for Storing Small PNG Images?

My final verdict was that for things such as a profile picture, just a small square image that needs to be there per user, mySQL would be better than storing a bunch of thumbs in the hdd, while for photo albums and things like that, folders/image files are better.

Hope it helps

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

I have faced the same issue and resolved as follows (if you have a project in local folder then follow the steps):

  1. create a new repo in guthub
  2. go to local folder and do "git init"
  3. git remote add origin (with your repo url) // simply copy from your repo
  4. git add -A
  5. git commit -m "your commit"
  6. git push -u origin master

javascript check for not null

This should work fine..

   if(val!= null)
    {
       alert("value is "+val.length); //-- this returns 4
    }
    else
    {
       alert("value* is null");
    }

Gradle: Execution failed for task ':processDebugManifest'

Duplication declaration of same activity in Android Manifest file.

Make div scrollable

Place this into your DIV style

overflow:scroll;

What causes HttpHostConnectException?

You must set proxy server for gradle at some time, you can try to change the proxy server ip address in gradle.properties which is under .gradle document

How to format current time using a yyyyMMddHHmmss format?

Use

fmt.Println(t.Format("20060102150405"))

as Go uses following constants to format date,refer here

const (
    stdLongMonth      = "January"
    stdMonth          = "Jan"
    stdNumMonth       = "1"
    stdZeroMonth      = "01"
    stdLongWeekDay    = "Monday"
    stdWeekDay        = "Mon"
    stdDay            = "2"
    stdUnderDay       = "_2"
    stdZeroDay        = "02"
    stdHour           = "15"
    stdHour12         = "3"
    stdZeroHour12     = "03"
    stdMinute         = "4"
    stdZeroMinute     = "04"
    stdSecond         = "5"
    stdZeroSecond     = "05"
    stdLongYear       = "2006"
    stdYear           = "06"
    stdPM             = "PM"
    stdpm             = "pm"
    stdTZ             = "MST"
    stdISO8601TZ      = "Z0700"  // prints Z for UTC
    stdISO8601ColonTZ = "Z07:00" // prints Z for UTC
    stdNumTZ          = "-0700"  // always numeric
    stdNumShortTZ     = "-07"    // always numeric
    stdNumColonTZ     = "-07:00" // always numeric
)

Wait for a void async method

I know this is an old question, but this is still a problem I keep walking into, and yet there is still no clear solution to do this correctly when using async/await in an async void signature method.

However, I noticed that .Wait() is working properly inside the void method.

and since async void and void have the same signature, you might need to do the following.

void LoadBlahBlah()
{
    blah().Wait(); //this blocks
}

Confusingly enough async/await does not block on the next code.

async void LoadBlahBlah()
{
    await blah(); //this does not block
}

When you decompile your code, my guess is that async void creates an internal Task (just like async Task), but since the signature does not support to return that internal Tasks

this means that internally the async void method will still be able to "await" internally async methods. but externally unable to know when the internal Task is complete.

So my conclusion is that async void is working as intended, and if you need feedback from the internal Task, then you need to use the async Task signature instead.

hopefully my rambling makes sense to anybody also looking for answers.

Edit: I made some example code and decompiled it to see what is actually going on.

static async void Test()
{
    await Task.Delay(5000);
}

static async Task TestAsync()
{
    await Task.Delay(5000);
}

Turns into (edit: I know that the body code is not here but in the statemachines, but the statemachines was basically identical, so I didn't bother adding them)

private static void Test()
{
    <Test>d__1 stateMachine = new <Test>d__1();
    stateMachine.<>t__builder = AsyncVoidMethodBuilder.Create();
    stateMachine.<>1__state = -1;
    AsyncVoidMethodBuilder <>t__builder = stateMachine.<>t__builder;
    <>t__builder.Start(ref stateMachine);
}
private static Task TestAsync()
{
    <TestAsync>d__2 stateMachine = new <TestAsync>d__2();
    stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
    stateMachine.<>1__state = -1;
    AsyncTaskMethodBuilder <>t__builder = stateMachine.<>t__builder;
    <>t__builder.Start(ref stateMachine);
    return stateMachine.<>t__builder.Task;
}

neither AsyncVoidMethodBuilder or AsyncTaskMethodBuilder actually have any code in the Start method that would hint of them to block, and would always run asynchronously after they are started.

meaning without the returning Task, there would be no way to check if it is complete.

as expected, it only starts the Task running async, and then it continues in the code. and the async Task, first it starts the Task, and then it returns it.

so I guess my answer would be to never use async void, if you need to know when the task is done, that is what async Task is for.

Redirecting from HTTP to HTTPS with PHP

You can always use

header('Location: https://www.domain.com/cart_save/');

to redirect to the save URL.

But I would recommend to do it by .htaccess and the Apache rewrite rules.

Enforcing the type of the indexed members of a Typescript object?

Building on @shabunc's answer, this would allow enforcing either the key or the value — or both — to be anything you want to enforce.

type IdentifierKeys = 'my.valid.key.1' | 'my.valid.key.2';
type IdentifierValues = 'my.valid.value.1' | 'my.valid.value.2';

let stuff = new Map<IdentifierKeys, IdentifierValues>();

Should also work using enum instead of a type definition.

How to handle ListView click in Android

On your list view, use setOnItemClickListener

How to select the last record from MySQL table using SQL syntax

User order by with desc order:

select * from t
order by id desc
limit 1

What is The Rule of Three?

Rule of three in C++ is a fundamental principle of the design and the development of three requirements that if there is clear definition in one of the following member function, then the programmer should define the other two members functions together. Namely the following three member functions are indispensable: destructor, copy constructor, copy assignment operator.

Copy constructor in C++ is a special constructor. It is used to build a new object, which is the new object equivalent to a copy of an existing object.

Copy assignment operator is a special assignment operator that is usually used to specify an existing object to others of the same type of object.

There are quick examples:

// default constructor
My_Class a;

// copy constructor
My_Class b(a);

// copy constructor
My_Class c = a;

// copy assignment operator
b = a;

Extract subset of key-value pairs from Python dictionary object?

solution

from operator import itemgetter
from typing import List, Dict, Union


def subdict(d: Union[Dict, List], columns: List[str]) -> Union[Dict, List[Dict]]:
    """Return a dict or list of dicts with subset of 
    columns from the d argument.
    """
    getter = itemgetter(*columns)

    if isinstance(d, list):
        result = []
        for subset in map(getter, d):
            record = dict(zip(columns, subset))
            result.append(record)
        return result
    elif isinstance(d, dict):
        return dict(zip(columns, getter(d)))

    raise ValueError('Unsupported type for `d`')

examples of use

# pure dict

d = dict(a=1, b=2, c=3)
print(subdict(d, ['a', 'c']))

>>> In [5]: {'a': 1, 'c': 3}
# list of dicts

d = [
    dict(a=1, b=2, c=3),
    dict(a=2, b=4, c=6),
    dict(a=4, b=8, c=12),
]

print(subdict(d, ['a', 'c']))

>>> In [5]: [{'a': 1, 'c': 3}, {'a': 2, 'c': 6}, {'a': 4, 'c': 12}]

How can I iterate over the elements in Hashmap?

HashMap<Integer,Player> hash = new HashMap<Integer,Player>();
Set keys = hash.keySet();   
Iterator itr = keys.iterator();

while(itr.hasNext()){
    Integer key = itr.next();
    Player objPlayer = (Player) hash.get(key);
    System.out.println("The player "+objPlayer.getName()+" has "+objPlayer.getScore()+" points");
}

You can use this code to print all scores in your format.

How do I make the first letter of a string uppercase in JavaScript?

If there's Lodash in your project, use upperFirst.

Get PostGIS version

PostGIS_Lib_Version(); - returns the version number of the PostGIS library.

http://postgis.refractions.net/docs/PostGIS_Lib_Version.html

Unable to copy ~/.ssh/id_rsa.pub

Have read the documentation you've linked. That's totally silly! xclip is just a clipboard. You'll find other ways to copy paste the key... (I'm sure)


If you aren't working from inside a graphical X session you need to pass the $DISPLAY environment var to the command. Run it like this:

DISPLAY=:0 xclip -sel clip < ~/.ssh/id_rsa.pub

Of course :0 depends on the display you are using. If you have a typical desktop machine it is likely that it is :0

How to connect to a docker container from outside the host (same network) [Windows]

I found that along with setting the -p port values, Docker for Windows uses vpnkit and inbound traffic for it was disabled by default on my host machine's firewall. After enabling the inbound TCP rules for vpnkit I was able to access my containers from other machines on the local network.

linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04

v4l support has been dropped in recent kernel versions (including the one shipped with Ubuntu 11.04).

EDIT: Your question is connected to a recent message that was sent to the OpenCV users group, which has instructions to compile OpenCV 2.2 in Ubuntu 11.04. Your approach is not ideal.

How do I tell Maven to use the latest version of a dependency?

If you want Maven should use the latest version of a dependency, then you can use Versions Maven Plugin and how to use this plugin, Tim has already given a good answer, follow his answer.

But as a developer, I will not recommend this type of practices. WHY?

answer to why is already given by Pascal Thivent in the comment of the question

I really don't recommend this practice (nor using version ranges) for the sake of build reproducibility. A build that starts to suddenly fail for an unknown reason is way more annoying than updating manually a version number.

I will recommend this type of practice:

<properties>
    <spring.version>3.1.2.RELEASE</spring.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

</dependencies>

it is easy to maintain and easy to debug. You can update your POM in no time.

How to clear PermGen space Error in tomcat

You have to allocate more space to the PermGenSpace of the tomcat JVM.

This can be done with the JVM argument : -XX:MaxPermSize=128m

By default, the PermGen space is 64M (and it contains all compiled classes, so if you have a lot of jar (classes) in your classpath, you may indeed fill this space).

On a side note, you can monitor the size of the PermGen space with JVisualVM and you can even inspect its content with YourKit Java Profiler

How to change mysql to mysqli?

(I realise this is old, but it still comes up...)

If you do replace mysql_* with mysqli_* then bear in mind that a whole load of mysqli_* functions need the database link to be passed.

E.g.:

mysql_query($query)

becomes

mysqli_query($link, $query)

I.e., lots of checking required.

Access maven properties defined in the pom

This can be done with standard java properties in combination with the maven-resource-plugin with enabled filtering on properties.

For more info see http://maven.apache.org/plugins/maven-resources-plugin/examples/filter.html

This will work for standard maven project as for plugin projects

Best method for reading newline delimited files and discarding the newlines?

I use this

def cleaned( aFile ):
    for line in aFile:
        yield line.strip()

Then I can do things like this.

lines = list( cleaned( open("file","r") ) )

Or, I can extend cleaned with extra functions to, for example, drop blank lines or skip comment lines or whatever.

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

How can I use a batch file to write to a text file?

@echo off

echo Type your text here.

:top

set /p boompanes=

pause

echo %boompanes%> practice.txt

hope this helps. you should change the string names(IDK what its called) and the file name

Get Unix timestamp with C++

#include <iostream>
#include <sys/time.h>

using namespace std;

int main ()
{
  unsigned long int sec= time(NULL);
  cout<<sec<<endl;
}

How to design RESTful search/filtering?

The best way to implement a RESTful search is to consider the search itself to be a resource. Then you can use the POST verb because you are creating a search. You do not have to literally create something in a database in order to use a POST.

For example:

Accept: application/json
Content-Type: application/json
POST http://example.com/people/searches
{
  "terms": {
    "ssn": "123456789"
  },
  "order": { ... },
  ...
}

You are creating a search from the user's standpoint. The implementation details of this are irrelevant. Some RESTful APIs may not even need persistence. That is an implementation detail.

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

I was trying to save a JSON object from a XHR request into a HTML5 data-* attribute. I tried many of above solutions with no success.

What I finally end up doing was replacing the single quote ' with it code &#39; using a regex after the stringify() method call the following way:

var productToString = JSON.stringify(productObject);
var quoteReplaced = productToString.replace(/'/g, "&#39;");
var anchor = '<a data-product=\'' + quoteReplaced + '\' href=\'#\'>' + productObject.name + '</a>';
// Here you can use the "anchor" variable to update your DOM element.

How do I run a VBScript in 32-bit mode on a 64-bit machine?

In the launcher script you can force it, it permits to keep the same script and same launcher for both architecture

:: For 32 bits architecture, this line is sufficent (32bits is the only cscript available)
set CSCRIPT="cscript.exe"
:: Detect windows 64bits and use the expected cscript (SysWOW64 contains 32bits executable)
if exist "C:\Windows\SysWOW64\cscript.exe" set CSCRIPT="C:\Windows\SysWOW64\cscript.exe"
%CSCRIPT% yourscript.vbs

Locate the nginx.conf file my nginx is actually using

Both nginx -t and nginx -V would print out the default nginx config file path.

$ nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

$ nginx -V
nginx version: nginx/1.11.1
built by gcc 4.9.2 (Debian 4.9.2-10)
built with OpenSSL 1.0.1k 8 Jan 2015
TLS SNI support enabled
configure arguments: --prefix=/etc/nginx --sbin-path=/usr/sbin/nginx --modules-path=/usr/lib/nginx/modules --conf-path=/etc/nginx/nginx.conf ...

If you want, you can get the config file by:

$ nginx -V 2>&1 | grep -o '\-\-conf-path=\(.*conf\)' | cut -d '=' -f2
/etc/nginx/nginx.conf

Even if you have loaded some other config file, they would still print out the default value.


ps aux would show you the current loaded nginx config file.

$ ps aux
USER       PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND
root        11  0.0  0.2  31720  2212 ?        Ss   Jul23   0:00 nginx: master process nginx -c /app/nginx.conf

So that you could actually get the config file by for example:

$ ps aux | grep "[c]onf" | awk '{print $(NF)}'
/app/nginx.conf

Disable back button in android

You can override the onBackPressed() method in your activity and remove the call to super class.

@Override
public void onBackPressed() {
  //remove call to the super class
  //super.onBackPressed();
}

MVC4 input field placeholder

Try this:

@Html.TextbBoxFor(x=>x.Email,new { @[email protected]}

If this possible or else what could be the way

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

In Drupal 7, you can modify the memory limit in the settings.php file located in your sites/default folder. Around line 260, you'll see this:

ini_set('memory_limit', '128M');

Even if your php.ini settings are high enough, you won't be able to consume more than 128 MB if this isn't set in your Drupal settings.php file.

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

Align labels in form next to input

I use something similar to this:

<div class="form-element">
  <label for="foo">Long Label</label>
  <input type="text" name="foo" id="foo" />
</div>

Style:

.form-element label {
    display: inline-block;
    width: 150px;
}

How to break out from foreach loop in javascript

Use a for loop instead of .forEach()

var myObj = [{"a": "1","b": null},{"a": "2","b": 5}]
var result = false

for(var call of myObj) {
    console.log(call)
    
    var a = call['a'], b = call['b']
     
    if(a == null || b == null) {
        result = false
        break
    }
}

Create listview in fragment android

The inflate() method takes three parameters:

  1. The id of a layout XML file (inside R.layout),
  2. A parent ViewGroup into which the fragment's View is to be inserted,

  3. A third boolean telling whether the fragment's View as inflated from the layout XML file should be inserted into the parent ViewGroup.

In this case we pass false because the View will be attached to the parent ViewGroup elsewhere, by some of the Android code we call (in other words, behind our backs). When you pass false as last parameter to inflate(), the parent ViewGroup is still used for layout calculations of the inflated View, so you cannot pass null as parent ViewGroup .

 View rootView = inflater.inflate(R.layout.fragment_photos, container, false);

So, You need to call rootView in here

ListView lv = (ListView)rootView.findViewById(R.id.lv_contact);

How to show PIL Image in ipython notebook

A cleaner Python3 version that use standard numpy, matplotlib and PIL. Merging the answer for opening from URL.

import matplotlib.pyplot as plt
from PIL import Image
import numpy as np

pil_im = Image.open('image.jpg')
## Uncomment to open from URL
#import requests
#r = requests.get('https://www.vegvesen.no/public/webkamera/kamera?id=131206')
#pil_im = Image.open(BytesIO(r.content))
im_array = np.asarray(pil_im)
plt.imshow(im_array)
plt.show()

No default constructor found; nested exception is java.lang.NoSuchMethodException with Spring MVC?

Spring cannot instantiate your TestController because its only constructor requires a parameter. You can add a no-arg constructor or you add @Autowired annotation to the constructor:

@Autowired
public TestController(KeeperClient testClient) {
    TestController.testClient = testClient;
}

In this case, you are explicitly telling Spring to search the application context for a KeeperClient bean and inject it when instantiating the TestControlller.

Converting a sentence string to a string array of words in Java

The easiest and best answer I can think of is to use the following method defined on the java string -

String[] split(String regex)

And just do "This is a sample sentence".split(" "). Because it takes a regex, you can do more complicated splits as well, which can include removing unwanted punctuation and other such characters.

Sleep function in Windows, using C

Use:

#include <windows.h>

Sleep(sometime_in_millisecs); // Note uppercase S

And here's a small example that compiles with MinGW and does what it says on the tin:

#include <windows.h>
#include <stdio.h>

int main() {
    printf( "starting to sleep...\n" );
    Sleep(3000); // Sleep three seconds
    printf("sleep ended\n");
}

Convert string to binary then back again using PHP

Yes, sure!

There...

$bin = decbin(ord($char));

... and back again.

$char = chr(bindec($bin));

Click events on Pie Charts in Chart.js

To successfully track click events and on what graph element the user clicked, I did the following in my .js file I set up the following variables:

vm.chartOptions = {
    onClick: function(event, array) {
        let element = this.getElementAtEvent(event);
        if (element.length > 0) {
            var series= element[0]._model.datasetLabel;
            var label = element[0]._model.label;
            var value = this.data.datasets[element[0]._datasetIndex].data[element[0]._index];
        }
    }
};
vm.graphSeries = ["Series 1", "Serries 2"];
vm.chartLabels = ["07:00", "08:00", "09:00", "10:00"];
vm.chartData = [ [ 20, 30, 25, 15 ], [ 5, 10, 100, 20 ] ];

Then in my .html file I setup the graph as follows:

<canvas id="releaseByHourBar" 
    class="chart chart-bar"
    chart-data="vm.graphData"
    chart-labels="vm.graphLabels" 
    chart-series="vm.graphSeries"
    chart-options="vm.chartOptions">
</canvas>

VB.Net: Dynamically Select Image from My.Resources

Found the solution:

UltraPictureBox1.Image = _
    My.Resources.ResourceManager.GetObject(object_name_as_string)

How to call C++ function from C?

I would do it in the following way:

(If working with MSVC, ignore the GCC compilation commands)

Suppose that I have a C++ class named AAA, defined in files aaa.h, aaa.cpp, and that the class AAA has a method named sayHi(const char *name), that I want to enable for C code.

The C++ code of class AAA - Pure C++, I don't modify it:

aaa.h

#ifndef AAA_H
#define AAA_H

class AAA {
    public:
        AAA();
        void sayHi(const char *name);
};

#endif

aaa.cpp

#include <iostream>

#include "aaa.h"

AAA::AAA() {
}

void AAA::sayHi(const char *name) {
    std::cout << "Hi " << name << std::endl;
}

Compiling this class as regularly done for C++. This code "does not know" that it is going to be used by C code. Using the command:

g++ -fpic -shared aaa.cpp -o libaaa.so

Now, also in C++, creating a C connector. Defining it in files aaa_c_connector.h, aaa_c_connector.cpp. This connector is going to define a C function, named AAA_sayHi(cosnt char *name), that will use an instance of AAA and will call its method:

aaa_c_connector.h

#ifndef AAA_C_CONNECTOR_H 
#define AAA_C_CONNECTOR_H 

#ifdef __cplusplus
extern "C" {
#endif

void AAA_sayHi(const char *name);

#ifdef __cplusplus
}
#endif


#endif

aaa_c_connector.cpp

#include <cstdlib>

#include "aaa_c_connector.h"
#include "aaa.h"

#ifdef __cplusplus
extern "C" {
#endif

// Inside this "extern C" block, I can implement functions in C++, which will externally 
//   appear as C functions (which means that the function IDs will be their names, unlike
//   the regular C++ behavior, which allows defining multiple functions with the same name
//   (overloading) and hence uses function signature hashing to enforce unique IDs),


static AAA *AAA_instance = NULL;

void lazyAAA() {
    if (AAA_instance == NULL) {
        AAA_instance = new AAA();
    }
}

void AAA_sayHi(const char *name) {
    lazyAAA();
    AAA_instance->sayHi(name);
}

#ifdef __cplusplus
}
#endif

Compiling it, again, using a regular C++ compilation command:

g++ -fpic -shared aaa_c_connector.cpp -L. -laaa -o libaaa_c_connector.so

Now I have a shared library (libaaa_c_connector.so), that implements the C function AAA_sayHi(const char *name). I can now create a C main file and compile it all together:

main.c

#include "aaa_c_connector.h"

int main() {
    AAA_sayHi("David");
    AAA_sayHi("James");

    return 0;
}

Compiling it using a C compilation command:

gcc main.c -L. -laaa_c_connector -o c_aaa

I will need to set LD_LIBRARY_PATH to contain $PWD, and if I run the executable ./c_aaa, I will get the output I expect:

Hi David
Hi James

EDIT:

On some linux distributions, -laaa and -lstdc++ may also be required for the last compilation command. Thanks to @AlaaM. for the attention

Clone() vs Copy constructor- which is recommended in java

Keep in mind that the copy constructor limits the class type to that of the copy constructor. Consider the example:

// Need to clone person, which is type Person
Person clone = new Person(person);

This doesn't work if person could be a subclass of Person (or if Person is an interface). This is the whole point of clone, is that it can can clone the proper type dynamically at runtime (assuming clone is properly implemented).

Person clone = (Person)person.clone();

or

Person clone = (Person)SomeCloneUtil.clone(person); // See Bozho's answer

Now person can be any type of Person assuming that clone is properly implemented.

How to detect a loop in a linked list?

The following may not be the best method--it is O(n^2). However, it should serve to get the job done (eventually).

count_of_elements_so_far = 0;
for (each element in linked list)
{
    search for current element in first <count_of_elements_so_far>
    if found, then you have a loop
    else,count_of_elements_so_far++;
}

Count number of occurrences for each unique value

Yes, you can use GROUP BY:

SELECT time,
       activities,
       COUNT(*)
FROM table
GROUP BY time, activities;

Determining Referer in PHP

We have only single option left after reading all the fake referrer problems: i.e. The page we desire to track as referrer should be kept in session, and as ajax called then checking in session if it has referrer page value and doing the action other wise no action.

While on the other hand as he request any different page then make the referrer session value to null.

Remember that session variable is set on desire page request only.

TortoiseGit-git did not exit cleanly (exit code 1)

I was heard that, one of the reasons is , the project is too large, so increasing the post buffer could solve the problem. so open the editSystemWideGitConfig, and add the following statements under [http] , postBuffer = 524288000. maybe work.

Using a Python subprocess call to invoke a Python script

The subprocess call is a very literal-minded system call. it can be used for any generic process...hence does not know what to do with a Python script automatically.

Try

call ('python somescript.py')

If that doesn't work, you might want to try an absolute path, and/or check permissions on your Python script...the typical fun stuff.

CSS hexadecimal RGBA?

If you can use LESS, there is a fade function.

@my-opaque-color: #a438ab;
@my-semitransparent-color: fade(@my-opaque-color, 50%);

background-color:linear-gradient(to right,@my-opaque-color, @my-semitransparent-color); 

// result: 
background-color: linear-gradient(to right, #a438ab, rgba(164, 56, 171, 0.5));

Converting a string to JSON object

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

link:-

http://api.jquery.com/jQuery.parseJSON/

how to fire event on file select

<input id="fusk" type="file" name="upload" style="display: none;"
    onChange=" document.getElementById('myForm').submit();"
>

Key Presses in Python

Install the pywin32 extensions. Then you can do the following:

import win32com.client as comclt
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Notepad") # select another application
wsh.SendKeys("a") # send the keys you want

Search for documentation of the WScript.Shell object (I believe installed by default in all Windows XP installations). You can start here, perhaps.

EDIT: Sending F11

import win32com.client as comctl
wsh = comctl.Dispatch("WScript.Shell")

# Google Chrome window title
wsh.AppActivate("icanhazip.com")
wsh.SendKeys("{F11}")

Making the iPhone vibrate

In Swift:

import AVFoundation
...
AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))

Implementation difference between Aggregation and Composition in Java

A simple Composition program

public class Person {
    private double salary;
    private String name;
    private Birthday bday;

    public Person(int y,int m,int d,String name){
        bday=new Birthday(y, m, d);
        this.name=name;
    }


    public double getSalary() {
        return salary;
    }

    public String getName() {
        return name;
    }

    public Birthday getBday() {
        return bday;
    }

    ///////////////////////////////inner class///////////////////////
    private class Birthday{
        int year,month,day;

        public Birthday(int y,int m,int d){
            year=y;
            month=m;
            day=d;
        }

        public String toString(){
           return String.format("%s-%s-%s", year,month,day);

        }
    }

    //////////////////////////////////////////////////////////////////

}
public class CompositionTst {

    public static void main(String[] args) {
        // TODO code application logic here
        Person person=new Person(2001, 11, 29, "Thilina");
        System.out.println("Name : "+person.getName());
        System.out.println("Birthday : "+person.getBday());

        //The below object cannot be created. A bithday cannot exixts without a Person 
        //Birthday bday=new Birthday(1988,11,10);

    }
}

Set Text property of asp:label in Javascript PROPER way

Asp.net codebehind runs on server first and then page is rendered to client (browser). Codebehind has no access to client side (javascript, html) because it lives on server only.

So, either use ajax and sent value of label to code behind. You can use PageMethods , or simply post the page to server where codebehind lives, so codebehind can know the updated value :)

APR based Apache Tomcat Native library was not found on the java.library.path?

I resolve this (On Eclipse IDE) by delete my old server and create the same again. This error is because you don't proper terminate Tomcat server and close Eclipse.

How to build a RESTful API?

Another framework which has not been mentioned so far is Laravel. It's great for building PHP apps in general but thanks to the great router it's really comfortable and simple to build rich APIs. It might not be that slim as Slim or Sliex but it gives you a solid structure.

See Aaron Kuzemchak - Simple API Development With Laravel on YouTube and

Laravel 4: A Start at a RESTful API on NetTuts+

Get current URL with jQuery?

In jstl we can access current url path using pageContext.request.contextPath, If you want to do a ajax call,

  url = "${pageContext.request.contextPath}" + "/controller/path"

Ex: in the page http://stackoverflow.com/questions/406192 this will give http://stackoverflow.com/controller/path

How to insert default values in SQL table?

To insert the default values you should omit them something like this :

Insert into Table (Field2) values(5)

All other fields will have null or their default values if it has defined.

np.mean() vs np.average() in Python NumPy?

In some version of numpy there is another imporant difference that you must be aware:

average do not take in account masks, so compute the average over the whole set of data.

mean takes in account masks, so compute the mean only over unmasked values.

g = [1,2,3,55,66,77]
f = np.ma.masked_greater(g,5)

np.average(f)
Out: 34.0

np.mean(f)
Out: 2.0

How to specify a local file within html using the file: scheme?

the "file://" url protocol can only be used to locate files in the file system of the local machine. since this html code is interpreted by a browser, the "local machine" is the machine that is running the browser.

if you are getting file not found errors, i suspect it is because the file is not found. however, it could also be a security limitation of the browser. some browsers will not let you reference a filesystem file from a non-filesystem html page. you could try using the file path from the command line on the machine running the browser to confirm that this is a browser limitation and not a legitimate missing file.

How can I delete a query string parameter in JavaScript?

This returns the URL w/o ANY GET Parameters:

var href = document.location.href;
var search = document.location.search;
var pos = href.indexOf( search );
if ( pos !== -1 ){
    href = href.slice( 0, pos );
    console.log( href );
}

curl: (60) SSL certificate problem: unable to get local issuer certificate

We ran into this error recently. Turns out it was related to the root cert not being installed in the CA store directory properly. I was using a curl command where I was specifying the CA dir directly. curl --cacert /etc/test/server.pem --capath /etc/test ... This command was failing every time with curl: (60) SSL certificate problem: unable to get local issuer certificate.

After using strace curl ..., it was determined that curl was looking for the root cert file with a name of 60ff2731.0, which is based on an openssl hash naming convetion. So I found this command to effectively import the root cert properly:

ln -s rootcert.pem `openssl x509 -hash -noout -in rootcert.pem`.0

which creates a softlink

60ff2731.0 -> rootcert.pem

curl, under the covers read the server.pem cert, determined the name of the root cert file (rootcert.pem), converted it to its hash name, then did an OS file lookup, but could not find it.

So, the takeaway is, use strace when running curl when the curl error is obscure (was a tremendous help), and then be sure to properly install the root cert using the openssl naming convention.

How SQL query result insert in temp table?

In MySQL:

create table temp as select * from original_table

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

Refer the Q/A for logging the request and response for the rest template by enabling the multiple reads on the HttpInputStream

Why my custom ClientHttpRequestInterceptor with empty response

Getting number of days in a month

  • int days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);


if you want to find days in this year and present month then this is best

How to create relationships in MySQL

Here are a couple of resources that will help get started: http://www.anchor.com.au/hosting/support/CreatingAQuickMySQLRelationalDatabase and http://code.tutsplus.com/articles/sql-for-beginners-part-3-database-relationships--net-8561

Also as others said, use a GUI - try downloading and installing Xampp (or Wamp) which run server-software (Apache and mySQL) on your computer. Then when you navigate to //localhost in a browser, select PHPMyAdmin to start working with a mySQL database visually. As mentioned above, used innoDB to allow you to make relationships as you requested. Makes it heaps easier to see what you're doing with the database tables. Just remember to STOP Apache and mySQL services when finished - these can open up ports which can expose you to hacking/malicious threats.

Difference between numpy dot() and Python 3.5+ matrix multiplication @

Here is a comparison with np.einsum to show how the indices are projected

np.allclose(np.einsum('ijk,ijk->ijk', a,b), a*b)        # True 
np.allclose(np.einsum('ijk,ikl->ijl', a,b), a@b)        # True
np.allclose(np.einsum('ijk,lkm->ijlm',a,b), a.dot(b))   # True

Cross-Origin Request Blocked

You have to placed this code in application.rb

config.action_dispatch.default_headers = {
        'Access-Control-Allow-Origin' => '*',
        'Access-Control-Request-Method' => %w{GET POST OPTIONS}.join(",")
}

Given a view, how do I get its viewController?

Alas, this is impossible unless you subclass the view and provide it with an instance property or alike which stores the view controller reference inside it once the view is added to the scene...

In most cases - it is very easy to work around the original problem of this post as most view controllers are well-known entities to the programmer who was responsible for adding any subviews to the ViewController's View ;-) Which is why I guess that Apple never bothered to add that property.

Google Chrome display JSON AJAX response as tree and not as a plain text

I've found the answer:

You MUST encode your json like this: {"c":21001,"m":"p"} but not {c:21001,m:"p"} or {'c':21001,'m':'p'}

Thus, the key of a dict must be wrapped in double quotes:", then chrome will preview it as json rather than plain text.

How can I enter latitude and longitude in Google Maps?

It's actually fairly easy, just enter it as a latitude,longitude pair, ie 46.38S,115.36E (which is in the middle of the ocean). You'll want to convert it to decimal though (divide the minutes portion by 60 and add it to the degrees [I've done that with your example]).

How to convert php array to utf8?

Due to this article is a good SEO site, so I suggest to use build-in function "mb_convert_variables" to solve this problem. It works with simple syntax.

mb_convert_variables('utf-8', 'original encode', array/object)

How would I extract a single file (or changes to a file) from a git stash?

$ git checkout stash@{0} -- <filename>

Notes:

  1. Make sure you put space after the "--" and the file name parameter

  2. Replace zero(0) with your specific stash number. To get stash list, use:

    git stash list
    

Based on Jakub Narebski's answer -- Shorter version

How to create a shortcut using PowerShell

Beginning PowerShell 5.0 New-Item, Remove-Item, and Get-ChildItem have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.

New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"

Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.

Anyway if you want to create a Run As Administrator shortcut using Powershell you can use

$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)

If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.

Concatenating multiple text files into a single file in Bash

all of that is nasty....

ls | grep *.txt | while read file; do cat $file >> ./output.txt; done;

easy stuff.

z-index issue with twitter bootstrap dropdown menu

This fixed it for me:

.navbar-wrapper {
  z-index: 11;
}

Center a position:fixed element

To fix the position use this :

div {
    position: fixed;
    left: 68%;
    transform: translateX(-8%);
}

WCF named pipe minimal example

I created this simple example from different search results on the internet.

public static ServiceHost CreateServiceHost(Type serviceInterface, Type implementation)
{
  //Create base address
  string baseAddress = "net.pipe://localhost/MyService";

  ServiceHost serviceHost = new ServiceHost(implementation, new Uri(baseAddress));

  //Net named pipe
  NetNamedPipeBinding binding = new NetNamedPipeBinding { MaxReceivedMessageSize = 2147483647 };
  serviceHost.AddServiceEndpoint(serviceInterface, binding, baseAddress);

  //MEX - Meta data exchange
  ServiceMetadataBehavior behavior = new ServiceMetadataBehavior();
  serviceHost.Description.Behaviors.Add(behavior);
  serviceHost.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexNamedPipeBinding(), baseAddress + "/mex/");

  return serviceHost;
}

Using the above URI I can add a reference in my client to the web service.

Storing a file in a database as opposed to the file system?

Have a look at this answer:

Storing Images in DB - Yea or Nay?

Essentially, the space and performance hit can be quite big, depending on the number of users. Also, keep in mind that Web servers are cheap and you can easily add more to balance the load, whereas the database is the most expensive and hardest to scale part of a web architecture usually.

There are some opposite examples (e.g., Microsoft Sharepoint), but usually, storing files in the database is not a good idea.

Unless possibly you write desktop apps and/or know roughly how many users you will ever have, but on something as random and unexpectable like a public web site, you may pay a high price for storing files in the database.

Why doesn't the Scanner class have a nextChar method?

According to the javadoc a Scanner does not seem to be intended for reading single characters. You attach a Scanner to an InputStream (or something else) and it parses the input for you. It also can strip of unwanted characters. So you can read numbers, lines, etc. easily. When you need only the characters from your input, use a InputStreamReader for example.

Javascript/jQuery: Set Values (Selection) in a multiple Select

this is error in some answers for replace |

var mystring = "this|is|a|test";
mystring = mystring.replace(/|/g, "");
alert(mystring);

this correction is correct but the | In the end it should look like this \|

var mystring = "this|is|a|test";
mystring = mystring.replace(/\|/g, "");
alert(mystring);

How to use find command to find all files with extensions from list?

find /path/to/  \( -iname '*.gif' -o -iname '*.jpg' \) -print0

will work. There might be a more elegant way.

How can I produce an effect similar to the iOS 7 blur view?

You can find your solution from apple's DEMO in this page: WWDC 2013 , find out and download UIImageEffects sample code.

Then with @Jeremy Fox's code. I changed it to

- (UIImage*)getDarkBlurredImageWithTargetView:(UIView *)targetView
{
    CGSize size = targetView.frame.size;

    UIGraphicsBeginImageContext(size);
    CGContextRef c = UIGraphicsGetCurrentContext();
    CGContextTranslateCTM(c, 0, 0);
    [targetView.layer renderInContext:c]; // view is the view you are grabbing the screen shot of. The view that is to be blurred.
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return [image applyDarkEffect];
}

Hope this will help you.

How to Install Windows Phone 8 SDK on Windows 7

You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.

Use of the MANIFEST.MF file in Java

The content of the Manifest file in a JAR file created with version 1.0 of the Java Development Kit is the following.

Manifest-Version: 1.0

All the entries are as name-value pairs. The name of a header is separated from its value by a colon. The default manifest shows that it conforms to version 1.0 of the manifest specification. The manifest can also contain information about the other files that are packaged in the archive. Exactly what file information is recorded in the manifest will depend on the intended use for the JAR file. The default manifest file makes no assumptions about what information it should record about other files, so its single line contains data only about itself. Special-Purpose Manifest Headers

Depending on the intended role of the JAR file, the default manifest may have to be modified. If the JAR file is created only for the purpose of archival, then the MANIFEST.MF file is of no purpose. Most uses of JAR files go beyond simple archiving and compression and require special information to be in the manifest file. Summarized below are brief descriptions of the headers that are required for some special-purpose JAR-file functions

Applications Bundled as JAR Files: If an application is bundled in a JAR file, the Java Virtual Machine needs to be told what the entry point to the application is. An entry point is any class with a public static void main(String[] args) method. This information is provided in the Main-Class header, which has the general form:

Main-Class: classname

The value classname is to be replaced with the application's entry point.

Download Extensions: Download extensions are JAR files that are referenced by the manifest files of other JAR files. In a typical situation, an applet will be bundled in a JAR file whose manifest references a JAR file (or several JAR files) that will serve as an extension for the purposes of that applet. Extensions may reference each other in the same way. Download extensions are specified in the Class-Path header field in the manifest file of an applet, application, or another extension. A Class-Path header might look like this, for example:

Class-Path: servlet.jar infobus.jar acme/beans.jar

With this header, the classes in the files servlet.jar, infobus.jar, and acme/beans.jar will serve as extensions for purposes of the applet or application. The URLs in the Class-Path header are given relative to the URL of the JAR file of the applet or application.

Package Sealing: A package within a JAR file can be optionally sealed, which means that all classes defined in that package must be archived in the same JAR file. A package might be sealed to ensure version consistency among the classes in your software or as a security measure. To seal a package, a Name header needs to be added for the package, followed by a Sealed header, similar to this:

Name: myCompany/myPackage/
Sealed: true

The Name header's value is the package's relative pathname. Note that it ends with a '/' to distinguish it from a filename. Any headers following a Name header, without any intervening blank lines, apply to the file or package specified in the Name header. In the above example, because the Sealed header occurs after the Name: myCompany/myPackage header, with no blank lines between, the Sealed header will be interpreted as applying (only) to the package myCompany/myPackage.

Package Versioning: The Package Versioning specification defines several manifest headers to hold versioning information. One set of such headers can be assigned to each package. The versioning headers should appear directly beneath the Name header for the package. This example shows all the versioning headers:

Name: java/util/
Specification-Title: "Java Utility Classes" 
Specification-Version: "1.2"
Specification-Vendor: "Sun Microsystems, Inc.".
Implementation-Title: "java.util" 
Implementation-Version: "build57"
Implementation-Vendor: "Sun Microsystems, Inc."

MySQL, create a simple function

Try to change CREATE FUNCTION F_TEST(PID INT) RETURNS VARCHAR this portion to CREATE FUNCTION F_TEST(PID INT) RETURNS TEXT

and change the following line too.

DECLARE NAME_FOUND TEXT DEFAULT "";

It should work.

Iterate a list with indexes in Python

>>> a = [3,4,5,6]
>>> for i, val in enumerate(a):
...     print i, val
...
0 3
1 4
2 5
3 6
>>>

Use querystring variables in MVC controller

public ActionResult SomeAction(string start, string end)

The framework will map the query string parameters to the method parameters.

Javascript: The prettiest way to compare one value against multiple values

Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):

(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)

if (~[foo, bar].indexOf(foobar)) {
    // pretty
}

What's an object file in C?

An object file is the real output from the compilation phase. It's mostly machine code, but has info that allows a linker to see what symbols are in it as well as symbols it requires in order to work. (For reference, "symbols" are basically names of global objects, functions, etc.)

A linker takes all these object files and combines them to form one executable (assuming that it can, ie: that there aren't any duplicate or undefined symbols). A lot of compilers will do this for you (read: they run the linker on their own) if you don't tell them to "just compile" using command-line options. (-c is a common "just compile; don't link" option.)

Keylistener in Javascript

JSFIDDLE DEMO

If you don't want the event to be continuous (if you want the user to have to release the key each time), change onkeydown to onkeyup

window.onkeydown = function (e) {
    var code = e.keyCode ? e.keyCode : e.which;
    if (code === 38) { //up key
        alert('up');
    } else if (code === 40) { //down key
        alert('down');
    }
};

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

VBA Excel 2-Dimensional Arrays

You need ReDim:

m = 5
n = 8
Dim my_array()
ReDim my_array(1 To m, 1 To n)
For i = 1 To m
  For j = 1 To n
    my_array(i, j) = i * j
  Next
Next

For i = 1 To m
  For j = 1 To n
    Cells(i, j) = my_array(i, j)
  Next
Next

As others have pointed out, your actual problem would be better solved with ranges. You could try something like this:

Dim r1 As Range
Dim r2 As Range
Dim ws1 As Worksheet
Dim ws2 As Worksheet

Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
totalRow = ws1.Range("A1").End(xlDown).Row
totalCol = ws1.Range("A1").End(xlToRight).Column

Set r1 = ws1.Range(ws1.Cells(1, 1), ws1.Cells(totalRow, totalCol))
Set r2 = ws2.Range(ws2.Cells(1, 1), ws2.Cells(totalRow, totalCol))
r2.Value = r1.Value

Convert list into a pandas data frame

You need convert list to numpy array and then reshape:

df = pd.DataFrame(np.array(my_list).reshape(3,3), columns = list("abc"))
print (df)
   a  b  c
0  1  2  3
1  4  5  6
2  7  8  9

C# - Create SQL Server table programmatically

Try this:

protected void Button1_Click(object sender, EventArgs e)
{
    SqlConnection cn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=|DataDirectory|\\Database.mdf;Integrated Security=True");
    try
    {
        cn.Open();
        SqlCommand cmd = new SqlCommand("create table Employee (empno int,empname varchar(50),salary money);", cn);
        cmd.ExecuteNonQuery();
        lblAlert.Text = "SucessFully Connected";
        cn.Close();
    }
    catch (Exception eq)
    {
        lblAlert.Text = eq.ToString();
    }
}

ASP.NET Web Site or ASP.NET Web Application?

In Web Application Projects, Visual Studio needs additional .designer files for pages and user controls. Web Site Projects do not require this overhead. The markup itself is interpreted as the design.

Android Activity as a dialog

Some times you can get the Exception which is given below

Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

So for resolving you can use simple solution

add theme of you activity in manifest as dialog for appCompact.

android:theme="@style/Theme.AppCompat.Dialog"

It can be helpful for somebody.

Twitter bootstrap hide element on small devices

<div class="small hidden-xs">
    Some Content Here
</div>

This also works for elements not necessarily used in a grid /small column. When it is rendered on larger screens the font-size will be smaller than your default text font-size.

This answer satisfies the question in the OP title (which is how I found this Q/A).

CSS rule to apply only if element has BOTH classes

Below applies to all tags with the following two classes

.abc.xyz {  
  width: 200px !important;
}

applies to div tags with the following two classes

div.abc.xyz {  
  width: 200px !important;
}

If you wanted to modify this using jQuery

$(document).ready(function() {
  $("div.abc.xyz").width("200px");
});

HashSet vs LinkedHashSet

LinkedHashSet's constructors invoke the following base class constructor:

HashSet(int initialCapacity, float loadFactor, boolean dummy) {
  map = new LinkedHashMap<E, Object>(initialCapacity, loadFactor);
}

As you can see, the internal map is a LinkedHashMap. If you look inside LinkedHashMap, you'll discover the following field:

private transient Entry<K, V> header;

This is the linked list in question.

How to move up a directory with Terminal in OS X

Let's make it even more simple. Type the below after the $ sign to go up one directory:

../

Execution time of C program

ANSI C only specifies second precision time functions. However, if you are running in a POSIX environment you can use the gettimeofday() function that provides microseconds resolution of time passed since the UNIX Epoch.

As a side note, I wouldn't recommend using clock() since it is badly implemented on many(if not all?) systems and not accurate, besides the fact that it only refers to how long your program has spent on the CPU and not the total lifetime of the program, which according to your question is what I assume you would like to measure.

jQuery click event not working after adding class

on document ready event there is no a tag with class tabclick. so you have to bind click event dynamically when you are adding tabclick class. please this code:

$("a.applicationdata").click(function() {
    var appid = $(this).attr("id");

   $('#gentab a').addClass("tabclick")
    .click(function() {
          var liId = $(this).parent("li").attr("id");
         alert(liId);        
      });


 $('#gentab a').attr('href', '#datacollector');

});

Windows equivalent to UNIX pwd

This prints it in the console:

echo %cd%

or paste this command in CMD, then you'll have pwd:

(echo @echo off
echo echo ^%cd^%) > C:\WINDOWS\pwd.bat

Compare 2 arrays which returns difference

use underscore as :

_.difference(array1,array2)

How to SHA1 hash a string in Android?

final MessageDigest digest = MessageDigest.getInstance("SHA-1");
result = digest.digest(stringToHash.getBytes("UTF-8"));

// Another way to construct HEX, my previous post was only the method like your solution
StringBuilder sb = new StringBuilder();

for (byte b : result) // This is your byte[] result..
{
    sb.append(String.format("%02X", b));
}

String messageDigest = sb.toString();

Form Submit Execute JavaScript Best Practice?

Use the onsubmit event to execute JavaScript code when the form is submitted. You can then return false or call the passed event's preventDefault method to disable the form submission.

For example:

<script>
function doSomething() {
    alert('Form submitted!');
    return false;
}
</script>

<form onsubmit="return doSomething();" class="my-form">
    <input type="submit" value="Submit">
</form>

This works, but it's best not to litter your HTML with JavaScript, just as you shouldn't write lots of inline CSS rules. Many Javascript frameworks facilitate this separation of concerns. In jQuery you bind an event using JavaScript code like so:

<script>
$('.my-form').on('submit', function () {
    alert('Form submitted!');
    return false;
});
</script>

<form class="my-form">
    <input type="submit" value="Submit">
</form>

Calculate distance in meters when you know longitude and latitude in java

You can use the Java Geodesy Library for GPS, it uses the Vincenty's formulae which takes account of the earths surface curvature.

Implementation goes like this:

import org.gavaghan.geodesy.*;

...

GeodeticCalculator geoCalc = new GeodeticCalculator();

Ellipsoid reference = Ellipsoid.WGS84;  

GlobalPosition pointA = new GlobalPosition(latitude, longitude, 0.0); // Point A

GlobalPosition userPos = new GlobalPosition(userLat, userLon, 0.0); // Point B

double distance = geoCalc.calculateGeodeticCurve(reference, userPos, pointA).getEllipsoidalDistance(); // Distance between Point A and Point B

The resulting distance is in meters.

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

In April 2017 a patch was merged into Safari, so it aligned with the other browsers. This was released with Safari 11.

https://bugs.webkit.org/show_bug.cgi?id=157010

Convert serial.read() into a useable string using Arduino?

This would be way easier:

char data [21];
int number_of_bytes_received;

if(Serial.available() > 0)
{
    number_of_bytes_received = Serial.readBytesUntil (13,data,20); // read bytes (max. 20) from buffer, untill <CR> (13). store bytes in data. count the bytes recieved.
    data[number_of_bytes_received] = 0; // add a 0 terminator to the char array
} 

bool result = strcmp (data, "whatever");
// strcmp returns 0; if inputs match.
// http://en.cppreference.com/w/c/string/byte/strcmp


if (result == 0)
{
   Serial.println("data matches whatever");
} 
else 
{
   Serial.println("data does not match whatever");
}

Python Dictionary Comprehension

You can use the dict.fromkeys class method ...

>>> dict.fromkeys(range(5), True)
{0: True, 1: True, 2: True, 3: True, 4: True}

This is the fastest way to create a dictionary where all the keys map to the same value.

But do not use this with mutable objects:

d = dict.fromkeys(range(5), [])
# {0: [], 1: [], 2: [], 3: [], 4: []}
d[1].append(2)
# {0: [2], 1: [2], 2: [2], 3: [2], 4: [2]} !!!

If you don't actually need to initialize all the keys, a defaultdict might be useful as well:

from collections import defaultdict
d = defaultdict(True)

To answer the second part, a dict-comprehension is just what you need:

{k: k for k in range(10)}

You probably shouldn't do this but you could also create a subclass of dict which works somewhat like a defaultdict if you override __missing__:

>>> class KeyDict(dict):
...    def __missing__(self, key):
...       #self[key] = key  # Maybe add this also?
...       return key
... 
>>> d = KeyDict()
>>> d[1]
1
>>> d[2]
2
>>> d[3]
3
>>> print(d)
{}

How to create separate AngularJS controller files?

For brevity, here's an ES2015 sample that doesn't rely on global variables

// controllers/example-controller.js

export const ExampleControllerName = "ExampleController"
export const ExampleController = ($scope) => {
  // something... 
}

// controllers/another-controller.js

export const AnotherControllerName = "AnotherController"
export const AnotherController = ($scope) => {
  // functionality... 
}

// app.js

import angular from "angular";

import {
  ExampleControllerName,
  ExampleController
} = "./controllers/example-controller";

import {
  AnotherControllerName,
  AnotherController
} = "./controllers/another-controller";

angular.module("myApp", [/* deps */])
  .controller(ExampleControllerName, ExampleController)
  .controller(AnotherControllerName, AnotherController)

Installing Bower on Ubuntu

sudo apt-get install nodejs

installs nodejs

sudo apt-get install npm

installs npm

sudo npm install bower -g

installs bower via npm

Why there is this "clear" class before footer?

Most likely, as mentioned by others, it is a class carrying the css values:

.clear{clear: both;} 

in order to prevent any more page elements from extending into the footer element. It is a quick and easy way of making sure that pages with columns of varying heights don't cause the footer to render oddly, by possibly setting its top position at the end of a shorter column.

In many cases it is not necessary, but if you are using best-practice standards it is a good idea to use, if you are floating page elements left and right. It functions with page elements similar to the way a horizontal rule works with text, to ensure proper and complete sepperation.

PHP - iterate on string characters

Hmm... There's no need to complicate things. The basics work great always.

    $string = 'abcdef';
    $len = strlen( $string );
    $x = 0;

Forward Direction:

while ( $len > $x ) echo $string[ $x++ ];

Outputs: abcdef

Reverse Direction:

while ( $len ) echo $string[ --$len ];

Outputs: fedcba

How can I redirect a php page to another php page?

<?php
   header("Location: your url");
   exit;
?>

Add URL link in CSS Background Image?

Try wrapping the spans in an anchor tag and apply the background image to that.

HTML:

<div class="header">
    <a href="/">
        <span class="header-title">My gray sea design</span><br />
        <span class="header-title-two">A beautiful design</span>
    </a>
</div>

CSS:

.header {
    border-bottom:1px solid #eaeaea;
}

.header a {
    display: block;
    background-image: url("./images/embouchure.jpg");
    background-repeat: no-repeat;
    height:160px;
    padding-left:280px;
    padding-top:50px;
    width:470px;
    color: #eaeaea;
}

Parse rfc3339 date strings in Python?

You can use dateutil.parser.parse (install with python -m pip install python-dateutil) to parse strings into datetime objects.

dateutil.parser.parse will attempt to guess the format of your string, if you know the exact format in advance then you can use datetime.strptime which you supply a format string to (see Brent Washburne's answer).

from dateutil.parser import parse

a = "2012-10-09T19:00:55Z"

b = parse(a)

print(b.weekday())
# 1 (equal to a Tuesday)

How to replace local branch with remote branch entirely in Git?

git reset --hard
git clean -fd

This worked for me - clean showed all the files it deleted too. If it tells you you'll lose changes, you need to stash.

MySQL query String contains

You probably are looking for find_in_set function:

Where find_in_set($needle,'column') > 0

This function acts like in_array function in PHP

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

How to search a string in multiple files and return the names of files in Powershell?

To keep the complete file details in resulting array you could use a slight modification of the answer posted by vikas368 (which didn't seem to work well with the ISE autocomplete):

Get-ChildItem -Recurse | Where-Object { $_ | Select-String -Pattern "dummy" }

or in short:

ls -r | ?{ $_ | Select-String -Pattern "dummy" }

How do I implement Toastr JS?

This is a simple way to do it!

<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/css/toastr.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/2.0.1/js/toastr.js"></script>
<script>
function notificationme(){
toastr.options = {
            "closeButton": false,
            "debug": false,
            "newestOnTop": false,
            "progressBar": true,
            "preventDuplicates": true,
            "onclick": null,
            "showDuration": "100",
            "hideDuration": "1000",
            "timeOut": "5000",
            "extendedTimeOut": "1000",
            "showEasing": "swing",
            "hideEasing": "linear",
            "showMethod": "show",
            "hideMethod": "hide"
        };
toastr.info('MY MESSAGE!');
}
</script>

How to unmerge a Git merge?

If you haven't committed the merge, then use:

git merge --abort

Parsing date string in Go

As answered but to save typing out "2006-01-02T15:04:05.000Z" for the layout, you could use the package's constant RFC3339.

str := "2014-11-12T11:45:26.371Z"
t, err := time.Parse(time.RFC3339, str)

if err != nil {
    fmt.Println(err)
}
fmt.Println(t)

https://play.golang.org/p/Dgu2ZvHwTh

Reloading submodules in IPython

IPython comes with some automatic reloading magic:

%load_ext autoreload
%autoreload 2

It will reload all changed modules every time before executing a new line. The way this works is slightly different than dreload. Some caveats apply, type %autoreload? to see what can go wrong.


If you want to always enable this settings, modify your IPython configuration file ~/.ipython/profile_default/ipython_config.py[1] and appending:

c.InteractiveShellApp.extensions = ['autoreload']     
c.InteractiveShellApp.exec_lines = ['%autoreload 2']

Credit to @Kos via a comment below.

[1] If you don't have the file ~/.ipython/profile_default/ipython_config.py, you need to call ipython profile create first. Or the file may be located at $IPYTHONDIR.

Uncaught TypeError: Cannot set property 'onclick' of null

So I was having a similar issue and I managed to solve it by putting the script tag with my JS file after the closing body tag.

I assume it's because it makes sure there's something to reference, but I am not entirely sure.

Select values from XML field in SQL Server 2008

MSSQL uses regular XPath rules as follows:

  • nodename Selects all nodes with the name "nodename"
  • / Selects from the root node
  • // Selects nodes in the document from the current node that match the selection no matter where they are
  • . Selects the current node
  • .. Selects the parent of the current node
  • @ Selects attributes

W3Schools

What is the <leader> in a .vimrc file?

In my system its the \ key. it's used for commands so that you can combine it with other chars.

How to run code after some delay in Flutter?

You can do it in two ways 1 is Future.delayed and 2 is Timer

Using Timer

Timer is a class that represents a count-down timer that is configured to trigger an action once end of time is reached, and it can fire once or repeatedly.

Make sure to import dart:async package to start of program to use Timer

Timer(Duration(seconds: 5), () {
  print(" This line is execute after 5 seconds");
});

Using Future.delayed

Future.delayed is creates a future that runs its computation after a delay.

Make sure to import "dart:async"; package to start of program to use Future.delayed

Future.delayed(Duration(seconds: 5), () {
   print(" This line is execute after 5 seconds");
});

Shortcut for creating single item list in C#

A different answer to my earlier one, based on exposure to the Google Java Collections:

public static class Lists
{
    public static List<T> Of<T>(T item)
    {
        return new List<T> { item };
    }
}

Then:

List<string> x = Lists.Of("Hello");

I advise checking out the GJC - it's got lots of interesting stuff in. (Personally I'd ignore the "alpha" tag - it's only the open source version which is "alpha" and it's based on a very stable and heavily used internal API.)

How can I use an ES6 import in Node.js?

Solution

https://www.npmjs.com/package/babel-register

// This is to allow ES6 export syntax
// to be properly read and processed by node.js application
require('babel-register')({
  presets: [
    'env',
  ],
});

// After that, any line you add below that has typical ES6 export syntax
// will work just fine

const utils = require('../../utils.js');
const availableMixins = require('../../../src/lib/mixins/index.js');

Below is definition of file *mixins/index.js

export { default as FormValidationMixin } from './form-validation'; // eslint-disable-line import/prefer-default-export

That worked just fine inside my Node.js CLI application.

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

Moq cannot mock non-virtual methods and sealed classes. While running a test using mock object, MOQ actually creates an in-memory proxy type which inherits from your "XmlCupboardAccess" and overrides the behaviors that you have set up in the "SetUp" method. And as you know in C#, you can override something only if it is marked as virtual which isn't the case with Java. Java assumes every non-static method to be virtual by default.

Another thing I believe you should consider is introducing an interface for your "CupboardAccess" and start mocking the interface instead. It would help you decouple your code and have benefits in the longer run.

Lastly, there are frameworks like : TypeMock and JustMock which work directly with the IL and hence can mock non-virtual methods. Both however, are commercial products.

Return the characters after Nth character in a string

If your numbers are always 4 digits long:

=RIGHT(A1,LEN(A1)-5) //'0001 Baseball' returns Baseball

If the numbers are variable (i.e. could be more or less than 4 digits) then:

=RIGHT(A1,LEN(A1)-FIND(" ",A1,1)) //'123456 Baseball’ returns Baseball

Calculate percentage saved between two numbers?

This is function with inverted option

It will return:

  • 'change' - string that you can use for css class in your template
  • 'result' - plain result
  • 'formatted' - formatted result

function getPercentageChange( $oldNumber , $newNumber , $format = true , $invert = false ){

    $value      = $newNumber - $oldNumber;

    $change     = '';
    $sign       = '';

    $result     = 0.00;

    if ( $invert ) {
         if ( $value > 0 ) {
        //  going UP
            $change             = 'up';
            $sign               = '+';
            if ( $oldNumber > 0 ) {
                $result         = ($newNumber / $oldNumber) * 100;
            } else {
                $result     = 100.00;
            }

        }elseif ( $value < 0 ) {        
        //  going DOWN
            $change             = 'down';
            //$value                = abs($value);
            $result             = ($oldNumber / $newNumber) * 100;
            $result             = abs($result);
            $sign               = '-';

        }else {
        //  no changes
        }

    }else{

        if ( $newNumber > $oldNumber ) {

            //  increase
            $change             = 'up';

            if ( $oldNumber > 0 ) {

                $result = ( ( $newNumber / $oldNumber ) - 1 )* 100;

            }else{
                $result = 100.00;
            }

            $sign               = '+';

        }elseif ( $oldNumber > $newNumber ) {

            //  decrease
            $change             = 'down';

            if ( $oldNumber > 0 ) {

                $result = ( ( $newNumber / $oldNumber ) - 1 )* 100;

            } else {
                $result = 100.00;
            }

            $sign               = '-';

        }else{

            //  no change

        }

        $result = abs($result);

    }

    $result_formatted       = number_format($result, 2);

    if ( $invert ) {
        if ( $change == 'up' ) {
            $change = 'down';
        }elseif ( $change == 'down' ) {
            $change = 'up';
        }else{
            //
        }

        if ( $sign == '+' ) {
            $sign = '-';
        }elseif ( $sign == '-' ) {
            $sign = '+';
        }else{
            //
        }
    }
    if ( $format ) {
        $formatted          = '<span class="going '.$change.'">'.$sign.''.$result_formatted.' %</span>';
    } else{
        $formatted          = $result_formatted;
    }

    return array( 'change' => $change , 'result' => $result , 'formatted' => $formatted );
}

Android load from URL to Bitmap

Please try this following steps.

1) Create AsyncTask in class or adapter(if you want to change the list item image).

public class AsyncTaskLoadImage extends AsyncTask<String, String, Bitmap> {
        private final static String TAG = "AsyncTaskLoadImage";
        private ImageView imageView;

        public AsyncTaskLoadImage(ImageView imageView) {
            this.imageView = imageView;
        }

        @Override
        protected Bitmap doInBackground(String... params) {
            Bitmap bitmap = null;
            try {
                URL url = new URL(params[0]);
                bitmap = BitmapFactory.decodeStream((InputStream) url.getContent());
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return bitmap;
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            try {
                int width, height;
                height = bitmap.getHeight();
                width = bitmap.getWidth();

                Bitmap bmpGrayscale = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                Canvas c = new Canvas(bmpGrayscale);
                Paint paint = new Paint();
                ColorMatrix cm = new ColorMatrix();
                cm.setSaturation(0);
                ColorMatrixColorFilter f = new ColorMatrixColorFilter(cm);
                paint.setColorFilter(f);
                c.drawBitmap(bitmap, 0, 0, paint);
                imageView.setImageBitmap(bmpGrayscale);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

2) Call the AsyncTask from your activity, fragment or adapter(inside onBindViewHolder).

2.a) For adapter:

    String src = current.getProductImage();
    new AsyncTaskLoadImage(holder.icon).execute(src);

2.b) For activity and fragment:

**Activity:**
  ImageView imagview= (ImageView) findViewById(R.Id.imageview);
  String src = (your image string);
  new AsyncTaskLoadImage(imagview).execute(src);

**Fragment:**
  ImageView imagview= (ImageView)view.findViewById(R.Id.imageview);
  String src = (your image string);
  new AsyncTaskLoadImage(imagview).execute(src);

3) Kindly run the app and check the image.

Happy coding....:)

Get battery level and state in Android

Since SDK 21 LOLLIPOP it is possible to use the following to get current battery level as a percentage:

BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
int batLevel = bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

Read BatteryManager  |  Android Developers - BATTERY_PROPERTY_CAPACITY

HTTP Status 405 - HTTP method POST is not supported by this URL java servlet

It's because you're calling doGet() without actually implementing doGet(). It's the default implementation of doGet() that throws the error saying the method is not supported.

ASP.NET Core - Swashbuckle not creating swagger.json file

I don't know if this is useful for someone, but in my case the problem was that the name had different casing.

V1 in the service configuration - V capital letter
v1 in Settings -- v lower case

The only thing I did was to use the same casing and it worked.

version name with capital V

Android studio takes too much memory

You can speed up your Eclipse or Android Studio work, you just follow these:

  • Use/open single project at a time
  • clean your project after running your app in emulator every time
  • use mobile/external device instead of emulator
  • don't close emulator after using once, use same emulator for running app each time
  • Disable VCS by using File->Settings->Plugins and disable the following things :
    1.CVS Integration
    2.Git Integration
    3.GitHub
    4.Google Cloud Tools for Android Studio
    5.Subversion Integration

I am also using Android Studio with 4-GB installed main memory but following these statements really boost my Android Studio performance.

Postgresql GROUP_CONCAT equivalent?

Hope below Oracle query will work.

Select First_column,LISTAGG(second_column,',') 
    WITHIN GROUP (ORDER BY second_column) as Sec_column, 
    LISTAGG(third_column,',') 
    WITHIN GROUP (ORDER BY second_column) as thrd_column 
FROM tablename 
GROUP BY first_column

How can I execute PHP code from the command line?

You can use:

 echo '<?php if(function_exists("my_func")) echo "function exists"; ' | php

The short tag "< ?=" can be helpful too:

 echo '<?= function_exists("foo") ? "yes" : "no";' | php
 echo '<?= 8+7+9 ;' | php

The closing tag "?>" is optional, but don't forget the final ";"!

Finding diff between current and last version

If last versions means last tag, and current versions means HEAD (current state), it's just a diff with the last tag:

Looking for tags:

$ git tag --list
...
v20.11.23.4
v20.11.25.1
v20.11.25.2
v20.11.25.351

The last tag would be:

$ git tag --list | tail -n 1
v20.11.25.351

Putting it together:

tag=$(git tag --list | tail -n 1)
git diff $tag

Where in an Eclipse workspace is the list of projects stored?

In Mac OS X, it is under

<workspace>/.metadata/.plugins/org.eclipse.core.resources/.projects

IE8 css selector

In the ASP.NET world, I've tended to use the built-in BrowserCaps feature to write out a set of classes onto the body tag that enable you to target any combination of browser and platform.

So in pre-render, I would run something like this code (assuming you give your tag an ID and make it runat the server):

HtmlGenericControl _body = (HtmlGenericControl)this.FindControl("pageBody");
_body.Attributes.Add("class", Request.Browser.Platform + " " + Request.Browser.Browser + Request.Browser.MajorVersion);

This code enables you to then target a specific browser in your CSS like this:

.IE8 #nav ul li { .... }
.IE7 #nav ul li { .... }
.MacPPC.Firefox #nav ul li { .... }

We create a sub-class of System.Web.UI.MasterPage and make sure all of our master pages inherit from our specialised MasterPage so that every page gets these classes added on for free.

If you're not in an ASP.NET environment, you could use jQuery which has a browser plugin that dynamically adds similar class names on page-load.

This method has the benefit of removing conditional comments from your markup, and also of keeping both your main styles and your browser-specific styles in roughly the same place in your CSS files. It also means your CSS is more future-proof (since it doesn't rely on bugs that may be fixed) and helps your CSS code make much more sense since you only have to see

.IE8 #container { .... }

Instead of

* html #container { .... }

or worse!

How do I speed up the gwt compiler?

Although this entry is quite old and most of you probably already know, I think it's worth mention that GWT 2.x includes a new compile flag which speeds up compiles by skipping optimizations. You definitely shouldn't deploy JavaScript compiled that way, but it can be a time saver during non-production continuous builds.

Just include the flag: -draftCompile to your GWT compiler line.

"relocation R_X86_64_32S against " linking Error

Add -fPIC at the end of CMAKE_CXX_FLAGS and CMAKE_C_FLAG

Example:

set( CMAKE_CXX_FLAGS  "${CMAKE_CXX_FLAGS} -Wall --std=c++11 -O3 -fPIC" )
set( CMAKE_C_FLAGS  "${CMAKE_C_FLAGS} -Wall -O3 -fPIC" )

This solved my issue.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

I had the same error. It is solved by following steps

Go to IIS -> find your site -> right click on the site -> Manage Website -> Advanced Setting -> Check your physical path is correct or not.

If it is wrong, locate the correct path. This will solve issue.

Should I use string.isEmpty() or "".equals(string)?

You can use apache commons StringUtils isEmpty() or isNotEmpty().

Java: random long number in 0 <= x < n range

The standard method to generate a number (without a utility method) in a range is to just use the double with the range:

long range = 1234567L;
Random r = new Random()
long number = (long)(r.nextDouble()*range);

will give you a long between 0 (inclusive) and range (exclusive). Similarly if you want a number between x and y:

long x = 1234567L;
long y = 23456789L;
Random r = new Random()
long number = x+((long)(r.nextDouble()*(y-x)));

will give you a long from 1234567 (inclusive) through 123456789 (exclusive)

Note: check parentheses, because casting to long has higher priority than multiplication.

Credentials for the SQL Server Agent service are invalid

In my case it was more of a Microsoft bug, than an actual issue. I installed under the Administrator login and used strong password btw but I was still getting this error constantly.

I tried to install with Windows credential without entering the password, but that did not go through either. Was getting the same error.

Then I cleared all password textboxes manually and copies the correct password in each text box. Hit enter, and it went through.

The error was most likely misleading.

read subprocess stdout line by line

You want to pass these extra parameters to subprocess.Popen:

bufsize=1, universal_newlines=True

Then you can iterate as in your example. (Tested with Python 3.5)

Programmatically open new pages on Tabs

This works 100%

window.open('http://www.google.com/','_newtab' + Date.now());

How does Go update third-party packages?

Since the question mentioned third-party libraries and not all packages then you probably want to fall back to using wildcards.

A use case being: I just want to update all my packages that are obtained from the Github VCS, then you would just say:

go get -u github.com/... // ('...' being the wildcard). 

This would go ahead and only update your github packages in the current $GOPATH

Same applies for within a VCS too, say you want to only upgrade all the packages from ogranizaiton A's repo's since as they have released a hotfix you depend on:

go get -u github.com/orgA/...

How to use the pass statement?

Suppose you are designing a new class with some methods that you don't want to implement, yet.

class MyClass(object):
    def meth_a(self):
        pass

    def meth_b(self):
        print "I'm meth_b"

If you were to leave out the pass, the code wouldn't run.

You would then get an:

IndentationError: expected an indented block

To summarize, the pass statement does nothing particular, but it can act as a placeholder, as demonstrated here.

execute shell command from android

You should grab the standard input of the su process just launched and write down the command there, otherwise you are running the commands with the current UID.

Try something like this:

try{
    Process su = Runtime.getRuntime().exec("su");
    DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

    outputStream.writeBytes("screenrecord --time-limit 10 /sdcard/MyVideo.mp4\n");
    outputStream.flush();

    outputStream.writeBytes("exit\n");
    outputStream.flush();
    su.waitFor();
}catch(IOException e){
    throw new Exception(e);
}catch(InterruptedException e){
    throw new Exception(e);
}

Git - remote: Repository not found

I was trying to clone a repo and was facing this issue, I tried removing all git related credentials from windows credentials manager after that while trying to clone git was asking me for my credentials and failing with error invalid username or password. This was happening because the repo I was trying to clone was under an organization on github and that organization had two factor auth enabled and git bash probably do not know how to handle 2fa. So I generated a token from https://github.com/settings/tokens and used the github token instead of password while trying to clone the repo and that worked.

How do you convert CString and std::string std::wstring to each other?

Works for me:

std::wstring CStringToWString(const CString& s)
{
    std::string s2;
    s2 = std::string((LPCTSTR)s);
    return std::wstring(s2.begin(),s2.end());
}

CString WStringToCString(std::wstring s)
{
    std::string s2;
    s2 = std::string(s.begin(),s.end());
    return s2.c_str();
}

access key and value of object using *ngFor

You have to do it like this for now, i know not very efficient as you don't want to convert the object you receive from firebase.

    this.af.database.list('/data/' + this.base64Email).subscribe(years => {
        years.forEach(year => {

            var localYears = [];

            Object.keys(year).forEach(month => {
                localYears.push(year[month])
            });

            year.months = localYears;

        })

        this.years = years;

    });

Remove white space below image

You can use code below if you don't want to modify block mode:

img{vertical-align:text-bottom}

Or you can use following as Stuart suggests:

img{vertical-align:bottom}

database attached is read only

If SQL Server Service is running as Local System, than make sure that the folder containing databases should have FULL CONTROL PERMISSION for the Local System account.

This worked for me.

What exactly does the T and Z mean in timestamp?

The T doesn't really stand for anything. It is just the separator that the ISO 8601 combined date-time format requires. You can read it as an abbreviation for Time.

The Z stands for the Zero timezone, as it is offset by 0 from the Coordinated Universal Time (UTC).

Both characters are just static letters in the format, which is why they are not documented by the datetime.strftime() method. You could have used Q or M or Monty Python and the method would have returned them unchanged as well; the method only looks for patterns starting with % to replace those with information from the datetime object.

How to dynamically change the color of the selected menu item of a web page?

It would probably be easiest to implement this using JavaScript ... Here's a JQuery script to demo ... As the others mentioned ... we have a class named 'active' to indicate the active tab - NOT the pseudo-class ':active.' We could have just as easily named it anything though ... selected, current, etc., etc.

/* CSS */

#nav { width:480px;margin:1em auto;}

#nav ul {margin:1em auto; padding:0; font:1em "Arial Black",sans-serif; }

#nav ul li{display:inline;} 

#nav ul li a{text-decoration:none; margin:0; padding:.25em 25px; background:#666; color:#ffffff;} 

#nav ul li a:hover{background:#ff9900; color:#ffffff;} 

#nav ul li a.active {background:#ff9900; color:#ffffff;} 

/* JQuery Example */

<script type="text/javascript">
$(function (){

    $('#nav ul li a').each(function(){
        var path = window.location.href;
        var current = path.substring(path.lastIndexOf('/')+1);
        var url = $(this).attr('href');

        if(url == current){
            $(this).addClass('active');
        };
    });         
});

</script>

 /* HTML */

<div id="nav" >
    <ul>
        <li><a href='index.php?1'>One</a></li>
        <li><a href='index.php?2'>Two</a></li>
        <li><a href='index.php?3'>Three</a></li>
        <li><a href='index.php?4'>Four</a></li>
    </ul>
</div>