Programs & Examples On #Mysql backup

Export and Import all MySQL databases at one time

All the answers I see on this question can have problems with the character sets in some databases due to the problem of redirecting the exit of mysqldump to a file within the shell operator >.

To solve this problem you should do the backup with a command like this

mysqldump -u root -p --opt --all-databases -r backup.sql

To do a good BD restore without any problem with character sets. Obviously you can change the default-character-set as you need.

mysql -uroot -p --default-character-set=utf8
mysql> SET names 'utf8';
mysql> SOURCE backup.sql;

Optional Parameters in Web Api Attribute Routing

Converting my comment into an answer to complement @Kiran Chala's answer as it seems helpful for the audiences-

When we mark a parameter as optional in the action uri using ? character then we must provide default values to the parameters in the method signature as shown below:

MyMethod(string name = "someDefaultValue", int? Id = null)

Styling an input type="file" button

All rendering engines automatically generate a button when an <input type="file"> is created. Historically, that button has been completely un-styleable. However, Trident and WebKit have added hooks through pseudo-elements.

Trident

As of IE10, the file input button can be styled using the ::-ms-browse pseudo-element. Basically, any CSS rules that you apply to a regular button can be applied to the pseudo-element. For example:

_x000D_
_x000D_
::-ms-browse {_x000D_
  background: black;_x000D_
  color: red;_x000D_
  padding: 1em;_x000D_
}
_x000D_
<input type="file">
_x000D_
_x000D_
_x000D_

This displays as follows in IE10 on Windows 8:

This displays as follows in IE10 on Windows 8:

WebKit

WebKit provides a hook for its file input button with the ::-webkit-file-upload-button pseudo-element. Again, pretty much any CSS rule can be applied, therefore the Trident example will work here as well:

_x000D_
_x000D_
::-webkit-file-upload-button {_x000D_
  background: black;_x000D_
  color: red;_x000D_
  padding: 1em;_x000D_
}
_x000D_
<input type="file">
_x000D_
_x000D_
_x000D_

This displays as follows in Chrome 26 on OS X:

This displays as follows in Chrome 26 on OS X:

What's the difference between next() and nextLine() methods from Scanner class?

next() can read the input only till the space. It can't read two words separated by a space. Also, next() places the cursor in the same line after reading the input.

nextLine() reads input including space between the words (that is, it reads till the end of line \n). Once the input is read, nextLine() positions the cursor in the next line.

For reading the entire line you can use nextLine().

How to export html table to excel or pdf in php

Either you can use CSV functions or PHPExcel

or you can try like below

<?php
$file="demo.xls";
$test="<table  ><tr><td>Cell 1</td><td>Cell 2</td></tr></table>";
header("Content-type: application/vnd.ms-excel");
header("Content-Disposition: attachment; filename=$file");
echo $test;
?>

The header for .xlsx files is Content-type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

C# Switch-case string starting with

This is now possible with C# 7.0's pattern matching. For example:

var myString = "abcDEF";

switch(myString)
{
    case string x when x.StartsWith("abc"):
        //Do something here
        break;
}

Stretch Image to Fit 100% of Div Height and Width

Instead of setting absolute widths and heights, you can use percentages:

#mydiv img {
    height: 100%;
    width: 100%;
}

Regular expressions in C: examples?

man regex.h reports there is no manual entry for regex.h, but man 3 regex gives you a page explaining the POSIX functions for pattern matching.
The same functions are described in The GNU C Library: Regular Expression Matching, which explains that the GNU C Library supports both the POSIX.2 interface and the interface the GNU C Library has had for many years.

For example, for an hypothetical program that prints which of the strings passed as argument match the pattern passed as first argument, you could use code similar to the following one.

#include <errno.h>
#include <regex.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void print_regerror (int errcode, size_t length, regex_t *compiled);

int
main (int argc, char *argv[])
{
  regex_t regex;
  int result;

  if (argc < 3)
    {
      // The number of passed arguments is lower than the number of
      // expected arguments.
      fputs ("Missing command line arguments\n", stderr);
      return EXIT_FAILURE;
    }

  result = regcomp (&regex, argv[1], REG_EXTENDED);
  if (result)
    {
      // Any value different from 0 means it was not possible to 
      // compile the regular expression, either for memory problems
      // or problems with the regular expression syntax.
      if (result == REG_ESPACE)
        fprintf (stderr, "%s\n", strerror(ENOMEM));
      else
        fputs ("Syntax error in the regular expression passed as first argument\n", stderr);
      return EXIT_FAILURE;               
    }
  for (int i = 2; i < argc; i++)
    {
      result = regexec (&regex, argv[i], 0, NULL, 0);
      if (!result)
        {
          printf ("'%s' matches the regular expression\n", argv[i]);
        }
      else if (result == REG_NOMATCH)
        {
          printf ("'%s' doesn't the regular expression\n", argv[i]);
        }
      else
        {
          // The function returned an error; print the string 
          // describing it.
          // Get the size of the buffer required for the error message.
          size_t length = regerror (result, &regex, NULL, 0);
          print_regerror (result, length, &regex);       
          return EXIT_FAILURE;
        }
    }

  /* Free the memory allocated from regcomp(). */
  regfree (&regex);
  return EXIT_SUCCESS;
}

void
print_regerror (int errcode, size_t length, regex_t *compiled)
{
  char buffer[length];
  (void) regerror (errcode, compiled, buffer, length);
  fprintf(stderr, "Regex match failed: %s\n", buffer);
}

The last argument of regcomp() needs to be at least REG_EXTENDED, or the functions will use basic regular expressions, which means that (for example) you would need to use a\{3\} instead of a{3} used from extended regular expressions, which is probably what you expect to use.

POSIX.2 has also another function for wildcard matching: fnmatch(). It doesn't allow to compile the regular expression, or get the substrings matching a sub-expression, but it is very specific for checking when a filename match a wildcard (e.g. it uses the FNM_PATHNAME flag).

How to iterate through a table rows and get the cell values using jQuery

I got it and explained in below:

//This table with two rows containing each row, one select in first td, and one input tags in second td and second input in third td;

<table id="tableID" class="table table-condensed">
       <thead>
          <tr>
             <th><label>From Group</lable></th>
             <th><label>To Group</lable></th>
             <th><label>Level</lable></th>

           </tr>
       </thead>
         <tbody>
           <tr id="rowCount">
             <td>
               <select >
                 <option value="">select</option>
                 <option value="G1">G1</option>
                 <option value="G2">G2</option>
                 <option value="G3">G3</option>
                 <option value="G4">G4</option>
               </select>
            </td>
            <td>
              <input type="text" id="" value="" readonly="readonly" />
            </td>
            <td>
              <input type="text" value=""  readonly="readonly" />
            </td>
         </tr>
         <tr id="rowCount">
          <td>
            <select >
              <option value="">select</option>
              <option value="G1">G1</option>
              <option value="G2">G2</option>
              <option value="G3">G3</option>
              <option value="G4">G4</option>
           </select>
         </td>
         <td>
           <input type="text" id="" value="" readonly="readonly" />
         </td>
         <td>
           <input type="text" value=""  readonly="readonly" />
         </td>
      </tr>
  </tbody>
</table>

  <button type="button" class="btn btn-default generate-btn search-btn white-font border-6 no-border" id="saveDtls">Save</button>


//call on click of Save button;
 $('#saveDtls').click(function(event) {

  var TableData = []; //initialize array;                           
  var data=""; //empty var;

  //Here traverse and  read input/select values present in each td of each tr, ;
  $("table#tableID > tbody > tr").each(function(row, tr) {

     TableData[row]={
        "fromGroup":  $('td:eq(0) select',this).val(),
        "toGroup": $('td:eq(1) input',this).val(),
        "level": $('td:eq(2) input',this).val()
 };

  //Convert tableData array to JsonData
  data=JSON.stringify(TableData)
  //alert('data'+data); 
  });
});

How to find out what group a given user has?

On Linux/OS X/Unix to display the groups to which you (or the optionally specified user) belong, use:

id -Gn [user]

which is equivalent to groups [user] utility which has been obsoleted on Unix.

On OS X/Unix, the command id -p [user] is suggested for normal interactive.

Explanation on the parameters:

-G, --groups - print all group IDs

-n, --name - print a name instead of a number, for -ugG

-p - Make the output human-readable.

How to find prime numbers between 0 - 100?

Whatever the language, one of the best and most accessible ways of finding primes within a range is using a sieve.

Not going to give you code, but this is a good starting point.

For a small range, such as yours, the most efficient would be pre-computing the numbers.

Finding import static statements for Mockito constructs

Here's what I've been doing to cope with the situation.

I use global imports on a new test class.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import static org.mockito.Matchers.*;

When you are finished writing your test and need to commit, you just CTRL+SHIFT+O to organize the packages. For example, you may just be left with:

import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.Matchers.anyString;

This allows you to code away without getting 'stuck' trying to find the correct package to import.

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

This thread is a bit older but here something I just came across:

Try this code:

$date = new DateTime();
$arr = ['date' => $date];

echo $date->format('Ymd') . '<br>';
mytest($arr);
echo $date->format('Ymd') . '<br>';

function mytest($params = []) {
    if (isset($params['date'])) {
        $params['date']->add(new DateInterval('P1D'));
    }
}

http://codepad.viper-7.com/gwPYMw

Note there is no amp for the $params parameter and still it changes the value of $arr['date']. This doesn't really match with all the other explanations here and what I thought until now.

If I clone the $params['date'] object, the 2nd outputted date stays the same. If I just set it to a string it doesn't effect the output either.

Spring: How to get parameters from POST body?

You can get param from request.

@ResponseBody
public ResponseEntity<Boolean> saveData(HttpServletRequest request,
            HttpServletResponse response, Model model){
   String jsonString = request.getParameter("json");
}

How to delete multiple pandas (python) dataframes from memory to save RAM?

del statement does not delete an instance, it merely deletes a name.

When you do del i, you are deleting just the name i - but the instance is still bound to some other name, so it won't be Garbage-Collected.

If you want to release memory, your dataframes has to be Garbage-Collected, i.e. delete all references to them.

If you created your dateframes dynamically to list, then removing that list will trigger Garbage Collection.

>>> lst = [pd.DataFrame(), pd.DataFrame(), pd.DataFrame()]
>>> del lst     # memory is released

If you created some variables, you have to delete them all.

>>> a, b, c = pd.DataFrame(), pd.DataFrame(), pd.DataFrame()
>>> lst = [a, b, c]
>>> del a, b, c # dfs still in list
>>> del lst     # memory release now

Get IP address of visitors using Flask for Python

I have Nginx and With below Nginx Config:

server {
    listen 80;
    server_name xxxxxx;
    location / {
               proxy_set_header   Host                 $host;
               proxy_set_header   X-Real-IP            $remote_addr;
               proxy_set_header   X-Forwarded-For      $proxy_add_x_forwarded_for;
               proxy_set_header   X-Forwarded-Proto    $scheme;

               proxy_pass http://x.x.x.x:8000;
        }
}

@tirtha-r solution worked for me

#!flask/bin/python
from flask import Flask, jsonify, request
app = Flask(__name__)

@app.route('/', methods=['GET'])
def get_tasks():
    if request.environ.get('HTTP_X_FORWARDED_FOR') is None:
        return jsonify({'ip': request.environ['REMOTE_ADDR']}), 200
    else:
        return jsonify({'ip': request.environ['HTTP_X_FORWARDED_FOR']}), 200

if __name__ == '__main__':
    app.run(debug=True,host='0.0.0.0', port=8000)

My Request and Response:

curl -X GET http://test.api

{
    "ip": "Client Ip......"
}

Where is SQL Profiler in my SQL Server 2008?

SQL Server Express does not come with profiler, but you can use SQL Server 2005/2008 Express Profiler instead.

Display Records From MySQL Database using JTable in Java

this is the easy way to do that you just need to download the jar file "rs2xml.jar" add it to your project and do that : 1- creat a connection 2- statment and resultset 3- creat a jtable 4- give the result set to DbUtils.resultSetToTableModel(rs) as define in this methode you well get your jtable so easy.

public void afficherAll(String tableName){
        String sql="select * from "+tableName;
        try {
            stmt=con.createStatement();
            rs=stmt.executeQuery(sql);
            tbContTable.setModel(DbUtils.resultSetToTableModel(rs));
        } catch (SQLException e) {
            // TODO Auto-generated catch block
             JOptionPane.showMessageDialog(null, e);
        }       
    }

How to show android checkbox at right side?

Just copy this:

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Your text:"/>
        <CheckBox
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:checked="true"
            />
    </LinearLayout>

Happy codding! :)

VBA module that runs other modules

I just learned something new thanks to Artiso. I gave each module a name in the properties box. These names were also what I declared in the module. When I tried to call my second module, I kept getting an error: Compile error: Expected variable or procedure, not module

After reading Artiso's comment above about not having the same names, I renamed my second module, called it from the first, and problem solved. Interesting stuff! Thanks for the info Artiso!

In case my experience is unclear:

Module Name: AllFSGroupsCY Public Sub AllFSGroupsCY()

Module Name: AllFSGroupsPY Public Sub AllFSGroupsPY()

From AllFSGroupsCY()

Public Sub FSGroupsCY()

    AllFSGroupsPY 'will error each time until the properties name is changed

End Sub

Android - how do I investigate an ANR?

Basic on @Horyun Lee answer, I wrote a small python script to help to investigate ANR from traces.txt.

The ANRs will output as graphics by graphviz if you have installed grapvhviz on your system.

$ ./anr.py --format png ./traces.txt

A png will output like below if there are ANRs detected in file traces.txt. It's more intuitive.

enter image description here

The sample traces.txt file used above was get from here.

Install Visual Studio 2013 on Windows 7

Fake IE10 to install Visual Studio 2013

Visual Studio 2013 requires Internet Explorer 10. If you try to install it on Windows 7 with IE8 you get the following error This version of Visual Studio requires Internet Explorer 10”. The value that the VS 2013 installer checks is svcVersion in the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorerkey on 32-bit Windows and HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer on 64-bit Windows. Any value >= 10.0.0.0 makes the installer happy.

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer]
"svcVersion"="10.0.0.0"

[HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer]
"svcVersion"="10.0.0.0"

opening html from google drive

Steps:

  1. Upload html file to the google drive and share it as "Public on the web" after uploading just make sure that the content of your html is not modified in the drive.
  2. Right click on the shared file and click on 'Get link' and save it to notepad it will look something like 'https://drive.google.com/open?id=0B55nkHvMDw18T3VaYjY3NEE4SEE'
  3. Take the code (about 28 character alphanumeric) after '=' sign from the above link and paste it after 'https://googledrive.com/host/' now 'https://googledrive.com/host/0B55nkHvMDw18T3VaYjY3NEE4SEE' is your actual sharable url link, open the html file from address bar of the browser using this url.

open program minimized via command prompt

If the application is already open (even in background), it will be restored by "start" command. Exit the program if running then /max or /min will work

MySQL remove all whitespaces from the entire column

Using below query you can remove leading and trailing whitespace in a MySQL.

UPDATE `table_name`
SET `col_name` = TRIM(`col_name`);

split python source code into multiple files?

Python has importing and namespacing, which are good. In Python you can import into the current namespace, like:

>>> from test import disp
>>> disp('World!')

Or with a namespace:

>>> import test
>>> test.disp('World!')

Typescript empty object for a typed variable

If you declare an empty object literal and then assign values later on, then you can consider those values optional (may or may not be there), so just type them as optional with a question mark:

type User = {
    Username?: string;
    Email?: string;
}

How can I get a process handle by its name in C++?

There are two basic techniques. The first uses PSAPI; MSDN has an example that uses EnumProcesses, OpenProcess, EnumProcessModules, and GetModuleBaseName.

The other uses Toolhelp, which I prefer. Use CreateToolhelp32Snapshot to get a snapshot of the process list, walk over it with Process32First and Process32Next, which provides module name and process ID, until you find the one you want, and then call OpenProcess to get a handle.

setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op

I have faced same problem since I have updated the latest react version. Solved like below.

My code was

async componentDidMount() {
  const { default: Component } = await importComponent();
  Nprogress.done();
  this.setState({
    component: <Component {...this.props} />
  });
}

Changed to

componentWillUnmount() {
  this.mounted = false;
}
async componentDidMount() {
  this.mounted = true;
  const { default: Component } = await importComponent();
  if (this.mounted) {
    this.setState({
      component: <Component {...this.props} />
    });
  }
}

Output (echo/print) everything from a PHP Array

 //@parram $data-array,$d-if true then die by default it is false
 //@author Your name

 function p($data,$d = false){

     echo "<pre>"; 
         print_r($data);
     echo "</pre>"; 

     if($d == TRUE){
        die();
     } 
} // END OF FUNCTION

Use this function every time whenver you need to string or array it will wroks just GREAT.
There are 2 Patameters
1.$data - It can be Array or String
2.$d - By Default it is FALSE but if you set to true then it will execute die() function

In your case you can use in this way....

while($row = mysql_fetch_array($result)){
    p($row); // Use this function if you use above function in your page.
}

React - Component Full Screen (with height 100%)

#app {
  height: 100%;
  min-height: 100vh;
}

Always full height of view min

How to delete columns in pyspark dataframe

You can use two way:

1: You just keep the necessary columns:

drop_column_list = ["drop_column"]
df = df.select([column for column in df.columns if column not in drop_column_list])  

2: This is the more elegant way.

df = df.drop("col_name")

You should avoid the collect() version, because it will send to the master the complete dataset, it will take a big computing effort!

Plotting multiple curves same graph and same scale

(The typical method would be to use plot just once to set up the limits, possibly to include the range of all series combined, and then to use points and lines to add the separate series.) To use plot multiple times with par(new=TRUE) you need to make sure that your first plot has a proper ylim to accept the all series (and in another situation, you may need to also use the same strategy for xlim):

# first plot
plot(x, y1, ylim=range(c(y1,y2)))

# second plot  EDIT: needs to have same ylim
par(new = TRUE)
plot(x, y2, ylim=range(c(y1,y2)), axes = FALSE, xlab = "", ylab = "")

enter image description here

This next code will do the task more compactly, by default you get numbers as points but the second one gives you typical R-type-"points":

  matplot(x, cbind(y1,y2))
  matplot(x, cbind(y1,y2), pch=1)

Set default value of an integer column SQLite

It happens that I'm just starting to learn coding and I needed something similar as you have just asked in SQLite (I´m using [SQLiteStudio] (3.1.1)).

It happens that you must define the column's 'Constraint' as 'Not Null' then entering your desired definition using 'Default' 'Constraint' or it will not work (I don't know if this is an SQLite or the program requirment).

Here is the code I used:

CREATE TABLE <MY_TABLE> (
<MY_TABLE_KEY>       INTEGER    UNIQUE
                                PRIMARY KEY,
<MY_TABLE_SERIAL>    TEXT       DEFAULT (<MY_VALUE>) 
                                NOT NULL
<THE_REST_COLUMNS>
);

How to get the Android Emulator's IP address?

If you need to refer to your host computer's localhost, such as when you want the emulator client to contact a server running on the same host, use the alias 10.0.2.2 to refer to the host computer's loopback interface. From the emulator's perspective, localhost (127.0.0.1) refers to its own loopback interface.More details: http://developer.android.com/guide/faq/commontasks.html#localhostalias

Fixed header, footer with scrollable content

It works fine for me using a CSS grid. Initially fix the container and then give overflow-y: auto; for the centre content which has to get scrolled i.e other than header and footer.

_x000D_
_x000D_
.container{
  height: 100%;
  left: 0;
  position: fixed;
  top: 0;
  width: 100%;
  display: grid;
  grid-template-rows: 5em auto 3em;
}

header{
   grid-row: 1;  
    background-color: rgb(148, 142, 142);
    justify-self: center;
    align-self: center;
    width: 100%;
}

.body{
  grid-row: 2;
  overflow-y: auto;
}

footer{
   grid-row: 3;
   
    background: rgb(110, 112, 112);
}
_x000D_
<div class="container">
    <header><h1>Header</h1></header>
    <div class="body">
      Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</div>
    <footer><h3>Footer</h3></footer>
</div>
_x000D_
_x000D_
_x000D_

How to create an integer-for-loop in Ruby?

If you're doing this in your erb view (for Rails), be mindful of the <% and <%= differences. What you'd want is:

<% (1..x).each do |i| %>
  Code to display using <%= stuff %> that you want to display    
<% end %>

For plain Ruby, you can refer to: http://www.tutorialspoint.com/ruby/ruby_loops.htm

Passing data to components in vue.js

The above-mentioned responses work well but if you want to pass data between 2 sibling components, then the event bus can also be used. Check out this blog which would help you understand better.

supppose for 2 components : CompA & CompB having same parent and main.js for setting up main vue app. For passing data from CompA to CompB without involving parent component you can do the following.

in main.js file, declare a separate global Vue instance, that will be event bus.

export const bus = new Vue();

In CompA, where the event is generated : you have to emit the event to bus.

methods: {
      somethingHappened (){
          bus.$emit('changedSomething', 'new data');
      }
  }

Now the task is to listen the emitted event, so, in CompB, you can listen like.

created (){
    bus.$on('changedSomething', (newData) => {
      console.log(newData);
    })
  }

Advantages:

  • Less & Clean code.
  • Parent should not involve in passing down data from 1 child comp to another ( as the number of children grows, it will become hard to maintain )
  • Follows pub-sub approach.

Convert an object to an XML string

Here are conversion method for both ways. this = instance of your class

public string ToXML()
    {
        using(var stringwriter = new System.IO.StringWriter())
        { 
            var serializer = new XmlSerializer(this.GetType());
            serializer.Serialize(stringwriter, this);
            return stringwriter.ToString();
        }
    }

 public static YourClass LoadFromXMLString(string xmlText)
    {
        using(var stringReader = new System.IO.StringReader(xmlText))
        {
            var serializer = new XmlSerializer(typeof(YourClass ));
            return serializer.Deserialize(stringReader) as YourClass ;
        }
    }

How to insert multiple rows from array using CodeIgniter framework?

Use insert batch in codeigniter to insert multiple row of data.

$this->db->insert_batch('tabname',$data_array); // $data_array holds the value to be inserted

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

Did you implement the main() function?

int main(int argc, char **argv) {
    ... code ...
    return 0;
}

[edit]

You have your main() in another source file so you've probably forgotten to add it to your project.

To add an existing source file: In Solution Explorer, right-click the Source Files folder, point to Add, and then click Existing Item. Now select the source file containing the main()

How To fix white screen on app Start up?

The user543 answer is perfect

<activity
        android:name="first Activity Name"
        android:theme="@android:style/Theme.Translucent.NoTitleBar" >
 <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
 </activity>

But:

You'r LAUNCHER Activity must extands Activity, not AppCompatActivity as it came by default!

Content is not allowed in Prolog SAXParserException

Check the XML. It is not a valid xml.

Prolog is the first line with xml version info. It ok not to include it in your xml.

This error is thrown when the parser reads an invalid tag at the start of the document. Normally where the prolog resides.

e.g.

  1. Root/><document>
  2. Root<document>

Why are there two ways to unstage a file in Git?

if you've accidentally staged files that you would not like to commit, and want to be certain you keep the changes, you can also use:

git stash
git stash pop

this performs a reset to HEAD and re-applies your changes, allowing you to re-stage individual files for commit. this is also helpful if you've forgotten to create a feature branch for pull requests (git stash ; git checkout -b <feature> ; git stash pop).

Spring 3 RequestMapping: Get path value

Just found that issue corresponding to my problem. Using HandlerMapping constants I was able to wrote a small utility for that purpose:

/**
 * Extract path from a controller mapping. /controllerUrl/** => return matched **
 * @param request incoming request.
 * @return extracted path
 */
public static String extractPathFromPattern(final HttpServletRequest request){


    String path = (String) request.getAttribute(
            HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);
    String bestMatchPattern = (String ) request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE);

    AntPathMatcher apm = new AntPathMatcher();
    String finalPath = apm.extractPathWithinPattern(bestMatchPattern, path);

    return finalPath;

}

Seeing if data is normally distributed in R

when you perform a test, you ever have the probabilty to reject the null hypothesis when it is true.

See the nextt R code:

p=function(n){
  x=rnorm(n,0,1)
  s=shapiro.test(x)
  s$p.value
}

rep1=replicate(1000,p(5))
rep2=replicate(1000,p(100))
plot(density(rep1))
lines(density(rep2),col="blue")
abline(v=0.05,lty=3)

The graph shows that whether you have a sample size small or big a 5% of the times you have a chance to reject the null hypothesis when it s true (a Type-I error)

jQuery checkbox checked state changed event

Try this jQuery validation

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#myform').validate({ // initialize the plugin_x000D_
    rules: {_x000D_
      agree: {_x000D_
        required: true_x000D_
      }_x000D_
_x000D_
    },_x000D_
    submitHandler: function(form) {_x000D_
      alert('valid form submitted');_x000D_
      return false;_x000D_
    }_x000D_
  });_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.js"></script>_x000D_
_x000D_
<form id="myform" action="" method="post">_x000D_
  <div class="buttons">_x000D_
    <div class="pull-right">_x000D_
      <input type="checkbox" name="agree" /><br/>_x000D_
      <label>I have read and agree to the <a href="https://stackexchange.com/legal/terms-of-service">Terms of services</a> </label>_x000D_
    </div>_x000D_
  </div>_x000D_
  <button type="submit">Agree</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

element not interactable exception in selenium web automation

Try setting an implicit wait of maybe 10 seconds.

gmail.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

Or set an explicit wait. An explicit waits is code you define to wait for a certain condition to occur before proceeding further in the code. In your case, it is the visibility of the password input field. (Thanks to ainlolcat's comment)

WebDriver gmail= new ChromeDriver();
gmail.get("https://www.gmail.co.in"); 
gmail.findElement(By.id("Email")).sendKeys("abcd");
gmail.findElement(By.id("next")).click();
WebDriverWait wait = new WebDriverWait(gmail, 10);
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.id("Passwd")));
gmail.findElement(By.id("Passwd")).sendKeys("xyz");

Explanation: The reason selenium can't find the element is because the id of the password input field is initially Passwd-hidden. After you click on the "Next" button, Google first verifies the email address entered and then shows the password input field (by changing the id from Passwd-hidden to Passwd). So, when the password field is still hidden (i.e. Google is still verifying the email id), your webdriver starts searching for the password input field with id Passwd which is still hidden. And hence, an exception is thrown.

Convert Time DataType into AM PM Format:

SELECT CONVERT(varchar, StartTime, 100) AS ST,
       CONVERT(varchar, EndTime, 100) AS ET
FROM some_table

or

SELECT RIGHT('0'+ LTRIM(RIGHT(CONVERT(varchar, StartTime, 100),8)),8) AS ST,
       RIGHT('0'+ LTRIM(RIGHT(CONVERT(varchar, EndTime, 100),8)),8) AS ET
FROM some_table

Passing parameters in Javascript onClick event

onclick vs addEventListener. A matter of preference perhaps (where IE>9).

// Using closures
function onClickLink(e, index) {   
    alert(index);
    return false;
}

var div = document.getElementById('div');

for (var i = 0; i < 10; i++) {
    var link = document.createElement('a');

    link.setAttribute('href', '#');
    link.innerHTML = i + '';
    link.addEventListener('click', (function(e) {
        var index = i;
        return function(e) {
            return onClickLink(e, index);
        }
    })(), false);
    div.appendChild(link);
    div.appendChild(document.createElement('BR'));
}

How abut just using a plain data-* attribute, not as cool as a closure, but..

function onClickLink(e) {       
    alert(e.target.getAttribute('data-index'));
    return false;
}

var div = document.getElementById('div');

for (var i = 0; i < 10; i++) {
    var link = document.createElement('a');

    link.setAttribute('href', '#');
    link.setAttribute('data-index', i);
    link.innerHTML = i + ' Hello';        
    link.addEventListener('click', onClickLink, false);
    div.appendChild(link);
    div.appendChild(document.createElement('BR'));
}

What is a callback function?

A layman response would be that it is a function that is not called by you but rather by the user or by the browser after a certain event has happened or after some code has been processed.

Adding an HTTP Header to the request in a servlet filter

You'll have to use an HttpServletRequestWrapper:

public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
    final HttpServletRequest httpRequest = (HttpServletRequest) request;
    HttpServletRequestWrapper wrapper = new HttpServletRequestWrapper(httpRequest) {
        @Override
        public String getHeader(String name) {
            final String value = request.getParameter(name);
            if (value != null) {
                return value;
            }
            return super.getHeader(name);
        }
    };
    chain.doFilter(wrapper, response);
}

Depending on what you want to do you may need to implement other methods of the wrapper like getHeaderNames for instance. Just be aware that this is trusting the client and allowing them to manipulate any HTTP header. You may want to sandbox it and only allow certain header values to be modified this way.

jQuery.getJSON - Access-Control-Allow-Origin Issue

It's simple, use $.getJSON() function and in your URL just include

callback=?

as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/

RecyclerView vs. ListView

I worked a little with RecyclerView and still prefer ListView.

  1. Sure, both of them use ViewHolders, so this is not an advantage.

  2. A RecyclerView is more difficult in coding.

  3. A RecyclerView doesn't contain a header and footer, so it's a minus.

  4. A ListView doesn't require to make a ViewHolder. In cases where you want to have a list with sections or subheaders it would be a good idea to make independent items (without a ViewHolder), it's easier and doesn't require separate classes.

Excel function to make SQL-like queries on worksheet data?

One quick way to do this is to create a column with a formula that evaluates to true for the rows you care about and then filter for the value TRUE in that column.

Using C# regular expressions to remove HTML tags

try regular expression method at this URL: http://www.dotnetperls.com/remove-html-tags

/// <summary>
/// Remove HTML from string with Regex.
/// </summary>
public static string StripTagsRegex(string source)
{
return Regex.Replace(source, "<.*?>", string.Empty);
}

/// <summary>
/// Compiled regular expression for performance.
/// </summary>
static Regex _htmlRegex = new Regex("<.*?>", RegexOptions.Compiled);

/// <summary>
/// Remove HTML from string with compiled Regex.
/// </summary>
public static string StripTagsRegexCompiled(string source)
{
return _htmlRegex.Replace(source, string.Empty);
}

Programmatically get own phone number in iOS

No official API to do it. Using private API you can use following method:

-(NSString*) getMyNumber {
    NSLog(@"Open CoreTelephony");
    void *lib = dlopen("/Symbols/System/Library/Framework/CoreTelephony.framework/CoreTelephony",RTLD_LAZY);
    NSLog(@"Get CTSettingCopyMyPhoneNumber from CoreTelephony");
    NSString* (*pCTSettingCopyMyPhoneNumber)() = dlsym(lib, "CTSettingCopyMyPhoneNumber");
    NSLog(@"Get CTSettingCopyMyPhoneNumber from CoreTelephony");

    if (pCTSettingCopyMyPhoneNumber == nil) {
        NSLog(@"pCTSettingCopyMyPhoneNumber is nil");
        return nil;
    }
    NSString* ownPhoneNumber = pCTSettingCopyMyPhoneNumber();
    dlclose(lib);
    return ownPhoneNumber;
}

It works on iOS 6 without JB and special signing.

As mentioned creker on iOS 7 with JB you need to use entitlements to make it working.

How to do it with entitlements you can find here: iOS 7: How to get own number via private API?

APT command line interface-like yes/no input?

There is a function strtobool in Python's standard library: http://docs.python.org/2/distutils/apiref.html?highlight=distutils.util#distutils.util.strtobool

You can use it to check user's input and transform it to True or False value.

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

In order for System.loadLibrary() to work, the library (on Windows, a DLL) must be in a directory somewhere on your PATH or on a path listed in the java.library.path system property (so you can launch Java like java -Djava.library.path=/path/to/dir).

Additionally, for loadLibrary(), you specify the base name of the library, without the .dll at the end. So, for /path/to/something.dll, you would just use System.loadLibrary("something").

You also need to look at the exact UnsatisfiedLinkError that you are getting. If it says something like:

Exception in thread "main" java.lang.UnsatisfiedLinkError: no foo in java.library.path

then it can't find the foo library (foo.dll) in your PATH or java.library.path. If it says something like:

Exception in thread "main" java.lang.UnsatisfiedLinkError: com.example.program.ClassName.foo()V

then something is wrong with the library itself in the sense that Java is not able to map a native Java function in your application to its actual native counterpart.

To start with, I would put some logging around your System.loadLibrary() call to see if that executes properly. If it throws an exception or is not in a code path that is actually executed, then you will always get the latter type of UnsatisfiedLinkError explained above.

As a sidenote, most people put their loadLibrary() calls into a static initializer block in the class with the native methods, to ensure that it is always executed exactly once:

class Foo {

    static {
        System.loadLibrary('foo');
    }

    public Foo() {
    }

}

Android Gallery on Android 4.4 (KitKat) returns different URI for Intent.ACTION_GET_CONTENT

This is a total hack, but here's what I did...

So while playing with setting up a DocumentsProvider, I noticed that the sample code (in getDocIdForFile, around line 450) generates a unique id for a selected document based on the file's (unique) path relative to the specified root you give it (that is, what you set mBaseDir to on line 96).

So the URI ends up looking something like:

content://com.example.provider/document/root:path/to/the/file

As the docs say, it's assuming only a single root (in my case that's Environment.getExternalStorageDirectory() but you may use somewhere else... then it takes the file path, starting at the root, and makes it the unique ID, prepending "root:". So I can determine the path by eliminating the "/document/root:" part from uri.getPath(), creating an actual file path by doing something like this:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
// check resultcodes and such, then...
uri = data.getData();
if (uri.getAuthority().equals("com.example.provider"))  {
    String path = Environment.getExternalStorageDirectory(0.toString()
                 .concat("/")
                 .concat(uri.getPath().substring("/document/root:".length())));
    doSomethingWithThePath(path); }
else {
    // another provider (maybe a cloud-based service such as GDrive)
    // created this uri.  So handle it, or don't.  You can allow specific
    // local filesystem providers, filter non-filesystem path results, etc.
}

I know. It's shameful, but it worked. Again, this relies on you using your own documents provider in your app to generate the document ID.

(Also, there's a better way to build the path that don't assume "/" is the path separator, etc. But you get the idea.)

Using "Object.create" instead of "new"

Summary:

  • Object.create() is a Javascript function which takes 2 arguments and returns a new object.
  • The first argument is an object which will be the prototype of the newly created object
  • The second argument is an object which will be the properties of the newly created object

Example:

_x000D_
_x000D_
const proto = {_x000D_
  talk : () => console.log('hi')_x000D_
}_x000D_
_x000D_
const props = {_x000D_
  age: {_x000D_
    writable: true,_x000D_
    configurable: true,_x000D_
    value: 26_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
let Person = Object.create(proto, props)_x000D_
_x000D_
console.log(Person.age);_x000D_
Person.talk();
_x000D_
_x000D_
_x000D_

Practical applications:

  1. The main advantage of creating an object in this manner is that the prototype can be explicitly defined. When using an object literal, or the new keyword you have no control over this (however, you can overwrite them of course).
  2. If we want to have a prototype The new keyword invokes a constructor function. With Object.create() there is no need for invoking or even declaring a constructor function.
  3. It can Basically be a helpful tool when you want create objects in a very dynamic manner. We can make an object factory function which creates objects with different prototypes depending on the arguments received.

Excel Formula to SUMIF date falls in particular month

=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )

Explanation:

  • (MONTH($A$2:$A$6)=1) creates an array of 1 and 0, it's 1 when the month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]

  • SUMPRODUCT first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6), then it sums them. Hence in your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)

This works also in OpenOffice and Google Spreadsheets

jquery: get value of custom attribute

You need some form of iteration here, as val (except when called with a function) only works on the first element:

$("input[placeholder]").val($("input[placeholder]").attr("placeholder"));

should be:

$("input[placeholder]").each( function () {
    $(this).val( $(this).attr("placeholder") );
});

or

$("input[placeholder]").val(function() {
    return $(this).attr("placeholder");
});

String comparison - Android

if(gender.equals(g1)); <---
if(gender == "Female"); <---

You have semicolon after if.REMOVE IT.

Get a list of numbers as input from the user

Get a list of number as input from the user.

This can be done by using list in python.

L=list(map(int,input(),split()))

Here L indicates list, map is used to map input with the position, int specifies the datatype of the user input which is in integer datatype, and split() is used to split the number based on space.

.

enter image description here

Git: How to pull a single file from a server repository in Git?

This windows batch works regardless of whether or not it's on GitHub. I'm using it because it shows some stark caveats. You'll notice that the operation is slow and traversing hundreds of megabytes of data, so don't use this method if your requirements are based on available bandwidth/R-W memory.

sparse_checkout.bat

pushd "%~dp0"
if not exist .\ms-server-essentials-docs mkdir .\ms-server-essentials-docs
pushd .\ms-server-essentials-docs
git init
git remote add origin -f https://github.com/MicrosoftDocs/windowsserverdocs.git
git config core.sparseCheckout true
(echo EssentialsDocs)>>.git\info\sparse-checkout
git pull origin master

=>

C:\Users\user name\Desktop>sparse_checkout.bat

C:\Users\user name\Desktop>pushd "C:\Users\user name\Desktop\"

C:\Users\user name\Desktop>if not exist .\ms-server-essentials-docs mkdir .\ms-server-essentials-docs

C:\Users\user name\Desktop>pushd .\ms-server-essentials-docs

C:\Users\user name\Desktop\ms-server-essentials-docs>git init Initialized empty Git repository in C:/Users/user name/Desktop/ms-server-essentials-docs/.git/

C:\Users\user name\Desktop\ms-server-essentials-docs>git remote add origin -f https://github.com/MicrosoftDocs/windowsserverdocs.git Updating origin remote: Enumerating objects: 97, done. remote: Counting objects: 100% (97/97), done. remote: Compressing objects: 100% (44/44), done. remote: Total 145517 (delta 63), reused 76 (delta 53), pack-reused 145420 Receiving objects: 100% (145517/145517), 751.33 MiB | 32.06 MiB/s, done. Resolving deltas: 100% (102110/102110), done. From https://github.com/MicrosoftDocs/windowsserverdocs * [new branch]
1106-conflict -> origin/1106-conflict * [new branch]
FromPrivateRepo -> origin/FromPrivateRepo * [new branch]
PR183 -> origin/PR183 * [new branch]
conflictfix -> origin/conflictfix * [new branch]
eross-msft-patch-1 -> origin/eross-msft-patch-1 * [new branch]
master -> origin/master * [new branch] patch-1
-> origin/patch-1 * [new branch] repo_sync_working_branch -> origin/repo_sync_working_branch * [new branch]
shortpatti-patch-1 -> origin/shortpatti-patch-1 * [new branch]
shortpatti-patch-2 -> origin/shortpatti-patch-2 * [new branch]
shortpatti-patch-3 -> origin/shortpatti-patch-3 * [new branch]
shortpatti-patch-4 -> origin/shortpatti-patch-4 * [new branch]
shortpatti-patch-5 -> origin/shortpatti-patch-5 * [new branch]
shortpatti-patch-6 -> origin/shortpatti-patch-6 * [new branch]
shortpatti-patch-7 -> origin/shortpatti-patch-7 * [new branch]
shortpatti-patch-8 -> origin/shortpatti-patch-8

C:\Users\user name\Desktop\ms-server-essentials-docs>git config core.sparseCheckout true

C:\Users\user name\Desktop\ms-server-essentials-docs>(echo EssentialsDocs ) 1>>.git\info\sparse-checkout

C:\Users\user name\Desktop\ms-server-essentials-docs>git pull origin master
From https://github.com/MicrosoftDocs/windowsserverdocs
* branch master -> FETCH_HEAD

What is the difference between & and && in Java?

&& and || are called short circuit operators. When they are used, for || - if the first operand evaluates to true, then the rest of the operands are not evaluated. For && - if the first operand evaluates to false, the rest of them don't get evaluated at all.

so if (a || (++x > 0)) in this example the variable x won't get incremented if a was true.

Convert .class to .java

Invoking javap to read the bytecode

The javap command takes class-names without the .class extension. Try

javap -c ClassName

Converting .class files back to .java files

javap will however not give you the implementations of the methods in java-syntax. It will at most give it to you in JVM bytecode format.

To actually decompile (i.e., do the reverse of javac) you will have to use proper decompiler. See for instance the following related question:

Read a HTML file into a string variable in memory

What kind of processing are you trying to do? You can do XmlDocument doc = new XmlDocument(); followed by doc.Load(filename). Then the XML document can be parsed in memory.

Read here for more information on XmlDocument:

How do I align a label and a textarea?

You need to put them both in some container element and then apply the alignment on it.

For example:

_x000D_
_x000D_
.formfield * {_x000D_
  vertical-align: middle;_x000D_
}
_x000D_
<p class="formfield">_x000D_
  <label for="textarea">Label for textarea</label>_x000D_
  <textarea id="textarea" rows="5">Textarea</textarea>_x000D_
</p>
_x000D_
_x000D_
_x000D_

What good are SQL Server schemas?

Just like Namespace of C# codes.

Recommended way to save uploaded files in a servlet application

I post my final way of doing it based on the accepted answer:

@SuppressWarnings("serial")
@WebServlet("/")
@MultipartConfig
public final class DataCollectionServlet extends Controller {

    private static final String UPLOAD_LOCATION_PROPERTY_KEY="upload.location";
    private String uploadsDirName;

    @Override
    public void init() throws ServletException {
        super.init();
        uploadsDirName = property(UPLOAD_LOCATION_PROPERTY_KEY);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // ...
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        Collection<Part> parts = req.getParts();
        for (Part part : parts) {
            File save = new File(uploadsDirName, getFilename(part) + "_"
                + System.currentTimeMillis());
            final String absolutePath = save.getAbsolutePath();
            log.debug(absolutePath);
            part.write(absolutePath);
            sc.getRequestDispatcher(DATA_COLLECTION_JSP).forward(req, resp);
        }
    }

    // helpers
    private static String getFilename(Part part) {
        // courtesy of BalusC : http://stackoverflow.com/a/2424824/281545
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim()
                        .replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1)
                        .substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }
}

where :

@SuppressWarnings("serial")
class Controller extends HttpServlet {

    static final String DATA_COLLECTION_JSP="/WEB-INF/jsp/data_collection.jsp";
    static ServletContext sc;
    Logger log;
    // private
    // "/WEB-INF/app.properties" also works...
    private static final String PROPERTIES_PATH = "WEB-INF/app.properties";
    private Properties properties;

    @Override
    public void init() throws ServletException {
        super.init();
        // synchronize !
        if (sc == null) sc = getServletContext();
        log = LoggerFactory.getLogger(this.getClass());
        try {
            loadProperties();
        } catch (IOException e) {
            throw new RuntimeException("Can't load properties file", e);
        }
    }

    private void loadProperties() throws IOException {
        try(InputStream is= sc.getResourceAsStream(PROPERTIES_PATH)) {
                if (is == null)
                    throw new RuntimeException("Can't locate properties file");
                properties = new Properties();
                properties.load(is);
        }
    }

    String property(final String key) {
        return properties.getProperty(key);
    }
}

and the /WEB-INF/app.properties :

upload.location=C:/_/

HTH and if you find a bug let me know

Batch file to copy files from one folder to another folder

You may want to take a look at XCopy or RoboCopy which are pretty comprehensive solutions for nearly all file copy operations on Windows.

pypi UserWarning: Unknown distribution option: 'install_requires'

This was the first result on my google search, but had no answer. I found that upgrading setuptools resolved the issue for me (and pip for good measure)

pip install --upgrade pip
pip install --upgrade setuptools

Hope this helps the next person to find this link!

Convert date time string to epoch in Bash

For Linux Run this command

date -d '06/12/2012 07:21:22' +"%s"

For mac OSX run this command

date -j -u -f "%a %b %d %T %Z %Y" "Tue Sep 28 19:35:15 EDT 2010" "+%s"

Get selected item value from Bootstrap DropDown with specific ID

You might want to modify your jQuery code a bit to '#demolist li a' so it specifically selects the text that is in the link rather than the text that is in the li element. That would allow you to have a sub-menu without causing issues. Also since your are specifically selecting the a tag you can access it with $(this).text();.

$('#datebox li a').on('click', function(){
    //$('#datebox').val($(this).text());
    alert($(this).text());
});

How to print a dictionary line by line in Python?

You have a nested structure, so you need to format the nested dictionary too:

for key, car in cars.items():
    print(key)
    for attribute, value in car.items():
        print('{} : {}'.format(attribute, value))

This prints:

A
color : 2
speed : 70
B
color : 3
speed : 60

Create Log File in Powershell

You might just want to use the new TUN.Logging PowerShell module, this can also send a log mail. Just use the Start-Log and/or Start-MailLog cmdlets to start logging and then just use Write-HostLog, Write-WarningLog, Write-VerboseLog, Write-ErrorLog etc. to write to console and log file/mail. Then call Send-Log and/or Stop-Log at the end and voila, you got your logging. Just install it from the PowerShell Gallery via

Install-Module -Name TUN.Logging

Or just follow the link: https://www.powershellgallery.com/packages/TUN.Logging

Documentation of the module can be found here: https://github.com/echalone/TUN/blob/master/PowerShell/Modules/TUN.Logging/TUN.Logging.md

Is there a short contains function for lists?

The list method index will return -1 if the item is not present, and will return the index of the item in the list if it is present. Alternatively in an if statement you can do the following:

if myItem in list:
    #do things

You can also check if an element is not in a list with the following if statement:

if myItem not in list:
    #do things

SVN checkout the contents of a folder, not the folder itself

Provide the directory on the command line:

svn checkout file:///home/landonwinters/svn/waterproject/trunk public_html

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

You can set HorizontalAlignment to Left, set your MaxWidth and then bind Width to the ActualWidth of the parent element:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <StackPanel Name="Container">   
    <TextBox Background="Azure" 
    Width="{Binding ElementName=Container,Path=ActualWidth}"
    Text="Hello" HorizontalAlignment="Left" MaxWidth="200" />
  </StackPanel>
</Page>

cd into directory without having permission

Alternatively, you can do:

sudo -s
cd directory

How does the communication between a browser and a web server take place?

There is a commercial product with an interesting logo which lets you see all kind of traffic between server and client named charles.

Another open source tools include: Live HttpHeaders, Wireshark or Firebug.

How to create JSON object Node.js

What I believe you're looking for is a way to work with arrays as object values:

var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into


var data = {
    sampleTime: '1450632410296',
    data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
    sampleTime: '1450632410296',
    data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);

This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify:

JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'

Rubymine: How to make Git ignore .idea files created by Rubymine

if a file is already being tracked by Git, adding the file to .gitignore won’t stop Git from tracking it. You’ll need to do git rm the offending file(s) first, then add to your .gitignore.

Adding .idea/ should work

How to run an awk commands in Windows?

You can download and run the setup file. This should install your AWK in "C:\Program Files (x86)\GnuWin32". You can run the awk or gawk command from the bin folder or add the folder ``C:\Program Files (x86)\GnuWin32\binto yourPATH`.

enter image description here

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

Can I change the fill color of an svg path with CSS?

It's possible to change the path fill color of the svg. See below for the CSS snippet:

  1. To apply the color for all the path: svg > path{ fill: red }

  2. To apply for the first d path: svg > path:nth-of-type(1){ fill: green }

  3. To apply for the second d path: svg > path:nth-of-type(2){ fill: green}

  4. To apply for the different d path, change only the path number:
    svg > path:nth-of-type(${path_number}){ fill: green}

  5. To support the CSS in Angular 2 to 8, use the encapsulation concept:

:host::ng-deep svg path:nth-of-type(1){
        fill:red;
    }

jQuery: read text file from file system

This is working fine in firefox at least.

The problem I was facing is, that I got an XML object in stead of a plain text string. Reading an xml-file from my local drive works fine (same directory as the html), so I do not see why reading a text file would be an issue.

I figured that I need to tell jquery to pass a string in stead of an XML object. Which is what I did, and it finally worked:

function readFiles()
{
    $.get('file.txt', function(data) {
        alert(data);
    }, "text");
}

Note the addition of '"text"' at the end. This tells jquery to pass the contents of 'file.txt' as a string in stead of an XML object. The alert box will show the contents of the text file. If you remove the '"text"' at the end, the alert box will say 'XML object'.

What's the difference between echo, print, and print_r in PHP?

echo

Not having return type

print

Have return type

print_r()

Outputs as formatted,

How to use putExtra() and getExtra() for string data

You can Simply use static variable to store the string of your edittext and then use that variable in the other class. Hope this will solve your problem

Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

Microsoft now recommends using an IHttpClientFactory with the following benefits:

  • Provides a central location for naming and configuring logical HttpClient instances. For example, a client named github could be registered and configured to access GitHub. A default client can be registered for general access.
  • Codifies the concept of outgoing middleware via delegating handlers in HttpClient. Provides extensions for Polly-based middleware to take advantage of delegating handlers in HttpClient.
  • Manages the pooling and lifetime of underlying HttpClientMessageHandler instances. Automatic management avoids common DNS (Domain Name System) problems that occur when manually managing HttpClient lifetimes.
  • Adds a configurable logging experience (via ILogger) for all requests sent through clients created by the factory.

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1

Setup:

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpClient();
        // Remaining code deleted for brevity.

POST example:

public class BasicUsageModel : PageModel
{
    private readonly IHttpClientFactory _clientFactory;

    public BasicUsageModel(IHttpClientFactory clientFactory)
    {
        _clientFactory = clientFactory;
    }
    
    public async Task CreateItemAsync(TodoItem todoItem)
    {
        var todoItemJson = new StringContent(
            JsonSerializer.Serialize(todoItem, _jsonSerializerOptions),
            Encoding.UTF8,
            "application/json");
            
        var httpClient = _clientFactory.CreateClient();
        
        using var httpResponse =
            await httpClient.PostAsync("/api/TodoItems", todoItemJson);
    
        httpResponse.EnsureSuccessStatusCode();
    }

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.1#make-post-put-and-delete-requests

Convert Json string to Json object in Swift 4

I used below code and it's working fine for me. :

let jsonText = "{\"userName\":\"Bhavsang\"}"
var dictonary:NSDictionary?
    
if let data = jsonText.dataUsingEncoding(NSUTF8StringEncoding) {
        
     do {
            dictonary =  try NSJSONSerialization.JSONObjectWithData(data, options: [.allowFragments]) as? [String:AnyObject]
        
            if let myDictionary = dictonary
              {
                  print(" User name is: \(myDictionary["userName"]!)")
              }
            } catch let error as NSError {
            
            print(error)
         }
}

How to disable logging on the standard error stream in Python?

Using Context manager - [ most simple ]

import logging 

class DisableLogger():
    def __enter__(self):
       logging.disable(logging.CRITICAL)
    def __exit__(self, exit_type, exit_value, exit_traceback):
       logging.disable(logging.NOTSET)

Example of use:

with DisableLogger():
    do_something()

If you need a [more COMPLEX] fine-grained solution you can look at AdvancedLogger

AdvancedLogger can be used for fine grained logging temporary modifications

How it works:
Modifications will be enabled when context_manager/decorator starts working and be reverted after

Usage:
AdvancedLogger can be used
- as decorator `@AdvancedLogger()`
- as context manager `with  AdvancedLogger():`

It has three main functions/features:
- disable loggers and it's handlers by using disable_logger= argument
- enable/change loggers and it's handlers by using enable_logger= argument
- disable specific handlers for all loggers, by using  disable_handler= argument

All features they can be used together

Use cases for AdvancedLogger

# Disable specific logger handler, for example for stripe logger disable console
AdvancedLogger(disable_logger={"stripe": "console"})
AdvancedLogger(disable_logger={"stripe": ["console", "console2"]})

# Enable/Set loggers
# Set level for "stripe" logger to 50
AdvancedLogger(enable_logger={"stripe": 50})
AdvancedLogger(enable_logger={"stripe": {"level": 50, "propagate": True}})

# Adjust already registered handlers
AdvancedLogger(enable_logger={"stripe": {"handlers": "console"}

How to close <img> tag properly?

Unfortunately the above solutions did not work in my case - maybe because a put the button inside a form-tag. This code ...

<input class="button" type="submit" value=" ">
    <img src="../assets/logo.png" alt="test" />
</input>

... always leads to error (with or without the closing slash of the img tag):

error  Parsing error: x-invalid-end-tag  vue/no-parsing-error

? 1 problem (1 error, 0 warnings)

A kind of workaround that did work was to define the image as background-image by means of css.

The html snippet describes the button only. The value attribute contains a single blank in order to suppress some browsers presenting unwanted default text.

<input class="button" type="submit" value=" " />

the CSS defines the button's background image:

.button {
  display: block;
  width: 6em;
  height: 6em;
  color: white;
  background-color: #639f59;
  padding: 0.4em 1.2em;
  box-shadow: inset 0 -0.6em 1em -0.35em rgba(5, 122, 11, 0.30),
    inset 0 0.6em 2em -0.3em rgba(255, 255, 255, 0.30),
    inset 0 0 0em 0.05em rgba(255, 255, 255, 0.30);
  cursor: pointer;
  background: url("../assets/logo.png") ;
  background-repeat: no-repeat;
  background-size: 6em;
  background-position: center;
  border: 0;
  border-radius: 3em;
}

What does 'wb' mean in this code, using Python?

That is the mode with which you are opening the file. "wb" means that you are writing to the file (w), and that you are writing in binary mode (b).

Check out the documentation for more: clicky

ExecJS and could not find a JavaScript runtime

I had a similar problem: my Rails 3.1 app worked fine on Windows but got the same error as the OP when running on Linux. The fix that worked for me on both platforms was to add the following to my Gemfile:

gem 'therubyracer', :platforms => :ruby

The trick is knowing that :platforms => :ruby actually means only use this gem with "C Ruby (MRI) or Rubinius, but NOT Windows."

Other possible values for :platforms are described in the bundler man page.

FYI: Windows has a builtin JavaScript engine which execjs can locate. On Linux there is not a builtin although there are several available that one can install. therubyracer is one of them. Others are listed in the execjs README.md.

Java SSLException: hostname in certificate didn't match

Updating the java version from 1.8.0_40 to 1.8.0_181 resolved the issue.

ConfigurationManager.AppSettings - How to modify and save?

Perhaps you should look at adding a Settings File. (e.g. App.Settings) Creating this file will allow you to do the following:

string mysetting = App.Default.MySetting;
App.Default.MySetting = "my new setting";

This means you can edit and then change items, where the items are strongly typed, and best of all... you don't have to touch any xml before you deploy!

The result is a Application or User contextual setting.

Have a look in the "add new item" menu for the setting file.

jQuery Toggle Text?

Improving and Simplifying @Nate's answer:

jQuery.fn.extend({
    toggleText: function (a, b){
        var that = this;
            if (that.text() != a && that.text() != b){
                that.text(a);
            }
            else
            if (that.text() == a){
                that.text(b);
            }
            else
            if (that.text() == b){
                that.text(a);
            }
        return this;
    }
});

Use as:

$("#YourElementId").toggleText('After', 'Before');

How to update json file with python

def updateJsonFile():
    jsonFile = open("replayScript.json", "r") # Open the JSON file for reading
    data = json.load(jsonFile) # Read the JSON into the buffer
    jsonFile.close() # Close the JSON file

    ## Working with buffered content
    tmp = data["location"] 
    data["location"] = path
    data["mode"] = "replay"

    ## Save our changes to JSON file
    jsonFile = open("replayScript.json", "w+")
    jsonFile.write(json.dumps(data))
    jsonFile.close()

What is 'Currying'?

As all other answers currying helps to create partially applied functions. Javascript does not provide native support for automatic currying. So the examples provided above may not help in practical coding. There is some excellent example in livescript (Which essentially compiles to js) http://livescript.net/

times = (x, y) --> x * y
times 2, 3       #=> 6 (normal use works as expected)
double = times 2
double 5         #=> 10

In above example when you have given less no of arguments livescript generates new curried function for you (double)

Eclipse: The declared package does not match the expected package

For me the issue was that I was converting an existing project to maven, created the folder structures according to the documentation and it was showing the 'main' folder as part of the package. I followed the instructions similar to Jon Skeet / JWoodchuck and went into the Java build path, removed all broken build paths, and then added my build path to be 'src/main/java' and 'src/test/java', as well as the resources folders for each, and it resolved the issue.

Remove useless zero digits from decimals in PHP

Due to this question is old. First, I'm sorry about this.

The question is about number xxx.xx but in case that it is x,xxx.xxxxx or difference decimal separator such as xxxx,xxxx this can be harder to find and remove zero digits from decimal value.

/**
 * Remove zero digits from decimal value.
 * 
 * @param string|int|float $number The number can be any format, any where use in the world such as 123, 1,234.56, 1234.56789, 12.345,67, -98,765.43
 * @param string The decimal separator. You have to set this parameter to exactly what it is. For example: in Europe it is mostly use "," instead of ".".
 * @return string Return removed zero digits from decimal value.
 */
function removeZeroDigitsFromDecimal($number, $decimal_sep = '.')
{
    $explode_num = explode($decimal_sep, $number);
    if (is_array($explode_num) && isset($explode_num[count($explode_num)-1]) && intval($explode_num[count($explode_num)-1]) === 0) {
        unset($explode_num[count($explode_num)-1]);
        $number = implode($decimal_sep, $explode_num);
    }
    unset($explode_num);
    return (string) $number;
}

And here is the code for test.

$numbers = [
    1234,// 1234
    -1234,// -1234
    '12,345.67890',// 12,345.67890
    '-12,345,678.901234',// -12,345,678.901234
    '12345.000000',// 12345
    '-12345.000000',// -12345
    '12,345.000000',// 12,345
    '-12,345.000000000',// -12,345
];
foreach ($numbers as $number) {
    var_dump(removeZeroDigitsFromDecimal($number));
}


echo '<hr>'."\n\n\n";


$numbers = [
    1234,// 12324
    -1234,// -1234
    '12.345,67890',// 12.345,67890
    '-12.345.678,901234',// -12.345.678,901234
    '12345,000000',// 12345
    '-12345,000000',// -12345
    '12.345,000000',// 12.345
    '-12.345,000000000',// -12.345
    '-12.345,000000,000',// -12.345,000000 STRANGE!! but also work.
];
foreach ($numbers as $number) {
    var_dump(removeZeroDigitsFromDecimal($number, ','));
}

A Windows equivalent of the Unix tail command

Another option would be to install MSYS (which is more leightweight than Cygwin).

Center content in responsive bootstrap navbar

Use following html

<link rel="stylesheet" href="app/components/directives/navBar/navBar.scss"/>
<nav class="navbar navbar-default" role="navigation">
    <div class="container-fluid">
        <!-- Collect the nav links, forms, and other content for toggling -->
            <ul class="nav navbar-nav">
                <li><h5><a href="#/">Home</a></h5></li>
                <li>|</li>
                <li><h5><a href="#products">About</a></h5></li>
                <li>|</li>
                <li><h5><a href="#">Contacts</a></h5></li>
                <li>|</li>
                <li><h5><a href="#cart">Cart</a></h5></li>
            </ul>
    </div><!-- /.container-fluid -->
</nav>

And css

.navbar-nav {
  width: 100%;
  text-align: center;
}
.navbar-nav > li {
  float: none;
  display: inline-block;
}
.navbar-default {
  background-color: white;
  border-color: white;
}
.navbar-default .navbar-nav>.active>a, .navbar-default .navbar-nav>.active>a:hover, .navbar-default .navbar-nav>.active>a:focus{
  background-color:white;
}

Modify according to your needs

Moving Git repository content to another repository preserving history

I think the commands you are looking for are:

cd repo2
git checkout master
git remote add r1remote **url-of-repo1**
git fetch r1remote
git merge r1remote/master --allow-unrelated-histories
git remote rm r1remote

After that repo2/master will contain everything from repo2/master and repo1/master, and will also have the history of both of them.

jQuery UI - Close Dialog When Clicked Outside

I had same problem while making preview modal on one page. After a lot of googling I found this very useful solution. With event and target it is checking where click happened and depending on it triggers the action or does nothing.

Code Snippet Library site

$('#modal-background').mousedown(function(e) {
var clicked = $(e.target);  
if (clicked.is('#modal-content') || clicked.parents().is('#modal-content')) 
    return; 
} else {  
 $('#modal-background').hide();
}
});

Is there a way to detect if a browser window is not currently active?

var visibilityChange = (function (window) {
    var inView = false;
    return function (fn) {
        window.onfocus = window.onblur = window.onpageshow = window.onpagehide = function (e) {
            if ({focus:1, pageshow:1}[e.type]) {
                if (inView) return;
                fn("visible");
                inView = true;
            } else if (inView) {
                fn("hidden");
                inView = false;
            }
        };
    };
}(this));

visibilityChange(function (state) {
    console.log(state);
});

http://jsfiddle.net/ARTsinn/JTxQY/

Node.js: printing to console without a trailing newline?

None of these solutions work for me, process.stdout.write('ok\033[0G') and just using '\r' just create a new line but don't overwrite on Mac OSX 10.9.2.

EDIT: I had to use this to replace the current line:

process.stdout.write('\033[0G');
process.stdout.write('newstuff');

HTML forms - input type submit problem with action=URL when URL contains index.aspx

Put the query arguments in hidden input fields:

<form action="http://spufalcons.com/index.aspx">
    <input type="hidden" name="tab" value="gymnastics" />
    <input type="hidden" name="path" value="gym" />
    <input type="submit" value="SPU Gymnastics"/>
</form>

Does Python have “private” variables in classes?

The only time I ever use private variables is when I need to do other things when writing to or reading from the variable and as such I need to force the use of a setter and/or getter.

Again this goes to culture, as already stated. I've been working on projects where reading and writing other classes variables was free-for-all. When one implementation became deprecated it took a lot longer to identify all code paths that used that function. When use of setters and getters was forced, a debug statement could easily be written to identify that the deprecated method had been called and the code path that calls it.

When you are on a project where anyone can write an extension, notifying users about deprecated methods that are to disappear in a few releases hence is vital to keep module breakage at a minimum upon upgrades.

So my answer is; if you and your colleagues maintain a simple code set then protecting class variables is not always necessary. If you are writing an extensible system then it becomes imperative when changes to the core is made that needs to be caught by all extensions using the code.

Concatenate rows of two dataframes in pandas

call concat and pass param axis=1 to concatenate column-wise:

In [5]:

pd.concat([df_a,df_b], axis=1)
Out[5]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

There is a useful guide to the various methods of merging, joining and concatenating online.

For example, as you have no clashing columns you can merge and use the indices as they have the same number of rows:

In [6]:

df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

And for the same reasons as above a simple join works too:

In [7]:

df_a.join(df_b)
Out[7]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

Java SSLHandshakeException "no cipher suites in common"

I got this error with this ... unfortunate... package I have to use and I don't have source for. After much digging (thank you, Stack Overflow) and trying endless combinations, I finally got things running by:

  1. Creating the JKS with the entire certificate chain.

  2. Making sure the key in the JKS had the alias of the FQDN of the machine.

  3. Renaming the alias of the certificate for my machine ${FQDN}.cert

This took endless experimentation with the java command line options:

-Djavax.net.debug=ssl:handshake:verbose:keymanager:trustmanager 
-Djava.security.debug=access:stack

My key and CSR were produced in OpenSSL so I had to import the key with:

openssl pkcs12 -export -in  cert.pem -inkey  cert.key -CAfile fullChain.pem -name ${FQDN} -out cert.p12
keytool -importkeystore -destkeystore cert.jks -srckeystore cert.p12 -srcstoretype PKCS12

keytool complains about the format so I converted the format followed by adding my cert chain:

keytool -importkeystore -srckeystore cert.jks -destkeystore cert_p12.jks -deststoretype pkcs12
keytool -import -trustcacerts -alias 'DigiCert Global Root G2 IntermediateCA' -keystore cert_p12.jks -file cert2.pem -storepass "$STOREPASS" -keypass "$KEYPASS" 
keytool -import -trustcacerts -alias 'DigiCert Global Root G2'                -keystore cert_p12.jks -file cert3.pem -storepass "$STOREPASS" -keypass "$KEYPASS"

(where cert2.pem and cert3.pem were downloaded from the DigiCert web site and converted to PEM format.) When I restarted the application with the resulting jks file, things started to work.

Something else I figured out as part of this. You can check the certificate chain by using:

openssl x509 -in cert2.pem -noout -text

for all your certificates and studying the output, paying attention to the X509v3 Authority Key Identifier: and X509v3 Authority Key Identifier: lines. The X509v3 Authority Key Identifier: of one level matches the X509v3 Subject Key Identifier: of the next higher level. You found the top of chain when the Issuer: string matches the Subject: string.

I hope this can save somebody some of the time it took me.

How to hide a column (GridView) but still access its value?

Here is how to get the value of a hidden column in a GridView that is set to Visible=False: add the data field in this case SpecialInstructions to the DataKeyNames property of the bound GridView , and access it this way.

txtSpcInst.Text = GridView2.DataKeys(GridView2.SelectedIndex).Values("SpecialInstructions")

That's it, it works every time very simple.

npm throws error without sudo

As if we need more answers here, but anyway..

Sindre Sorus has a guide Install npm packages globally without sudo on OS X and Linux outlining how to cleanly install without messing with permissions:

Here is a way to install packages globally for a given user.

  1. Create a directory for your global packages

    mkdir "${HOME}/.npm-packages"
    
  2. Reference this directory for future usage in your .bashrc/.zshrc:

    NPM_PACKAGES="${HOME}/.npm-packages"
    
  3. Indicate to npm where to store your globally installed package. In your $HOME/.npmrc file add:

    prefix=${HOME}/.npm-packages
    
  4. Ensure node will find them. Add the following to your .bashrc/.zshrc:

    NODE_PATH="$NPM_PACKAGES/lib/node_modules:$NODE_PATH"
    
  5. Ensure you'll find installed binaries and man pages. Add the following to your .bashrc/.zshrc:

    PATH="$NPM_PACKAGES/bin:$PATH"
    # Unset manpath so we can inherit from /etc/manpath via the `manpath`
    # command
    unset MANPATH # delete if you already modified MANPATH elsewhere in your config
    MANPATH="$NPM_PACKAGES/share/man:$(manpath)"
    

Check out npm-g_nosudo for doing the above steps automagically

Checkout the source of this guide for the latest updates.

Split string with multiple delimiters in Python

In response to Jonathan's answer above, this only seems to work for certain delimiters. For example:

>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']

>>> b='1999-05-03 10:37:00'
>>> re.split('- :', b)
['1999-05-03 10:37:00']

By putting the delimiters in square brackets it seems to work more effectively.

>>> re.split('[- :]', b)
['1999', '05', '03', '10', '37', '00']

How to get these two divs side-by-side?

#parent_div_1, #parent_div_2, #parent_div_3 {
  width: 100px;
  height: 100px;
  border: 1px solid red;
  margin-right: 10px;
  float: left;
}
.child_div_1 {
  float: left;
  margin-right: 5px;
}

Check working example at http://jsfiddle.net/c6242/1/

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

Sometimes this happens when you download a project from github or other third party tutorial sites.These apps are usually signed with a different identity or company/name.When this happens,if you can't solve the solution,simply create a new xcode project and copy all the header and implementation files into your new project.Also don't forget the dependency files..such as the framework files.This works for me.

How to clear https proxy setting of NPM?

npm config delete proxy -g

worked for me.

-g was important as initially it was set with that option. You can check configurations set with :

npm config list

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

Python datetimes are a little clunky. Use arrow.

> str(arrow.utcnow())
'2014-05-17T01:18:47.944126+00:00'

Arrow has essentially the same api as datetime, but with timezones and some extra niceties that should be in the main library.

A format compatible with Javascript can be achieved by:

arrow.utcnow().isoformat().replace("+00:00", "Z")
'2018-11-30T02:46:40.714281Z'

Javascript Date.parse will quietly drop microseconds from the timestamp.

g++ undefined reference to typeinfo

In my case it is purely a library dependency issue even if I have dynamic_cast call. After adding enough dependency into makefile this problem was gone.

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

Splitting a C++ std::string using tokens, e.g. ";"

There are several libraries available solving this problem, but the simplest is probably to use Boost Tokenizer:

#include <iostream>
#include <string>
#include <boost/tokenizer.hpp>
#include <boost/foreach.hpp>

typedef boost::tokenizer<boost::char_separator<char> > tokenizer;

std::string str("denmark;sweden;india;us");
boost::char_separator<char> sep(";");
tokenizer tokens(str, sep);

BOOST_FOREACH(std::string const& token, tokens)
{
    std::cout << "<" << *tok_iter << "> " << "\n";
}

String isNullOrEmpty in Java?

If you are doing android development, you can use:

TextUtils.isEmpty (CharSequence str) 

Added in API level 1 Returns true if the string is null or 0-length.

How do I convert strings between uppercase and lowercase in Java?

Yes. There are methods on the String itself for this.

Note that the result depends on the Locale the JVM is using. Beware, locales is an art in itself.

Can Json.NET serialize / deserialize to / from a stream?

The current version of Json.net does not allow you to use the accepted answer code. A current alternative is:

public static object DeserializeFromStream(Stream stream)
{
    var serializer = new JsonSerializer();

    using (var sr = new StreamReader(stream))
    using (var jsonTextReader = new JsonTextReader(sr))
    {
        return serializer.Deserialize(jsonTextReader);
    }
}

Documentation: Deserialize JSON from a file stream

Any good boolean expression simplifiers out there?

Try Logic Friday 1 It includes tools from the Univerity of California (Espresso and misII) and makes them usable with a GUI. You can enter boolean equations and truth tables as desired. It also features a graphical gate diagram input and output.

The minimization can be carried out two-level or multi-level. The two-level form yields a minimized sum of products. The multi-level form creates a circuit composed out of logical gates. The types of gates can be restricted by the user.

Your expression simplifies to C.

Define variable to use with IN operator (T-SQL)

slight improvement on @LukeH, there is no need to repeat the "INSERT INTO": and @realPT's answer - no need to have the SELECT:

DECLARE @MyList TABLE (Value INT) 
INSERT INTO @MyList VALUES (1),(2),(3),(4)

SELECT * FROM MyTable
WHERE MyColumn IN (SELECT Value FROM @MyList)

How to get jSON response into variable from a jquery script

Look out for this pitfal: http://www.vertstudios.com/blog/avoiding-ajax-newline-pitfall/

Searched several houres before I found there were some linebreaks in the included files.

Java abstract interface

Every interface is implicitly abstract.
This modifier is obsolete and should not be used in new programs.

[The Java Language Specification - 9.1.1.1 abstract Interfaces]

Also note that interface member methods are implicitly public abstract.
[The Java Language Specification - 9.2 Interface Members]

Why are those modifiers implicit? There is no other modifier (not even the 'no modifier'-modifier) that would be useful here, so you don't explicitly have to type it.

How to listen to the window scroll event in a VueJS component?

document.addEventListener('scroll', function (event) {
    if ((<HTMLInputElement>event.target).id === 'latest-div') { // or any other filtering condition
  
    }
}, true /*Capture event*/);

You can use this to capture an event and and here "latest-div" is the id name so u can capture all scroller action here based on the id you can do the action as well inside here.

Is it possible to import a whole directory in sass using @import?

With defining the file to import it's possible to use all folders common definitions.

So, @import "style/*" will compile all the files in the style folder.

More about import feature in Sass you can find here.

Anaconda export Environment file

  • Linux

    conda env export --no-builds | grep -v "prefix" > environment.yml

  • Windows

    conda env export --no-builds | findstr -v "prefix" > environment.yml


Rationale: By default, conda env export includes the build information:

$ conda env export
...
dependencies:
  - backcall=0.1.0=py37_0
  - blas=1.0=mkl
  - boto=2.49.0=py_0
...

You can instead export your environment without build info:

$ conda env export --no-builds
...
dependencies:
  - backcall=0.1.0
  - blas=1.0
  - boto=2.49.0
...

Which unties the environment from the Python version and OS.

Pass accepts header parameter to jquery ajax

There two alternate ways to set accept header, which are as below:

1) setRequestHeader('Accept','application/json; charset=utf-8');

2) $.ajax({
    dataType: ($.browser.msie) ? "text" : "json",
    accepts: {
        text: "application/json"
    }
});

AttributeError: 'module' object has no attribute 'model'

As the error message says in the last line: the module models in the file c:\projects\mysite..\mysite\polls\models.py contains no class model. This error occurs in the definition of the Poll class:

class Poll(models.model):

Either the class model is misspelled in the definition of the class Poll or it is misspelled in the module models. Another possibility is that it is completely missing from the module models. Maybe it is in another module or it is not yet implemented in models.

How to find a value in an excel column by vba code Cells.Find

Dim strFirstAddress As String
Dim searchlast As Range
Dim search As Range

Set search = ActiveSheet.Range("A1:A100")
Set searchlast = search.Cells(search.Cells.Count)

Set rngFindValue = ActiveSheet.Range("A1:A100").Find(Text, searchlast, xlValues)
If Not rngFindValue Is Nothing Then
  strFirstAddress = rngFindValue.Address
  Do
    Set rngFindValue = search.FindNext(rngFindValue)
  Loop Until rngFindValue.Address = strFirstAddress

Inserting a string into a list without getting split into characters

You have to add another list:

list[:0]=['foo']

How do I check whether a checkbox is checked in jQuery?

For older versions of jQuery, I had to use following,

$('#change_plan').live('click', function() {
     var checked = $('#change_plan').attr('checked');
     if(checked) {
          //Code       
     }
     else {
          //Code       
     }
});

Shadow Effect for a Text in Android?

TextView textv = (TextView) findViewById(R.id.textview1);
textv.setShadowLayer(1, 0, 0, Color.BLACK);

How to change dataframe column names in pyspark?

df.withColumnRenamed('age', 'age2')

ssh remote host identification has changed

Remove that the entry from known_hosts using:

ssh-keygen -R *ip_address_or_hostname*

This will remove the problematic IP or hostname from known_hosts file and try to connect again.

From the man pages:

-R hostname
Removes all keys belonging to hostname from a known_hosts file. This option is useful to delete hashed hosts (see the -H option above).

How to save an image to localStorage and display it on the next page?

If your images keep getting cropped, here's some code to get the dimensions of the image file before saving to localstorage.

First, I would create some hidden input boxes to hold the width and height values

<input id="file-h" hidden type="text"/>
<input id="file-w" hidden type="text"/>

Then get the dimensions of your file into the input boxes

var _URL = window.URL || window.webkitURL;
$("#file-input").change(function(e) {
    var file, img;
    if ((file = this.files[0])) {
        img = new Image();
        img.onload = function() {
            $("#file-h").val(this.height);
            $("#file-w").val(this.width);
        };
        img.onerror = function() {
            alert( "not a valid file: " + file.type);
        };
        img.src = _URL.createObjectURL(file);
    }
});

Lastly, change the width and height objects used in the getBase64Image() function by pointing to your input box values

FROM

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;

TO

function getBase64Image(img) {
    var canvas = document.createElement("canvas");
    canvas.width = $("#file-w").val();
    canvas.height = $("#file-h").val();

Also, you are going to have to maintain a size of about 300kb for all files. There are posts on stackoverflow that cover file size validation using Javascript.

How do you get the file size in C#?

If you have already a file path as input, this is the code you need:

long length = new System.IO.FileInfo(path).Length;

Create a folder inside documents folder in iOS apps

I don't like "[paths objectAtIndex:0]" because if Apple adds a new folder starting with "A", "B" oder "C", the "Documents"-folder isn't the first folder in the directory.

Better:

NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/MyFolder"];
if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:NO attributes:nil error:&error]; //Create folder

How to fix ReferenceError: primordials is not defined in node

I was also getting error on Node 12/13 with Gulp 3, moving to Node 11 worked.

Write single CSV file using spark-csv

This answer expands on the accepted answer, gives more context, and provides code snippets you can run in the Spark Shell on your machine.

More context on accepted answer

The accepted answer might give you the impression the sample code outputs a single mydata.csv file and that's not the case. Let's demonstrate:

val df = Seq("one", "two", "three").toDF("num")
df
  .repartition(1)
  .write.csv(sys.env("HOME")+ "/Documents/tmp/mydata.csv")

Here's what's outputted:

Documents/
  tmp/
    mydata.csv/
      _SUCCESS
      part-00000-b3700504-e58b-4552-880b-e7b52c60157e-c000.csv

N.B. mydata.csv is a folder in the accepted answer - it's not a file!

How to output a single file with a specific name

We can use spark-daria to write out a single mydata.csv file.

import com.github.mrpowers.spark.daria.sql.DariaWriters
DariaWriters.writeSingleFile(
    df = df,
    format = "csv",
    sc = spark.sparkContext,
    tmpFolder = sys.env("HOME") + "/Documents/better/staging",
    filename = sys.env("HOME") + "/Documents/better/mydata.csv"
)

This'll output the file as follows:

Documents/
  better/
    mydata.csv

S3 paths

You'll need to pass s3a paths to DariaWriters.writeSingleFile to use this method in S3:

DariaWriters.writeSingleFile(
    df = df,
    format = "csv",
    sc = spark.sparkContext,
    tmpFolder = "s3a://bucket/data/src",
    filename = "s3a://bucket/data/dest/my_cool_file.csv"
)

See here for more info.

Avoiding copyMerge

copyMerge was removed from Hadoop 3. The DariaWriters.writeSingleFile implementation uses fs.rename, as described here. Spark 3 still used Hadoop 2, so copyMerge implementations will work in 2020. I'm not sure when Spark will upgrade to Hadoop 3, but better to avoid any copyMerge approach that'll cause your code to break when Spark upgrades Hadoop.

Source code

Look for the DariaWriters object in the spark-daria source code if you'd like to inspect the implementation.

PySpark implementation

It's easier to write out a single file with PySpark because you can convert the DataFrame to a Pandas DataFrame that gets written out as a single file by default.

from pathlib import Path
home = str(Path.home())
data = [
    ("jellyfish", "JALYF"),
    ("li", "L"),
    ("luisa", "LAS"),
    (None, None)
]
df = spark.createDataFrame(data, ["word", "expected"])
df.toPandas().to_csv(home + "/Documents/tmp/mydata-from-pyspark.csv", sep=',', header=True, index=False)

Limitations

The DariaWriters.writeSingleFile Scala approach and the df.toPandas() Python approach only work for small datasets. Huge datasets can not be written out as single files. Writing out data as a single file isn't optimal from a performance perspective because the data can't be written in parallel.

using sql count in a case statement

select sum(rsp_ind = 0) as `New`,
       sum(rsp_ind = 1) as `Accepted` 
from tb_a

Why does "return list.sort()" return None, not the list?

you can use sorted() method if you want it to return the sorted list. It's more convenient.

l1 = []
n = int(input())

for i in range(n):
  user = int(input())
  l1.append(user)
sorted(l1,reverse=True)

list.sort() method modifies the list in-place and returns None.

if you still want to use sort you can do this.

l1 = []
n = int(input())

for i in range(n):
  user = int(input())
  l1.append(user)
l1.sort(reverse=True)
print(l1)

How to correctly use "section" tag in HTML5?

My understanding is that SECTION holds a section with a heading which is an important part of the "flow" of the page (not an aside). SECTIONs would be chapters, numbered parts of documents and so on.

ARTICLE is for syndicated content -- e.g. posts, news stories etc. ARTICLE and SECTION are completely separate -- you can have one without the other as they are very different use cases.

Another thing about SECTION is that you shouldn't use it if your page has only the one section. Also, each section must have a heading (H1-6, HGROUP, HEADING). Headings are "scoped" withing the SECTION, so e.g. if you use a H1 in the main page (outside a SECTION) and then a H1 inside the section, the latter will be treated as an H2.

The examples in the spec are pretty good at time of writing.

So in your first example would be correct if you had several sections of content which couldn't be described as ARTICLEs. (With a minor point that you wouldn't need the #primary DIV unless you wanted it for a style hook - P tags would be better).

The second example would be correct if you removed all the SECTION tags -- the data in that document would be articles, posts or something like this.

SECTIONs should not be used as containers -- DIV is still the correct use for that, and any other custom box you might come up with.

Shortcut for creating single item list in C#

Use an extension method with method chaining.

public static List<T> WithItems(this List<T> list, params T[] items)
{
    list.AddRange(items);
    return list;
}

This would let you do this:

List<string> strings = new List<string>().WithItems("Yes");

or

List<string> strings = new List<string>().WithItems("Yes", "No", "Maybe So");

Update

You can now use list initializers:

var strings = new List<string> { "This", "That", "The Other" };

See http://msdn.microsoft.com/en-us/library/bb384062(v=vs.90).aspx

How do I remove a MySQL database?

I needed to correct the privileges.REVOKE ALL PRIVILEGES ONlogs.* FROM 'root'@'root'; GRANT ALL PRIVILEGES ONlogs.* TO 'root'@'root'WITH GRANT OPTION;

How to determine the screen width in terms of dp or dip at runtime in Android?

Answer in kotlin:

  context?.let {
        val displayMetrics = it.resources.displayMetrics
        val dpHeight = displayMetrics.heightPixels / displayMetrics.density
        val dpWidth = displayMetrics.widthPixels / displayMetrics.density
    }

What is the definition of "interface" in object oriented programming

An interface defines what a class that inherits from it must implement. In this way, multiple classes can inherit from an interface, and because of that inherticance, you can

  • be sure that all members of the interface are implemented in the derived class (even if its just to throw an exception)
  • Abstract away the class itself from the caller (cast an instance of a class to the interface, and interact with it without needing to know what the actual derived class IS)

for more info, see this http://msdn.microsoft.com/en-us/library/ms173156.aspx

Adding multiple columns AFTER a specific column in MySQL

This works fine for me:

ALTER TABLE 'users'
ADD COLUMN 'count' SMALLINT(6) NOT NULL AFTER 'lastname',
ADD COLUMN 'log' VARCHAR(12) NOT NULL AFTER 'count',
ADD COLUMN 'status' INT(10) UNSIGNED NOT NULL AFTER 'log';

Preloading images with JavaScript

Working solution as of 2020

Most answers on this post no longer work - (atleast on Firefox)

Here's my solution:

var cache = document.createElement("CACHE");
cache.style = "position:absolute;z-index:-1000;opacity:0;";
document.body.appendChild(cache);
function preloadImage(url) {
    var img = new Image();
    img.src = url;
    img.style = "position:absolute";
    cache.appendChild(img);
}

Usage:

preloadImage("example.com/yourimage.png");

Obviously <cache> is not a "defined" element, so you could use a <div> if you wanted to.

Use this in your CSS, instead of applying the style attribute:

cache {
    position: absolute;
    z-index: -1000;
    opacity: 0;
}

cache image {
    position: absolute;
}

If you have tested this, please leave a comment.

Notes:

  • Do NOT apply display: none; to cache - this will not load the image.
  • Don't resize the image element, as this will also affect the quality of the loaded image when you come to use it.
  • Setting position: absolute to the image is necessary, as the image elements will eventually make it's way outside of the viewport - causing them to not load, and affect performance.

UPDATE

While above solution works, here's a small update I made to structure it nicely:

(This also now accepts multiple images in one function)

var cache = document.createElement("CACHE");
document.body.appendChild(cache);
function preloadImage() {
    for (var i=0; i<arguments.length; i++) {
        var img = new Image();
        img.src = arguments[i];
        var parent = arguments[i].split("/")[1]; // Set to index of folder name
        if ($(`cache #${parent}`).length == 0) {
            var ele = document.createElement("DIV");
            ele.id = parent;
            cache.appendChild(ele);
        }
        $(`cache #${parent}`)[0].appendChild(img);
        console.log(parent);
    }
}

preloadImage(
    "assets/office/58.png",
    "assets/leftbutton/124.png",
    "assets/leftbutton/125.png",
    "assets/leftbutton/130.png",
    "assets/leftbutton/122.png",
    "assets/leftbutton/124.png"
);

Preview:

enter image description here

Notes:

  • Try not to keep too many images preloaded at the same time (this can cause major performance issues) - I got around this by hiding images, which I knew wasn't going to be visible during certain events. Then, of course, show them again when I needed it.

Getting a browser's name client-side

It's all about what you really want to do, but in times to come and right now, the best way is avoid browser detection and check for features. like Canvas, Audio, WebSockets, etc through simple javascript calls or in your CSS, for me your best approach is use a tool like ModernizR:

Unlike with the traditional—but highly unreliable—method of doing “UA sniffing,” which is detecting a browser by its (user-configurable) navigator.userAgent property, Modernizr does actual feature detection to reliably discern what the various browsers can and cannot do.

If using CSS, you can do this:

.no-js .glossy,
.no-cssgradients .glossy {
    background: url("images/glossybutton.png");
}

.cssgradients .glossy {
    background-image: linear-gradient(top, #555, #333);
}

as it will load and append all features as a class name in the <html> element and you will be able to do as you wish in terms of CSS.

And you can even load files upon features, for example, load a polyfill js and css if the browser does not have native support

Modernizr.load([
  // Presentational polyfills
  {
    // Logical list of things we would normally need
    test : Modernizr.fontface && Modernizr.canvas && Modernizr.cssgradients,
    // Modernizr.load loads css and javascript by default
    nope : ['presentational-polyfill.js', 'presentational.css']
  },
  // Functional polyfills
  {
    // This just has to be truthy
    test : Modernizr.websockets && window.JSON,
    // socket-io.js and json2.js
    nope : 'functional-polyfills.js',
    // You can also give arrays of resources to load.
    both : [ 'app.js', 'extra.js' ],
    complete : function () {
      // Run this after everything in this group has downloaded
      // and executed, as well everything in all previous groups
      myApp.init();
    }
  },
  // Run your analytics after you've already kicked off all the rest
  // of your app.
  'post-analytics.js'
]);

a simple example of requesting features from javascript:

http://jsbin.com/udoyic/1

What is the naming convention in Python for variable and function names?

There is a paper about this: http://www.cs.kent.edu/~jmaletic/papers/ICPC2010-CamelCaseUnderScoreClouds.pdf

TL;DR It says that snake_case is more readable than camelCase. That's why modern languages use (or should use) snake wherever they can.

How do I concatenate two lists in Python?

It's worth noting that the itertools.chain function accepts variable number of arguments:

>>> l1 = ['a']; l2 = ['b', 'c']; l3 = ['d', 'e', 'f']
>>> [i for i in itertools.chain(l1, l2)]
['a', 'b', 'c']
>>> [i for i in itertools.chain(l1, l2, l3)]
['a', 'b', 'c', 'd', 'e', 'f']

If an iterable (tuple, list, generator, etc.) is the input, the from_iterable class method may be used:

>>> il = [['a'], ['b', 'c'], ['d', 'e', 'f']]
>>> [i for i in itertools.chain.from_iterable(il)]
['a', 'b', 'c', 'd', 'e', 'f']

Redirecting from HTTP to HTTPS with PHP

Try something like this (should work for Apache and IIS):

if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === "off") {
    $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
}

Default property value in React component using TypeScript

You can use the spread operator to re-assign props with a standard functional component. The thing I like about this approach is that you can mix required props with optional ones that have a default value.

interface MyProps {
   text: string;
   optionalText?: string;
}

const defaultProps = {
   optionalText = "foo";
}

const MyComponent = (props: MyProps) => {
   props = { ...defaultProps, ...props }
}

New self vs. new static

If the method of this code is not static, you can get a work-around in 5.2 by using get_class($this).

class A {
    public function create1() {
        $class = get_class($this);
        return new $class();
    }
    public function create2() {
        return new static();
    }
}

class B extends A {

}

$b = new B();
var_dump(get_class($b->create1()), get_class($b->create2()));

The results:

string(1) "B"
string(1) "B"

Naming convention - underscore in C++ and C# variables

I use the _var naming for member variables of my classes. There are 2 main reasons I do:

1) It helps me keep track of class variables and local function variables when I'm reading my code later.

2) It helps in Intellisense (or other code-completion system) when I'm looking for a class variable. Just knowing the first character is helpful in filtering through the list of available variables and methods.

Modify property value of the objects in list using Java 8 streams

You can use just forEach. No stream at all:

fruits.forEach(fruit -> fruit.setName(fruit.getName() + "s"));

How to concatenate characters in java?

this is very simple approach to concatenate or append the character

       StringBuilder desc = new StringBuilder(); 
       String Description="this is my land"; 
       desc=desc.append(Description.charAt(i));

SQL - Create view from multiple tables

Are you using MySQL or PostgreSQL?

You want to use JOIN syntax, not UNION. For example, using INNER JOIN:

CREATE VIEW V AS
SELECT POP.country, POP.year, POP.pop, FOOD.food, INCOME.income
FROM POP
INNER JOIN FOOD ON (POP.country=FOOD.country) AND (POP.year=FOOD.year)
INNER JOIN INCOME ON (POP.country=INCOME.country) AND (POP.year=INCOME.year)

However, this will only show results when each country and year are present in all three tables. If this is not what you want, look into left outer joins (using the same link above).

ClassNotFoundException: org.slf4j.LoggerFactory

Add the following JARs to the build path or lib folder of the project:

  1. slf4j-api-1.7.2.jar
  2. slf4j-jdk14-1.7.2.jar

How can I dynamically switch web service addresses in .NET without a recompile?

I've struggled with this issue for a few days and finally the light bulb clicked. The KEY to being able to change the URL of a webservice at runtime is overriding the constructor, which I did with a partial class declaration. The above, setting the URL behavior to Dynamic must also be done.

This basically creates a web-service wrapper where if you have to reload web service at some point, via add service reference, you don't loose your work. The Microsoft help for Partial classes specially states that part of the reason for this construct is to create web service wrappers. http://msdn.microsoft.com/en-us/library/wa80x488(v=vs.100).aspx

// Web Service Wrapper to override constructor to use custom ConfigSection 
// app.config values for URL/User/Pass
namespace myprogram.webservice
{
    public partial class MyWebService
    {
        public MyWebService(string szURL)
        {
            this.Url = szURL;
            if ((this.IsLocalFileSystemWebService(this.Url) == true))
            {
                this.UseDefaultCredentials = true;
                this.useDefaultCredentialsSetExplicitly = false;
            }
            else
            {
                this.useDefaultCredentialsSetExplicitly = true;
            }
        }
    }
}

Create PDF with Java

I prefer outputting my data into XML (using Castor, XStream or JAXB), then transforming it using a XSLT stylesheet into XSL-FO and render that with Apache FOP into PDF. Worked so far for 10-page reports and 400-page manuals. I found this more flexible and stylable than generating PDFs in code using iText.

Regex to check whether a string contains only numbers

If you want to match the numbers with signed values, you can use:

var reg = new RegExp('^(\-?|\+?)\d*$');

It will validate the numbers of format: +1, -1, 1.

C++ pass an array by reference

As you are using C++, the obligatory suggestion that's still missing here, is to use std::vector<double>.

You can easily pass it by reference:

void foo(std::vector<double>& bar) {}

And if you have C++11 support, also have a look at std::array.

For reference:

Commit only part of a file in Git

If it's on Windows platform, in my opinion git gui is very good tool to stage/commit few lines from unstaged file

1. Hunk wise:

  • Select the file from unstagged Changes section
  • Right click chunk of code which needs to be staged
  • Select Stage Hunk for commit

2. Line wise:

  • Select the file from unstagged Changes section
  • Select the line/lines to be staged
  • Right click and select Stage Lines for commit

3. If you want to stage the complete file except couple of lines:

  • Select the file from unstagged Changes section
  • Press Ctrl+T (Stage file to commit)
  • Selected file now moves to Staged Changes Section
  • Select the line/lines be staged
  • Right click and select UnStage Lines for commit

Execution failed app:processDebugResources Android Studio

There may be some errors in your layouts like android:id="@id/ instead of android:id="@+id/.... At least that was the cause for my exception.

Must issue a STARTTLS command first

Google now has a feature stating that it won't allow insecure devices to send emails. When I ran my program it came up with the error in the first post. I had to go into my account and allow insecure apps to send emails, which I did by clicking on my account, going into the security tab, and allowing insecure apps to use my gmail.

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I had the same issue, I fixed it by using org.hibernate.annotations.Table annotation instead of javax.persistence.Table in the Entity class.

import javax.persistence.Entity;
import org.hibernate.annotations.Table;

@Entity
@Table(appliesTo = "my_table")
public class MyTable{
//and rest of the code

How to trigger event when a variable's value is changed?

you can use generic class:

class Wrapped<T>  {
    private T _value;

    public Action ValueChanged;

    public T Value
    {
        get => _value;

        set
        {
            _value = value;
            OnValueChanged();
        }
    }

    protected virtual void OnValueChanged() => ValueChanged?.Invoke() ;
}

and will be able to do the following:

var i = new Wrapped<int>();

i.ValueChanged += () => { Console.WriteLine("changed!"); };

i.Value = 10;
i.Value = 10;
i.Value = 10;
i.Value = 10;

Console.ReadKey();

result:

changed!
changed!
changed!
changed!
changed!
changed!
changed!

JavaScript Loading Screen while page loads

I would suggest adding class no-js to your html to nest your CSS selectors under it like:

.loading {
    display: none;
 }

.no-js .loading {
 display: block;
 //....
}

and when you finish loading your credit code remove it:

$('html').removeClass('no-js');

This will hide your loading spinner as there's no no-js class in html it means you already loaded your credit code

How to get the mobile number of current sim card in real device?

Well, all could be temporary hacks, but there is no way to get mobile number of a user. It is against ethical policy.

For eg, one of the answers above suggests getting all accounts and extracting from there. And it doesn't work anymore! All of these are hacks only.

Only way to get user's mobile number is going through operator. If you have a tie-up with mobile operators like Aitel, Vodafone, etc, you can get user's mobile number in header of request from mobile handset when connected via mobile network internet.

Not sure if any manufacturer tie ups to get specific permissions can help - not explored this area, but nothing documented atleast.

How to get records randomly from the oracle database?

In case of huge tables standard way with sorting by dbms_random.value is not effective because you need to scan whole table and dbms_random.value is pretty slow function and requires context switches. For such cases, there are 3 additional methods:


1: Use sample clause:

for example:

select *
from s1 sample block(1)
order by dbms_random.value
fetch first 1 rows only

ie get 1% of all blocks, then sort them randomly and return just 1 row.


2: if you have an index/primary key on the column with normal distribution, you can get min and max values, get random value in this range and get first row with a value greater or equal than that randomly generated value.

Example:

--big table with 1 mln rows with primary key on ID with normal distribution:
Create table s1(id primary key,padding) as 
   select level, rpad('x',100,'x')
   from dual 
   connect by level<=1e6;

select *
from s1 
where id>=(select 
              dbms_random.value(
                 (select min(id) from s1),
                 (select max(id) from s1) 
              )
           from dual)
order by id
fetch first 1 rows only;

3: get random table block, generate rowid and get row from the table by this rowid:

select * 
from s1
where rowid = (
   select
      DBMS_ROWID.ROWID_CREATE (
         1, 
         objd,
         file#,
         block#,
         1) 
   from    
      (
      select/*+ rule */ file#,block#,objd
      from v$bh b
      where b.objd in (select o.data_object_id from user_objects o where object_name='S1' /* table_name */)
      order by dbms_random.value
      fetch first 1 rows only
      )
);

How to get the current URL within a Django template?

The other answers were incorrect, at least in my case. request.path does not provide the full url, only the relative url, e.g. /paper/53. I did not find any proper solution, so I ended up hardcoding the constant part of the url in the View before concatenating it with request.path.

How to get input from user at runtime

`DECLARE
c_id customers.id%type := &c_id;
c_name customers.name%type;
c_add customers.address%type;
c_sal customers.salary%type;
a integer := &a`   

Here c_id customers.id%type := &c_id; statement inputs the c_id with type already defined in the table and statement a integer := &a just input integer in variable a.

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

Following the unobtrusive principle, it's not quite required for "_myPartial" to inject content directly into scripts section. You could add those partial view scripts into separate .js file and reference them into @scripts section from parent view.

receiver type *** for instance message is a forward declaration

I got this sort of message when I had two files that depended on each other. The tricky thing here is that you'll get a circular reference if you just try to import each other (class A imports class B, class B imports class A) from their header files. So what you would do is instead place a forward (@class A) declaration in one of the classes' (class B's) header file. However, when attempting to use an ivar of class A within the implementation of class B, this very error comes up, merely adding an #import "A.h" in the .m file of class B fixed the problem for me.

Why can't Python parse this JSON data?

data = []
with codecs.open('d:\output.txt','rU','utf-8') as f:
    for line in f:
       data.append(json.loads(line))

Insert data into a view (SQL Server)

You have created a table with ID as PRIMARY KEY, which satisfies UNIQUE and NOT NULL constraints, so you can't make the ID as NULL by inserting name field, so ID should also be inserted.

The error message indicates this.

Best way to implement multi-language/globalization in large .NET project

I've seen projects implemented using a number of different approaches, each have their merits and drawbacks.

  • One did it in the config file (not my favourite)
  • One did it using a database - this worked pretty well, but was a pain in the you know what to maintain.
  • One used resource files the way you're suggesting and I have to say it was my favourite approach.
  • The most basic one did it using an include file full of strings - ugly.

I'd say the resource method you've chosen makes a lot of sense. It would be interesting to see other people's answers too as I often wonder if there's a better way of doing things like this. I've seen numerous resources that all point to the using resources method, including one right here on SO.

What's the Linq to SQL equivalent to TOP or LIMIT/OFFSET?

Array oList = ((from m in dc.Reviews
                           join n in dc.Users on m.authorID equals n.userID
                           orderby m.createdDate descending
                           where m.foodID == _id                      
                           select new
                           {
                               authorID = m.authorID,
                               createdDate = m.createdDate,
                               review = m.review1,
                               author = n.username,
                               profileImgUrl = n.profileImgUrl
                           }).Take(2)).ToArray();

How to get an element by its href in jquery?

Yes, you can use jQuery's attribute selector for that.

var linksToGoogle = $('a[href="http://google.com"]');

Alternatively, if your interest is rather links starting with a certain URL, use the attribute-starts-with selector:

var allLinksToGoogle = $('a[href^="http://google.com"]');

CSS3 :unchecked pseudo-class

:unchecked is not defined in the Selectors or CSS UI level 3 specs, nor has it appeared in level 4 of Selectors.

In fact, the quote from W3C is taken from the Selectors 4 spec. Since Selectors 4 recommends using :not(:checked), it's safe to assume that there is no corresponding :unchecked pseudo. Browser support for :not() and :checked is identical, so that shouldn't be a problem.

This may seem inconsistent with the :enabled and :disabled states, especially since an element can be neither enabled nor disabled (i.e. the semantics completely do not apply), however there does not appear to be any explanation for this inconsistency.

(:indeterminate does not count, because an element can similarly be neither unchecked, checked nor indeterminate because the semantics don't apply.)

Most efficient T-SQL way to pad a varchar on the left to a certain length?

I have one function that lpad with x decimals: CREATE FUNCTION [dbo].[LPAD_DEC] ( -- Add the parameters for the function here @pad nvarchar(MAX), @string nvarchar(MAX), @length int, @dec int ) RETURNS nvarchar(max) AS BEGIN -- Declare the return variable here DECLARE @resp nvarchar(max)

IF LEN(@string)=@length
BEGIN
    IF CHARINDEX('.',@string)>0
    BEGIN
        SELECT @resp = CASE SIGN(@string)
            WHEN -1 THEN
                -- Nros negativos grandes con decimales
                concat('-',SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            ELSE
                -- Nros positivos grandes con decimales
                concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(@string,@length,@dec)))                  
            END
    END
    ELSE
    BEGIN
        SELECT @resp = CASE SIGN(@string)
            WHEN -1 THEN
                --Nros negativo grande sin decimales
                concat('-',SUBSTRING(replicate(@pad,@length),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            ELSE
                -- Nros positivos grandes con decimales
                concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(@string,@length,@dec)))                  
            END                     
    END
END
ELSE
    IF CHARINDEX('.',@string)>0
    BEGIN
        SELECT @resp =CASE SIGN(@string)
            WHEN -1 THEN
                -- Nros negativos con decimales
                concat('-',SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            ELSE
                --Ntos positivos con decimales
                concat(SUBSTRING(replicate(@pad,@length),1,@length-len(@string)),ltrim(str(abs(@string),@length,@dec))) 
            END
    END
    ELSE
    BEGIN
        SELECT @resp = CASE SIGN(@string)
            WHEN -1 THEN
                -- Nros Negativos sin decimales
                concat('-',SUBSTRING(replicate(@pad,@length-3),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            ELSE
                -- Nros Positivos sin decimales
                concat(SUBSTRING(replicate(@pad,@length),1,(@length-3)-len(@string)),ltrim(str(abs(@string),@length,@dec)))
            END
    END
RETURN @resp

END

How do format a phone number as a String in Java?

U can format any string containing non numeric characters also to your desired format use my util class to format

usage is very simple

public static void main(String[] args){
    String num = "ab12345*&67890";

    System.out.println(PhoneNumberUtil.formateToPhoneNumber(num,"(XXX)-XXX-XXXX",10));
}

output: (123)-456-7890

u can specify any foramt such as XXX-XXX-XXXX and length of the phone number , if input length is greater than specified length then string will be trimmed.

Get my class from here: https://github.com/gajeralalji/PhoneNumberUtil/blob/master/PhoneNumberUtil.java

python catch exception and continue try block

No, you cannot do that. That's just the way Python has its syntax. Once you exit a try-block because of an exception, there is no way back in.

What about a for-loop though?

funcs = do_smth1, do_smth2

for func in funcs:
    try:
        func()
    except Exception:
        pass  # or you could use 'continue'

Note however that it is considered a bad practice to have a bare except. You should catch for a specific exception instead. I captured for Exception because that's as good as I can do without knowing what exceptions the methods might throw.

tsconfig.json: Build:No inputs were found in config file

Ok, in 2021, with a <project>/src/index.ts file, the following worked for me:

If VS Code complains with No inputs were found in config file... then change the include to…

"include": ["./src/**/*.ts"]

Found the above as a comment of How to Write Node.js Applications in Typescript

XAMPP on Windows - Apache not starting

I know this is somewhat of an old topic, but in case anyone reads this in the future...

I uninstalled xampp, deleted everything under the c:\xampp folder, then reinstalled xampp as administrator and it worked like a charm.

Java: how to convert HashMap<String, Object> to array

If you are using Java 8+ and need a 2 dimensional Array, perhaps for TestNG data providers, you can try:

map.entrySet()
    .stream()
    .map(e -> new Object[]{e.getKey(), e.getValue()})
    .toArray(Object[][]::new);

If your Objects are Strings and you need a String[][], try:

map.entrySet()
    .stream()
    .map(e -> new String[]{e.getKey(), e.getValue().toString()})
    .toArray(String[][]::new);

Is there a git-merge --dry-run option?

This might be interesting: From the documentation:

If you tried a merge which resulted in complex conflicts and want to start over, you can recover with git merge --abort.

But you could also do it the naive (but slow) way:

rm -Rf /tmp/repository
cp -r repository /tmp/
cd /tmp/repository
git merge ...
...if successful, do the real merge. :)

(Note: It won't work just cloning to /tmp, you'd need a copy, in order to be sure that uncommitted changes will not conflict).

Revert to Eclipse default settings

The settings of plugins, including the core ones, are saved in the [workspace_dir]/.metadata/.plugins directories ([workspace_dir] refers to the workspace directory you use).

So if you remove the [workspace_dir]/.metadata, you will reset all the properties defined (which will include all the properties, not only the font ones). Another idea is to create and use a new workspace. Be careful, as your code source may be located in your [workspace_dir]/ directory.

But why don't you just use Use System Font button in the Eclipse Properties dialog?

Java keytool easy way to add server cert from url/port

Was looking at how to trust a certificate while using jenkins cli, and found https://issues.jenkins-ci.org/browse/JENKINS-12629 which has some recipe for that.

This will give you the certificate:

openssl s_client -connect ${HOST}:${PORT} </dev/null

if you are interested only in the certificate part, cut it out by piping it to:

| sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'

and redirect to a file:

> ${HOST}.cert

Then import it using keytool:

keytool -import -noprompt -trustcacerts -alias ${HOST} -file ${HOST}.cert \
    -keystore ${KEYSTOREFILE} -storepass ${KEYSTOREPASS}

In one go:

HOST=myhost.example.com
PORT=443
KEYSTOREFILE=dest_keystore
KEYSTOREPASS=changeme

# get the SSL certificate
openssl s_client -connect ${HOST}:${PORT} </dev/null \
    | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ${HOST}.cert

# create a keystore and import certificate
keytool -import -noprompt -trustcacerts \
    -alias ${HOST} -file ${HOST}.cert \
    -keystore ${KEYSTOREFILE} -storepass ${KEYSTOREPASS}

# verify we've got it.
keytool -list -v -keystore ${KEYSTOREFILE} -storepass ${KEYSTOREPASS} -alias ${HOST}