Programs & Examples On #Robots.txt

Robots.txt (the Robots Exclusion Protocol) is a text file placed in the root of a web site domain to give instructions to compliant web robots (such as search engine crawlers) about what pages to crawl and not crawl, as well as other information such as a Sitemap location. In modern frameworks it can be useful to programmatically generate the file. General questions about Search Engine Optimization are more appropriate on the Webmasters StackExchange site.

How to configure robots.txt to allow everything?

I understand that this is fairly old question and has some pretty good answers. But, here is my two cents for the sake of completeness.

As per the official documentation, there are four ways, you can allow complete access for robots to access your site.

Clean:

Specify a global matcher with a disallow segment as mentioned by @unor. So your /robots.txt looks like this.

User-agent: *
Disallow:

The hack:

Create a /robots.txt file with no content in it. Which will default to allow all for all type of Bots.

I don't care way:

Do not create a /robots.txt altogether. Which should yield the exact same results as the above two.

The ugly:

From the robots documentation for meta tags, You can use the following meta tag on all your pages on your site to let the Bots know that these pages are not supposed to be indexed.

<META NAME="ROBOTS" CONTENT="NOINDEX">

In order for this to be applied to your entire site, You will have to add this meta tag for all of your pages. And this tag should strictly be placed under your HEAD tag of the page. More about this meta tag here.

Can a relative sitemap url be used in a robots.txt?

Google crawlers are not smart enough, they can't crawl relative URLs, that's why it's always recommended to use absolute URL's for better crawlability and indexability.

Therefore, you can not use this variation

> sitemap: /sitemap.xml

Recommended syntax is

Sitemap: https://www.yourdomain.com/sitemap.xml

Note:

  • Don't forgot to capitalise the first letter in "sitemap"
  • Don't forgot to put space after "Sitemap:"

How to change value of a request parameter in laravel

It work for me

$request = new Request();
$request->headers->set('content-type', 'application/json');     
$request->initialize(['yourParam' => 2]);

check output

$queryParams = $request->query();
dd($queryParams['yourParam']); // 2

How to change TextField's height and width?

You can simply wrap Text field widget in padding widget..... Like this,

Padding(
         padding: EdgeInsets.only(left: 5.0, right: 5.0),
          child: TextField(
            cursorColor: Colors.blue,

            decoration: InputDecoration(
                labelText: 'Email',
                hintText: '[email protected]',
                //labelStyle: textStyle,
              border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(5),
                  borderSide: BorderSide(width: 2, color: Colors.blue,)),
              focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                  borderSide: BorderSide(width: 2, color: Colors.green)),
                )

            ),
          ),

How to extract an assembly from the GAC?

Use the file browser "Total Commander" instead.

  1. Enable the "show hidden/system files" setting in Total Commander
  2. Browse to "c:\windows\assembly"
  3. copy

How to use Google fonts in React.js?

In your CSS file, such as App.css in a create-react-app, add a fontface import. For example:

@fontface {
  font-family: 'Bungee Inline', cursive;
  src: url('https://fonts.googleapis.com/css?family=Bungee+Inline')
}

Then simply add the font to the DOM element within the same css file.

body {
  font-family: 'Bungee Inline', cursive;
}

Mock a constructor with parameter

Without Using Powermock .... See the example below based on Ben Glasser answer since it took me some time to figure it out ..hope that saves some times ...

Original Class :

public class AClazz {

    public void updateObject(CClazz cClazzObj) {
        log.debug("Bundler set.");
        cClazzObj.setBundler(new BClazz(cClazzObj, 10));
    } 
}

Modified Class :

@Slf4j
public class AClazz {

    public void updateObject(CClazz cClazzObj) {
        log.debug("Bundler set.");
        cClazzObj.setBundler(getBObject(cClazzObj, 10));
    }

    protected BClazz getBObject(CClazz cClazzObj, int i) {
        return new BClazz(cClazzObj, 10);
    }
 }

Test Class

public class AClazzTest {

    @InjectMocks
    @Spy
    private AClazz aClazzObj;

    @Mock
    private CClazz cClazzObj;

    @Mock
    private BClazz bClassObj;

    @Before
    public void setUp() throws Exception {
        Mockito.doReturn(bClassObj)
               .when(aClazzObj)
               .getBObject(Mockito.eq(cClazzObj), Mockito.anyInt());
    }

    @Test
    public void testConfigStrategy() {
        aClazzObj.updateObject(cClazzObj);

        Mockito.verify(cClazzObj, Mockito.times(1)).setBundler(bClassObj);
    }
}

Increment a Integer's int value?

You can use IntHolder as mutable alternative to Integer. But does it worth?

How to define custom exception class in Java, the easiest way?

If you inherit from Exception, you have to provide a constructor that takes a String as a parameter (it will contain the error message).

Comparing strings in C# with OR in an if statement

try

if (testString.Equals(testString2)){
}

Creating a new database and new connection in Oracle SQL Developer

Open Oracle SQLDeveloper

Right click on connection tab and select new connection

Enter HR_ORCL in connection name and HR for the username and password.

Specify localhost for your Hostname and enter ORCL for the SID.

Click Test.

The status of the connection Test Successfully.

The connection was not saved however click on Save button to save the connection. And then click on Connect button to connect your database.

The connection is saved and you see the connection list.

Variable might not have been initialized error

Since no other answer has cited the Java language standard, I have decided to write an answer of my own:

In Java, local variables are not, by default, initialized with a certain value (unlike, for example, the field of classes). From the language specification one (§4.12.5) can read the following:

A local variable (§14.4, §14.14) must be explicitly given a value before it is used, by either initialization (§14.4) or assignment (§15.26), in a way that can be verified using the rules for definite assignment (§16 (Definite Assignment)).

Therefore, since the variables a and b are not initialized :

 for (int l= 0; l<x.length; l++) 
    {
        if (x[l] == 0) 
        a++ ;
        else if (x[l] == 1) 
        b++ ;
    }

the operations a++; and b++; could not produce any meaningful results, anyway. So it is logical for the compiler to notify you about it:

Rand.java:72: variable a might not have been initialized
                a++ ;
                ^
Rand.java:74: variable b might not have been initialized
                b++ ;
                ^

However, one needs to understand that the fact that a++; and b++; could not produce any meaningful results has nothing to do with the reason why the compiler displays an error. But rather because it is explicitly set on the Java language specification that

A local variable (§14.4, §14.14) must be explicitly given a value (...)

To showcase the aforementioned point, let us change a bit your code to:

public static Rand searchCount (int[] x) 
{
    if(x == null || x.length  == 0)
      return null;
    int a ; 
    int b ; 

    ...   

    for (int l= 0; l<x.length; l++) 
    {
        if(l == 0)
           a = l;
        if(l == 1)
           b = l;
    }

    ...   
}

So even though the code above can be formally proven to be valid (i.e., the variables a and b will be always assigned with the value 0 and 1, respectively) it is not the compiler job to try to analyze your application's logic, and neither does the rules of local variable initialization rely on that. The compiler checks if the variables a and b are initialized according to the local variable initialization rules, and reacts accordingly (e.g., displaying a compilation error).

How to write URLs in Latex?

You just need to escape characters that have special meaning: # $ % & ~ _ ^ \ { }

So

http://stack_overflow.com/~foo%20bar#link

would be

http://stack\_overflow.com/\~foo\%20bar\#link

How do I avoid the specification of the username and password at every git push?

On Windows operating system use this instead, this works for me:

https://{Username}:{Password}@github.com/{Username}/{repo}.git

e.g.

git clone https://{Username}:{Password}@github.com/{Username}/{repo}.git

git pull https://{Username}:{Password}@github.com/{Username}/{repo}.git

git remote add origin https://{Username}:{Password}@github.com/{Username}/{repo}.git

git push origin master

httpd: Could not reliably determine the server's fully qualified domain name, using 127.0.0.1 for ServerName

There are two ways to resolve this error:

  1. Include /etc/apache2/httpd.conf

    Add the above line in file /etc/apache2/apache2.conf

  2. Add this line at the end of the file /etc/apache2/apache2.conf:

    ServerName localhost

How to select specific columns in laravel eloquent

You can do it like this:

Table::select('name','surname')->where('id', 1)->get();

Why does an image captured using camera intent gets rotated on some devices on Android?

The simplest solution for this problem:

captureBuilder.set(CaptureRequest.JPEG_ORIENTATION,
                   characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION));

I am saving the image in jpg format.

Get output parameter value in ADO.NET

Create the SqlParamObject which would give you control to access methods on the parameters

:

SqlParameter param = new SqlParameter();

SET the Name for your paramter (it should b same as you would have declared a variable to hold the value in your DataBase)

: param.ParameterName = "@yourParamterName";

Clear the value holder to hold you output data

: param.Value = 0;

Set the Direction of your Choice (In your case it should be Output)

: param.Direction = System.Data.ParameterDirection.Output;

Error: EACCES: permission denied

Try using this: On the command line, in your home directory, create a directory for global installations:

mkdir ~/.npm-global

Configure npm to use the new directory path:

npm config set prefix '~/.npm-global'

In your preferred text editor, open or create a ~/.profile file and add this line:

export PATH=~/.npm-global/bin:$PATH

On the command line, update your system variables:

source ~/.profile

Test installing package globally without using sudo, Hope it helps

How to distinguish mouse "click" and "drag"

from @Przemek 's answer,

_x000D_
_x000D_
function listenClickOnly(element, callback, threshold=10) {
  let drag = 0;
  element.addEventListener('mousedown', () => drag = 0);
  element.addEventListener('mousemove', () => drag++);
  element.addEventListener('mouseup', e => {
    if (drag<threshold) callback(e);
  });
}

listenClickOnly(
  document,
  () => console.log('click'),
  10
);
_x000D_
_x000D_
_x000D_

What is WebKit and how is it related to CSS?

Even though this is an older post, there is also another method to rendering for older versions of Internet Explorer. -webkit while being a CSS Vendor Prefix, you can also download a few JS applications and place them in the bottom of the HTML's HEAD.

Try using Modernizr, HTML5 Shiv and Respond.js. These are amazing IE compatible polyfill scripts that use polyfills, and other resources which will help better render HTML5 elements in IE9 and Below.

To use these polyfills, simply add HTML boolean logic to place them, IF the browser is less than the desire IE version. Example code is:

_x000D_
_x000D_
<head>_x000D_
<!-- HEAD Elements -->  _x000D_
<script src="path/to/modernizr.js" type="text/javascript"></script>_x000D_
<!--[if lt IE 6]>_x000D_
  <script src="path/to/HTMLSiv.js" type="text/javascript">_x000D_
  </script>_x000D_
  <script src="path/to/respond.js" type="text/javascript">_x000D_
  </script>_x000D_
<![endif]-->_x000D_
</head>
_x000D_
_x000D_
_x000D_

Get total number of items on Json object?

In addition to kieran's answer, apparently, modern browsers have an Object.keys function. In this case, you could do this:

Object.keys(jsonArray).length;

More details in this answer on How to list the properties of a javascript object

bootstrap multiselect get selected values

$('#multiselect1').on('change', function(){
    var selected = $(this).find("option:selected");
    var arrSelected = [];
    selected.each(function(){
       arrSelected.push($(this).val());
    });
});

jQuery append() - return appended elements

I think you could do something like this:

var $child = $("#parentId").append("<div></div>").children("div:last-child");

The parent #parentId is returned from the append, so add a jquery children query to it to get the last div child inserted.

$child is then the jquery wrapped child div that was added.

How to clean node_modules folder of packages that are not in package.json?

For Windows User, alternative solution to remove such folder listed here: http://ask.osify.com/qa/567

Among them, a free tool: Long Path Fixer is good to try: http://corz.org/windows/software/accessories/Long-Path-Fixer-for-Windows.php

How to export datagridview to excel using vb.net?

In design mode: Set DataGridView1 ClipboardCopyMode properties to EnableAlwaysIncludeHeaderText

or on the program code

DataGridView1.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText

In the run time select all cells content (Ctrl+A) and copy (Ctrl+C) and paste to the Excel Program. Let the Excel do the rest

Sorry for the inconvenient, I have been searching the method to print data directly from the datagridvew (create report from vb.net VB2012) and have not found the satisfaction result. Above code just my though, wondering if my applications user can rely on above simple step it will be nice and I could go ahead to next step on my program progress.

Copy all the lines to clipboard

on Mac

  • copy selected part: visually select text(type v or V in normal mode) and type :w !pbcopy

  • copy the whole file :%w !pbcopy

  • past from the clipboard :r !pbpaste

How to include another XHTML in XHTML using JSF 2.0 Facelets?

<ui:include>

Most basic way is <ui:include>. The included content must be placed inside <ui:composition>.

Kickoff example of the master page /page.xhtml:

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title>Include demo</title>
    </h:head>
    <h:body>
        <h1>Master page</h1>
        <p>Master page blah blah lorem ipsum</p>
        <ui:include src="/WEB-INF/include.xhtml" />
    </h:body>
</html>

The include page /WEB-INF/include.xhtml (yes, this is the file in its entirety, any tags outside <ui:composition> are unnecessary as they are ignored by Facelets anyway):

<ui:composition 
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h2>Include page</h2>
    <p>Include page blah blah lorem ipsum</p>
</ui:composition>
  

This needs to be opened by /page.xhtml. Do note that you don't need to repeat <html>, <h:head> and <h:body> inside the include file as that would otherwise result in invalid HTML.

You can use a dynamic EL expression in <ui:include src>. See also How to ajax-refresh dynamic include content by navigation menu? (JSF SPA).


<ui:define>/<ui:insert>

A more advanced way of including is templating. This includes basically the other way round. The master template page should use <ui:insert> to declare places to insert defined template content. The template client page which is using the master template page should use <ui:define> to define the template content which is to be inserted.

Master template page /WEB-INF/template.xhtml (as a design hint: the header, menu and footer can in turn even be <ui:include> files):

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
    <h:head>
        <title><ui:insert name="title">Default title</ui:insert></title>
    </h:head>
    <h:body>
        <div id="header">Header</div>
        <div id="menu">Menu</div>
        <div id="content"><ui:insert name="content">Default content</ui:insert></div>
        <div id="footer">Footer</div>
    </h:body>
</html>

Template client page /page.xhtml (note the template attribute; also here, this is the file in its entirety):

<ui:composition template="/WEB-INF/template.xhtml"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:ui="http://xmlns.jcp.org/jsf/facelets">

    <ui:define name="title">
        New page title here
    </ui:define>

    <ui:define name="content">
        <h1>New content here</h1>
        <p>Blah blah</p>
    </ui:define>
</ui:composition>

This needs to be opened by /page.xhtml. If there is no <ui:define>, then the default content inside <ui:insert> will be displayed instead, if any.


<ui:param>

You can pass parameters to <ui:include> or <ui:composition template> by <ui:param>.

<ui:include ...>
    <ui:param name="foo" value="#{bean.foo}" />
</ui:include>
<ui:composition template="...">
    <ui:param name="foo" value="#{bean.foo}" />
    ...
</ui:composition >

Inside the include/template file, it'll be available as #{foo}. In case you need to pass "many" parameters to <ui:include>, then you'd better consider registering the include file as a tagfile, so that you can ultimately use it like so <my:tagname foo="#{bean.foo}">. See also When to use <ui:include>, tag files, composite components and/or custom components?

You can even pass whole beans, methods and parameters via <ui:param>. See also JSF 2: how to pass an action including an argument to be invoked to a Facelets sub view (using ui:include and ui:param)?


Design hints

The files which aren't supposed to be publicly accessible by just entering/guessing its URL, need to be placed in /WEB-INF folder, like as the include file and the template file in above example. See also Which XHTML files do I need to put in /WEB-INF and which not?

There doesn't need to be any markup (HTML code) outside <ui:composition> and <ui:define>. You can put any, but they will be ignored by Facelets. Putting markup in there is only useful for web designers. See also Is there a way to run a JSF page without building the whole project?

The HTML5 doctype is the recommended doctype these days, "in spite of" that it's a XHTML file. You should see XHTML as a language which allows you to produce HTML output using a XML based tool. See also Is it possible to use JSF+Facelets with HTML 4/5? and JavaServer Faces 2.2 and HTML5 support, why is XHTML still being used.

CSS/JS/image files can be included as dynamically relocatable/localized/versioned resources. See also How to reference CSS / JS / image resource in Facelets template?

You can put Facelets files in a reusable JAR file. See also Structure for multiple JSF projects with shared code.

For real world examples of advanced Facelets templating, check the src/main/webapp folder of Java EE Kickoff App source code and OmniFaces showcase site source code.

How can I perform a reverse string search in Excel without using VBA?

=RIGHT(A1,LEN(A1)-FIND("`*`",SUBSTITUTE(A1," ","`*`",LEN(A1)-LEN(SUBSTITUTE(A1," ",""))))) 

How to do a newline in output

You can do this all in the File.open block:

Dir.chdir 'C:/Users/name/Music'
music = Dir['C:/Users/name/Music/*.{mp3, MP3}']
puts 'what would you like to call the playlist?'
playlist_name = gets.chomp + '.m3u'

File.open playlist_name, 'w' do |f|
  music.each do |z|
    f.puts z
  end
end

How to default to other directory instead of home directory

Right-click the Git Bash application link go to Properties and modify the Start in location to be the location you want it to start from.

Check to see if python script is running

ps ax | grep processName

if yor debug script in pycharm always exit

pydevd.py --multiproc --client 127.0.0.1 --port 33882 --file processName

Get Application Directory

I got this

String appPath = App.getApp().getApplicationContext().getFilesDir().getAbsolutePath();

from here:

Go to particular revision

You can get a graphical view of the project history with tools like gitk. Just run:

gitk --all

If you want to checkout a specific branch:

git checkout <branch name>

For a specific commit, use the SHA1 hash instead of the branch name. (See Treeishes in the Git Community Book, which is a good read, to see other options for navigating your tree.)

git log has a whole set of options to display detailed or summary history too.

I don't know of an easy way to move forward in a commit history. Projects with a linear history are probably not all that common. The idea of a "revision" like you'd have with SVN or CVS doesn't map all that well in Git.

What is the difference between call and apply?

A well explained by flatline. I just want to add a simple example. which makes it easy to understand for beginners.

func.call(context, args1 , args2 ); // pass arguments as "," saprated value

func.apply(context, [args1 , args2 ]);   //  pass arguments as "Array"

we also use "Call" and "Apply" method for changing reference as defined in code below

_x000D_
_x000D_
    let Emp1 = {_x000D_
        name: 'X',_x000D_
        getEmpDetail: function (age, department) {_x000D_
            console.log('Name :', this.name, '  Age :', age, '  Department :', department)_x000D_
        }_x000D_
    }_x000D_
    Emp1.getEmpDetail(23, 'Delivery')_x000D_
_x000D_
    // 1st approch of chenging "this"_x000D_
    let Emp2 = {_x000D_
        name: 'Y',_x000D_
        getEmpDetail: Emp1.getEmpDetail_x000D_
    }_x000D_
    Emp2.getEmpDetail(55, 'Finance')_x000D_
_x000D_
    // 2nd approch of changing "this" using "Call" and "Apply"_x000D_
    let Emp3 = {_x000D_
        name: 'Z',_x000D_
    }_x000D_
_x000D_
    Emp1.getEmpDetail.call(Emp3, 30, 'Admin')        _x000D_
// here we have change the ref from **Emp1 to Emp3**  object_x000D_
// now this will print "Name =  X" because it is pointing to Emp3 object_x000D_
    Emp1.getEmpDetail.apply(Emp3, [30, 'Admin']) //
_x000D_
_x000D_
_x000D_

How do I declare a two dimensional array?

You can try this, but second dimension values will be equals to indexes:

$array = array_fill_keys(range(0,5), range(0,5));

a little more complicated for empty array:

$array = array_fill_keys(range(0, 5), array_fill_keys(range(0, 5), null));

Import CSV to mysql table

I have google search many ways to import csv to mysql, include " load data infile ", use mysql workbench, etc.

when I use mysql workbench import button, first you need to create the empty table on your own, set each column type on your own. Note: you have to add ID column at the end as primary key and not null and auto_increment, otherwise, the import button will not visible at later. However, when I start load CSV file, nothing loaded, seems like a bug. I give up.

Lucky, the best easy way so far I found is to use Oracle's mysql for excel. you can download it from here mysql for excel

This is what you are going to do: open csv file in excel, at Data tab, find mysql for excel button

select all data, click export to mysql. Note to set a ID column as primary key.

when finished, go to mysql workbench to alter the table, such as currency type should be decimal(19,4) for large amount decimal(10,2) for regular use. other field type may be set to varchar(255).

Why is Maven downloading the maven-metadata.xml every time?

Look in your settings.xml (or, possibly your project's parent or corporate parent POM) for the <repositories> element. It will look something like the below.

<repositories>
    <repository>
        <id>central</id>
        <url>http://gotoNexus</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>always</updatePolicy>
        </snapshots>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
        </releases>
    </repository>
</repositories>

Note the <updatePolicy> element. The example tells Maven to contact the remote repo (Nexus in my case, Maven Central if you're not using your own remote repo) any time Maven needs to retrieve a snapshot artifact during a build, checking to see if there's a newer copy. The metadata is required for this. If there is a newer copy Maven downloads it to your local repo.

In the example, for releases, the policy is daily so it will check during your first build of the day. never is also a valid option, as described in Maven settings docs.

Plugins are resolved separately. You may have repositories configured for those as well, with different update policies if desired.

<pluginRepositories>
    <pluginRepository>
        <id>central</id>
        <url>http://gotoNexus</url>
        <snapshots>
            <enabled>true</enabled>
            <updatePolicy>daily</updatePolicy>
        </snapshots>
        <releases>
            <enabled>true</enabled>
            <updatePolicy>never</updatePolicy>
        </releases>
    </pluginRepository>
</pluginRepositories>

Someone else mentioned the -o option. If you use that, Maven runs in "offline" mode. It knows it has a local repo only, and it won't contact the remote repo to refresh the artifacts no matter what update policies you use.

How do I convert hh:mm:ss.000 to milliseconds in Excel?

Let's say that your time value is in cell A1 then in A2 you can put:

=A1*1000*60*60*24

or simply:

=A1*86400000

What I am doing is taking the decimal value of the time and multiply it by 1000 (milliseconds) and 60 (seconds) and 60 (minutes) and 24 (hours).

You will then need to format cell A2 as General for it to be in milliseconds format.

If your time is a text value then use:

=TIMEVALUE(A1)*86400000

UPDATE

Per @dandfra's comment this solution may not work in the Italian version of Excel.

How to force input to only allow Alpha Letters?

Rather than relying on key codes, which can be quite cumbersome, you can instead use regular expressions. By changing the pattern we can easily restrict the input to fit our needs. Note that this works with the keypress event and will allow the use of backspace (as in the accepted answer). It will not prevent users from pasting 'illegal' chars.

_x000D_
_x000D_
function testInput(event) {_x000D_
   var value = String.fromCharCode(event.which);_x000D_
   var pattern = new RegExp(/[a-zåäö ]/i);_x000D_
   return pattern.test(value);_x000D_
}_x000D_
_x000D_
$('#my-field').bind('keypress', testInput);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<label>_x000D_
   Test input:_x000D_
   <input id="my-field" type="text">_x000D_
</label>
_x000D_
_x000D_
_x000D_

Delete a row in Excel VBA

Chris Nielsen's solution is simple and will work well. A slightly shorter option would be...

ws.Rows(Rand).Delete

...note there is no need to specify a Shift when deleting a row as, by definition, it's not possible to shift left

Incidentally, my preferred method for deleting rows is to use...

ws.Rows(Rand) = ""

...in the initial loop. I then use a Sort function to push these rows to the bottom of the data. The main reason for this is because deleting single rows can be a very slow procedure (if you are deleting >100). It also ensures nothing gets missed as per Robert Ilbrink's comment

You can learn the code for sorting by recording a macro and reducing the code as demonstrated in this expert Excel video. I have a suspicion that the neatest method (Range("A1:Z10").Sort Key1:=Range("A1"), Order1:=xlSortAscending/Descending, Header:=xlYes/No) can only be discovered on pre-2007 versions of Excel...but you can always reduce the 2007/2010 equivalent code

Couple more points...if your list is not already sorted by a column and you wish to retain the order, you can stick the row number 'Rand' in a spare column to the right of each row as you loop through. You would then sort by that comment and eliminate it

If your data rows contain formatting, you may wish to find the end of the new data range and delete the rows that you cleared earlier. That's to keep the file size down. Note that a single large delete at the end of the procedure will not impair your code's performance in the same way that deleting single rows does

How does the ARM architecture differ from x86?

ARM is a RISC (Reduced Instruction Set Computing) architecture while x86 is a CISC (Complex Instruction Set Computing) one.

The core difference between those in this aspect is that ARM instructions operate only on registers with a few instructions for loading and saving data from / to memory while x86 can operate directly on memory as well. Up until v8 ARM was a native 32 bit architecture, favoring four byte operations over others.

So ARM is a simpler architecture, leading to small silicon area and lots of power save features while x86 becoming a power beast in terms of both power consumption and production.

About question on "Is the x86 Architecture specially designed to work with a keyboard while ARM expects to be mobile?". x86 isn't specially designed to work with a keyboard neither ARM for mobile. However again because of the core architectural choices actually x86 also has instructions to work directly with IO while ARM has not. However with specialized IO buses like USBs, need for such features are also disappearing.

If you need a document to quote, this is what Cortex-A Series Programmers Guide (4.0) tells about differences between RISC and CISC architectures:

An ARM processor is a Reduced Instruction Set Computer (RISC) processor.

Complex Instruction Set Computer (CISC) processors, like the x86, have a rich instruction set capable of doing complex things with a single instruction. Such processors often have significant amounts of internal logic that decode machine instructions to sequences of internal operations (microcode).

RISC architectures, in contrast, have a smaller number of more general purpose instructions, that might be executed with significantly fewer transistors, making the silicon cheaper and more power efficient. Like other RISC architectures, ARM cores have a large number of general-purpose registers and many instructions execute in a single cycle. It has simple addressing modes, where all load/store addresses can be determined from register contents and instruction fields.

ARM company also provides a paper titled Architectures, Processors, and Devices Development Article describing how those terms apply to their bussiness.

An example comparing instruction set architecture:

For example if you would need some sort of bytewise memory comparison block in your application (generated by compiler, skipping details), this is how it might look like on x86

repe cmpsb         /* repeat while equal compare string bytewise */

while on ARM shortest form might look like (without error checking etc.)

top:
ldrb r2, [r0, #1]! /* load a byte from address in r0 into r2, increment r0 after */
ldrb r3, [r1, #1]! /* load a byte from address in r1 into r3, increment r1 after */
subs r2, r3, r2    /* subtract r2 from r3 and put result into r2      */
beq  top           /* branch(/jump) if result is zero                 */

which should give you a hint on how RISC and CISC instruction sets differ in complexity.

How to get the number of threads in a Java process

    public class MainClass {

        public static void main(String args[]) {

          Thread t = Thread.currentThread();
          t.setName("My Thread");

          t.setPriority(1);

          System.out.println("current thread: " + t);

          int active = Thread.activeCount();
          System.out.println("currently active threads: " + active);
          Thread all[] = new Thread[active];
          Thread.enumerate(all);

          for (int i = 0; i < active; i++) {
             System.out.println(i + ": " + all[i]);
          }
       }
   }

How can I set a DateTimePicker control to a specific date?

Use the Value property.

MyDateTimePicker.Value = DateTime.Today.AddDays(-1);

DateTime.Today holds today's date, from which you can subtract 1 day (add -1 days) to become yesterday.

DateTime.Now, on the other hand, contains time information as well. DateTime.Now.AddDays(-1) will return this time one day ago.

How to .gitignore all files/folder in a folder, but not the folder itself?

You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.

For example, add an empty file called .gitkeep to the folder you want to keep, then in your .gitignore file write:

# exclude everything
somefolder/*

# exception to the rule
!somefolder/.gitkeep 

Commit your .gitignore and .gitkeep files and this should resolve your issue.

changing iframe source with jquery

Should work.

Here's a working example:

http://jsfiddle.net/rhpNc/

Excerpt:

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ($iframe.length) {
        $iframe.attr('src',url);
        return false;
    }
    return true;
}

What does file:///android_asset/www/index.html mean?

file:/// is a URI (Uniform Resource Identifier) that simply distinguishes from the standard URI that we all know of too well - http://.

It does imply an absolute path name pointing to the root directory in any environment, but in the context of Android, it's a convention to tell the Android run-time to say "Here, the directory www has a file called index.html located in the assets folder in the root of the project".

That is how assets are loaded at runtime, for example, a WebView widget would know exactly where to load the embedded resource file by specifying the file:/// URI.

Consider the code example:

WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/www/index.html");

A very easy mistake to make here is this, some would infer it to as file:///android_assets, notice the plural of assets in the URI and wonder why the embedded resource is not working!

Pandas left outer join multiple dataframes on multiple columns

Merge them in two steps, df1 and df2 first, and then the result of that to df3.

In [33]: s1 = pd.merge(df1, df2, how='left', on=['Year', 'Week', 'Colour'])

I dropped year from df3 since you don't need it for the last join.

In [39]: df = pd.merge(s1, df3[['Week', 'Colour', 'Val3']],
                       how='left', on=['Week', 'Colour'])

In [40]: df
Out[40]: 
   Year Week Colour  Val1  Val2 Val3
0  2014    A    Red    50   NaN  NaN
1  2014    B    Red    60   NaN   60
2  2014    B  Black    70   100   10
3  2014    C    Red    10    20  NaN
4  2014    D  Green    20   NaN   20

[5 rows x 6 columns]

How to find my Subversion server version number?

Just use a web browser to go to the SVN address. Check the source code (Ctrl + U). Then you will find something like in the HTML code:

<svn version="1.6. ..." ...

How can I check if PostgreSQL is installed or not via Linux script?

You may also check in /opt mount in following path /opt/PostgresPlus/9.5AS/bin/

iOS 7 - Status bar overlaps the view

This is all that is needed to remove the status bar. enter image description here

Access denied for user 'root'@'localhost' while attempting to grant privileges. How do I grant privileges?

You may have come to this question with MySQL version 8 installed (like me) and not found a satisfactory answer. You can no longer create users like this in version 8:

GRANT ALL PRIVILEGES ON *.* TO 'steves'@'[hostname].com' IDENTIFIED BY '[OBSCURED]' WITH GRANT OPTION;

The rather confusing error message that you get back is: ERROR 1410 (42000): You are not allowed to create a user with GRANT

In order to create users in version 8 you have to do it in two steps:

CREATE USER 'steves'@'[hostname].com' IDENTIFIED BY '[OBSCURED]';
GRANT ALL PRIVILEGES ON *.* TO 'steves'@'[hostname].com' WITH GRANT OPTION;

Of course, if you prefer, you can also supply a limited number of privileges (instead of GRANT ALL PRIVILEGES), e.g. GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER

How do I get the current date and time in PHP?

date(format, timestamp)

The date function returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of time().

And the parameters are -

format - Required. Specifies the format of the timestamp

timestamp - (Optional) Specifies a timestamp. Default is the current date and time

How to get a simple date

The required format parameter of the date() function specifies how to format the date (or time).

Here are some characters that are commonly used for dates:

  1. d - Represents the day of the month (01 to 31)
  2. m - Represents a month (01 to 12)
  3. Y - Represents a year (in four digits)
  4. l (lowercase 'L') - Represents the day of the week

Other characters, like "/", ".", or "-" can also be inserted between the characters to add additional formatting.

The example below formats today's date in three different ways:

<?php
    echo "Today is " . date("Y/m/d") . "<br>";
    echo "Today is " . date("Y.m.d") . "<br>";
    echo "Today is " . date("Y-m-d") . "<br>";
    echo "Today is " . date("l");
?>

Some useful links

How to remove the arrow from a select element in Firefox

You could increase the width of the box and move the arrow closer to the left of the arrow. this then allows you to cover the arrow with an empty white div.

Have a look: http://jsbin.com/aniyu4/86/edit

HTML5 canvas ctx.fillText won't do line breaks?

Split the text into lines, and draw each separately:

function fillTextMultiLine(ctx, text, x, y) {
  var lineHeight = ctx.measureText("M").width * 1.2;
  var lines = text.split("\n");
  for (var i = 0; i < lines.length; ++i) {
    ctx.fillText(lines[i], x, y);
    y += lineHeight;
  }
}

How can one pull the (private) data of one's own Android app?

I had the same problem but solved it running following:

$ adb shell
$ run-as {app-package-name}
$ cd /data/data/{app-package-name}
$ chmod 777 {file}
$ cp {file} /mnt/sdcard/

After this you can run

$ adb pull /mnt/sdcard/{file}

What do Push and Pop mean for Stacks?

The rifle clip analogy posted by Oren A is pretty good, but I'll try another one and try to anticipate what the instructor was trying to get across.

A stack, as it's name suggests is an arrangement of "things" that has:

  • A top
  • A bottom
  • An ordering in between the top and bottom (e.g. second from the top, 3rd from the bottom).

(think of it as a literal stack of books on your desk and you can only take something from the top)

Pushing something on the stack means "placing it on top". Popping something from the stack means "taking the top 'thing'" off the stack.

A simple usage is for reversing the order of words. Say I want to reverse the word: "popcorn". I push each letter from left to right (all 7 letters), and then pop 7 letters and they'll end up in reverse order. It looks like this was what he was doing with those expressions.

push(p) push(o) push(p) push(c) push(o) push(r) push(n)

after pushing the entire word, the stack looks like:

   |  n   |  <- top
   |  r   |
   |  o   |
   |  c   |
   |  p   |
   |  o   |
   |  p   |  <- bottom (first "thing" pushed on an empty stack)
    ======

when I pop() seven times, I get the letters in this order:

n,r,o,c,p,o,p

conversion of infix/postfix/prefix is a pathological example in computer science when teaching stacks:

Infix to Postfix conversion.

Post fix conversion to an infix expression is pretty straight forward:

(scan expression from left to right)

  1. For every number (operand) push it on the stack.
  2. Every time you encounter an operator (+,-,/,*) pop twice from the stack and place the operator between them. Push that on the stack:

So if we have 53+2* we can convert that to infix in the following steps:

  1. Push 5.
  2. Push 3.
  3. Encountered +: pop 3, pop 5, push 5+3 on stack (be consistent with ordering of 5 and 3)
  4. Push 2.
  5. Encountered *: pop 2, pop (5+3), push (2 * (5+3)).

*When you reach the end of the expression, if it was formed correctly you stack should only contain one item.

By introducing 'x' and 'o' he may have been using them as temporary holders for the left and right operands of an infix expression: x + o, x - o, etc. (or order of x,o reversed).

There's a nice write up on wikipedia as well. I've left my answer as a wiki incase I've botched up any ordering of expressions.

Getting the first character of a string with $str[0]

I've used that notation before as well, with no ill side effects and no misunderstandings. It makes sense -- a string is just an array of characters, after all.

FULL OUTER JOIN vs. FULL JOIN

Microsoft® SQL Server™ 2000 uses these SQL-92 keywords for outer joins specified in a FROM clause:

  • LEFT OUTER JOIN or LEFT JOIN

  • RIGHT OUTER JOIN or RIGHT JOIN

  • FULL OUTER JOIN or FULL JOIN

From MSDN

The full outer join or full join returns all rows from both tables, matching up the rows wherever a match can be made and placing NULLs in the places where no matching row exists.

Is there an "if -then - else " statement in XPath?

Personally, I would use XSLT to transform the XML and remove the trailing colons. For example, suppose I have this input:

<?xml version="1.0" encoding="UTF-8"?>
<Document>
    <Paragraph>This paragraph ends in a period.</Paragraph>
    <Paragraph>This one ends in a colon:</Paragraph>
    <Paragraph>This one has a : in the middle.</Paragraph>
</Document>

If I wanted to strip out trailing colons in my paragraphs, I would use this XSLT:

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:fn="http://www.w3.org/2005/xpath-functions"
    version="2.0">
    <!-- identity -->
    <xsl:template match="/|@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>
    <!-- strip out colons at the end of paragraphs -->
    <xsl:template match="Paragraph">
        <xsl:choose>
            <!-- if it ends with a : -->
            <xsl:when test="fn:ends-with(.,':')">
                <xsl:copy>
                    <!-- copy everything but the last character -->
                    <xsl:value-of select="substring(., 1, string-length(.)-1)"></xsl:value-of>
                </xsl:copy>
            </xsl:when>
            <xsl:otherwise>
                <xsl:copy>
                    <xsl:apply-templates/>
                </xsl:copy>
            </xsl:otherwise>
        </xsl:choose>
    </xsl:template>
</xsl:stylesheet> 

Git diff against a stash

To see the most recent stash:

git stash show -p

To see an arbitrary stash:

git stash show -p stash@{1}

Also, I use git diff to compare the stash with any branch.

You can use:

git diff stash@{0} master

To see all changes compared to branch master.


Or You can use:

git diff --name-only stash@{0} master

To easy find only changed file names.

What's the difference between a web site and a web application?

A web application is a website in the same way that a square is a rectangle.

The application part is the model-controller combo. The web part (the view) is why it qualifies as a website.

Something that is only a website and not a web application is simply missing the dynamic aspect.

Of course, it can be difficult to decide on how much server-side processing is required to qualify it as a web application. Probably when it has a data store.

Thus, you have the primary role of webapps confused. A website's primary role is to inform. A web app's primary role is to inform using dynamic content (the do something part).

What does yield mean in PHP?

None of the answers above show a concrete example using massive arrays populated by non-numeric members. Here is an example using an array generated by explode() on a large .txt file (262MB in my use case):

<?php

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

echo "Starting memory usage: " . memory_get_usage() . "<br>";

$path = './file.txt';
$content = file_get_contents($path);

foreach(explode("\n", $content) as $ex) {
    $ex = trim($ex);
}

echo "Final memory usage: " . memory_get_usage();

The output was:

Starting memory usage: 415160
Final memory usage: 270948256

Now compare that to a similar script, using the yield keyword:

<?php

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

echo "Starting memory usage: " . memory_get_usage() . "<br>";

function x() {
    $path = './file.txt';
    $content = file_get_contents($path);
    foreach(explode("\n", $content) as $x) {
        yield $x;
    }
}

foreach(x() as $ex) {
    $ex = trim($ex);
}

echo "Final memory usage: " . memory_get_usage();

The output for this script was:

Starting memory usage: 415152
Final memory usage: 415616

Clearly memory usage savings were considerable (?MemoryUsage -----> ~270.5 MB in first example, ~450B in second example).

How to drop a database with Mongoose?

There is no method for dropping a collection from mongoose, the best you can do is remove the content of one :

Model.remove({}, function(err) { 
   console.log('collection removed') 
});

But there is a way to access the mongodb native javascript driver, which can be used for this

mongoose.connection.collections['collectionName'].drop( function(err) {
    console.log('collection dropped');
});

Warning

Make a backup before trying this in case anything goes wrong!

jQuery Call to WebService returns "No Transport" error

I solved it simply by removing the domain from the request url.

Before: https://some.domain.com/_vti_bin/service.svc

After: /_vti_bin/service.svc

SQL Query Multiple Columns Using Distinct on One Column Only

you have various ways to distinct values on one column or multi columns.

  • using the GROUP BY

    SELECT DISTINCT MIN(o.tblFruit_ID)  AS tblFruit_ID,
       o.tblFruit_FruitType,
       MAX(o.tblFruit_FruitName)
    FROM   tblFruit  AS o
    GROUP BY
         tblFruit_FruitType
    
  • using the subquery

    SELECT b.tblFruit_ID,
       b.tblFruit_FruitType,
       b.tblFruit_FruitName
    FROM   (
           SELECT DISTINCT(tblFruit_FruitType),
                  MIN(tblFruit_ID) tblFruit_ID
           FROM   tblFruit
           GROUP BY
                  tblFruit_FruitType
       ) AS a
       INNER JOIN tblFruit b
            ON  a.tblFruit_ID = b.tblFruit_I
    
  • using the join with subquery

    SELECT t1.tblFruit_ID,
        t1.tblFruit_FruitType,
        t1.tblFruit_FruitName
    FROM   tblFruit  AS t1
       INNER JOIN (
                SELECT DISTINCT MAX(tblFruit_ID) AS tblFruit_ID,
                       tblFruit_FruitType
                FROM   tblFruit
                GROUP BY
                       tblFruit_FruitType
            )  AS t2
            ON  t1.tblFruit_ID = t2.tblFruit_ID 
    
  • using the window functions only one column distinct

    SELECT tblFruit_ID,
        tblFruit_FruitType,
        tblFruit_FruitName
    FROM   (
             SELECT tblFruit_ID,
                  tblFruit_FruitType,
                  tblFruit_FruitName,
                  ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_ID) 
        rn
           FROM   tblFruit
        ) t
        WHERE  rn = 1 
    
  • using the window functions multi column distinct

    SELECT tblFruit_ID,
        tblFruit_FruitType,
        tblFruit_FruitName
    FROM   (
             SELECT tblFruit_ID,
                  tblFruit_FruitType,
                  tblFruit_FruitName,
                  ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType,     tblFruit_FruitName 
        ORDER BY tblFruit_ID) rn
              FROM   tblFruit
         ) t
        WHERE  rn = 1 
    

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

Besides the Stanford lib that tylerl mentioned. I found jsrsasign very useful (Github repo here:https://github.com/kjur/jsrsasign). I don't know how exactly trustworthy it is, but i've used its API of SHA256, Base64, RSA, x509 etc. and it works pretty well. In fact, it includes the Stanford lib as well.

If all you want to do is SHA256, jsrsasign might be a overkill. But if you have other needs in the related area, I feel it's a good fit.

Static extension methods

specifically I want to overload Boolean.Parse to allow an int argument.

Would an extension for int work?

public static bool ToBoolean(this int source){
    // do it
    // return it
}

Then you can call it like this:

int x = 1;

bool y = x.ToBoolean();

Docker container not starting (docker start)

You are trying to run bash, an interactive shell that requires a tty in order to operate. It doesn't really make sense to run this in "detached" mode with -d, but you can do this by adding -it to the command line, which ensures that the container has a valid tty associated with it and that stdin remains connected:

docker run -it -d -p 52022:22 basickarl/docker-git-test

You would more commonly run some sort of long-lived non-interactive process (like sshd, or a web server, or a database server, or a process manager like systemd or supervisor) when starting detached containers.

If you are trying to run a service like sshd, you cannot simply run service ssh start. This will -- depending on the distribution you're running inside your container -- do one of two things:

  • It will try to contact a process manager like systemd or upstart to start the service. Because there is no service manager running, this will fail.

  • It will actually start sshd, but it will be started in the background. This means that (a) the service sshd start command exits, which means that (b) Docker considers your container to have failed, so it cleans everything up.

If you want to run just ssh in a container, consider an example like this.

If you want to run sshd and other processes inside the container, you will need to investigate some sort of process supervisor.

How to convert a JSON string to a Map<String, String> with Jackson JSON

Warning you get is done by compiler, not by library (or utility method).

Simplest way using Jackson directly would be:

HashMap<String,Object> props;

// src is a File, InputStream, String or such
props = new ObjectMapper().readValue(src, new TypeReference<HashMap<String,Object>>() {});
// or:
props = (HashMap<String,Object>) new ObjectMapper().readValue(src, HashMap.class);
// or even just:
@SuppressWarnings("unchecked") // suppresses typed/untype mismatch warnings, which is harmless
props = new ObjectMapper().readValue(src, HashMap.class);

Utility method you call probably just does something similar to this.

Best implementation for hashCode method for a collection

I prefer using utility methods fromm Google Collections lib from class Objects that helps me to keep my code clean. Very often equals and hashcode methods are made from IDE's template, so their are not clean to read.

sqlplus: error while loading shared libraries: libsqlplus.so: cannot open shared object file: No such file or directory

It means you didn't set ORACLE_HOME and ORACLE_SID variables. Kindly set proper working $ORACLE_HOME and $ORACLE_SID and after that execute sqlplus /nolog command. It will be working.

How do I get the day of week given a date?

Below is the code to enter date in the format of DD-MM-YYYY you can change the input format by changing the order of '%d-%m-%Y' and also by changing the delimiter.

import datetime
try:
    date = input()
    date_time_obj = datetime.datetime.strptime(date, '%d-%m-%Y')
    print(date_time_obj.strftime('%A'))
except ValueError:
    print("Invalid date.")

int to hex string

Try C# string interpolation introduced in C# 6:

var id = 100;
var hexid = $"0x{id:X}";

hexid value:

"0x64"

Intellij JAVA_HOME variable

Bit counter-intuitive, but you must first setup a SDK for Java projects. On the bottom right of the IntelliJ welcome screen, select 'Configure > Project Defaults > Project Structure'.

The Project tab on the left will show that you have no SDK selected:

Therefore, you must click the 'New...' button on the right hand side of the dropdown and point it to your JDK. After that, you can go back to the import screen and it should be populated with your JAVA_HOME variable, providing you have this set.

How to specify the private SSH-key to use when executing shell command on Git?

GIT_SSH_COMMAND="ssh -i /path/to/git-private-access-key" git clone $git_repo

or

export GIT_SSH_COMMAND="ssh -i /path/to/git-private-access-key"
git clone REPO
git push

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

This ERROR can happen when you use Mockito to mock final classes.

Consider using Mockito inline or Powermock instead.

how to increase the limit for max.print in R

See ?options:

options(max.print=999999)

Get index of a row of a pandas dataframe as an integer

To answer the original question on how to get the index as an integer for the desired selection, the following will work :

df[df['A']==5].index.item()

Excel concatenation quotes

easier answer - put the stuff in quotes in different cells and then concatenate them!

B1: rcrCheck.asp
C1: =D1&B1&E1
D1: "code in quotes" and "more code in quotes"  
E1: "

it comes out perfect (can't show you because I get a stupid dialog box about code)

easy peasy!!

Why does "pip install" inside Python raise a SyntaxError?

To run pip in Python 3.x, just follow the instructions on Python's page: Installing Python Modules.

python -m pip install SomePackage

Note that this is run from the command line and not the python shell (the reason for syntax error in the original question).

Getting multiple keys of specified value of a generic Dictionary?

Dictionaries aren't really meant to work like this, because while uniqueness of keys is guaranteed, uniqueness of values isn't. So e.g. if you had

var greek = new Dictionary<int, string> { { 1, "Alpha" }, { 2, "Alpha" } };

What would you expect to get for greek.WhatDoIPutHere("Alpha")?

Therefore you can't expect something like this to be rolled into the framework. You'd need your own method for your own unique uses---do you want to return an array (or IEnumerable<T>)? Do you want to throw an exception if there are multiple keys with the given value? What about if there are none?

Personally I'd go for an enumerable, like so:

IEnumerable<TKey> KeysFromValue<TKey, TValue>(this Dictionary<TKey, TValue> dict, TValue val)
{
    if (dict == null)
    {
        throw new ArgumentNullException("dict");
    }
    return dict.Keys.Where(k => dict[k] == val);
}

var keys = greek.KeysFromValue("Beta");
int exceptionIfNotExactlyOne = greek.KeysFromValue("Beta").Single();

How to select multiple rows filled with constants?

Try the connect by clause in oracle, something like this

select level,level+1,level+2 from dual connect by level <=3;

For more information on connect by clause follow this link : removed URL because oraclebin site is now malicious.

SQL Greater than, Equal to AND Less Than

If start time is a datetime type then you can use something like

SELECT BookingId, StartTime
FROM Booking
WHERE StartTime >= '2012-03-08 00:00:00.000' 
AND StartTime <= '2012-03-08 01:00:00.000'

Obviously you would want to use your own values for the times but this should give you everything in that 1 hour period inclusive of both the upper and lower limit.

You can use the GETDATE() function to get todays current date.

How to use patterns in a case statement?

Brace expansion doesn't work, but *, ? and [] do. If you set shopt -s extglob then you can also use extended pattern matching:

  • ?() - zero or one occurrences of pattern
  • *() - zero or more occurrences of pattern
  • +() - one or more occurrences of pattern
  • @() - one occurrence of pattern
  • !() - anything except the pattern

Here's an example:

shopt -s extglob
for arg in apple be cd meet o mississippi
do
    # call functions based on arguments
    case "$arg" in
        a*             ) foo;;    # matches anything starting with "a"
        b?             ) bar;;    # matches any two-character string starting with "b"
        c[de]          ) baz;;    # matches "cd" or "ce"
        me?(e)t        ) qux;;    # matches "met" or "meet"
        @(a|e|i|o|u)   ) fuzz;;   # matches one vowel
        m+(iss)?(ippi) ) fizz;;   # matches "miss" or "mississippi" or others
        *              ) bazinga;; # catchall, matches anything not matched above
    esac
done

Get names of all keys in the collection

I know this question is 10 years old but there is no C# solution and this took me hours to figure out. I'm using the .NET driver and System.Linq to return a list of the keys.

var map = new BsonJavaScript("function() { for (var key in this) { emit(key, null); } }");
var reduce = new BsonJavaScript("function(key, stuff) { return null; }");
var options = new MapReduceOptions<BsonDocument, BsonDocument>();
var result = await collection.MapReduceAsync(map, reduce, options);
var list = result.ToEnumerable().Select(item => item["_id"].ToString());

How do you add input from user into list in Python

code below allows user to input items until they press enter key to stop:

In [1]: items=[]
   ...: i=0
   ...: while 1:
   ...:     i+=1
   ...:     item=input('Enter item %d: '%i)
   ...:     if item=='':
   ...:         break
   ...:     items.append(item)
   ...: print(items)
   ...: 

Enter item 1: apple

Enter item 2: pear

Enter item 3: #press enter here
['apple', 'pear']

In [2]: 

Pipe subprocess standard output to a variable

If you are using python 2.7 or later, the easiest way to do this is to use the subprocess.check_output() command. Here is an example:

output = subprocess.check_output('ls')

To also redirect stderr you can use the following:

output = subprocess.check_output('ls', stderr=subprocess.STDOUT)



In the case that you want to pass parameters to the command, you can either use a list or use invoke a shell and use a single string.

output = subprocess.check_output(['ls', '-a'])
output = subprocess.check_output('ls -a', shell=True)

How to copy directories in OS X 10.7.3?

Is there something special with that directory or are you really just asking how to copy directories?

Copy recursively via CLI:

cp -R <sourcedir> <destdir>

If you're only seeing the files under the sourcedir being copied (instead of sourcedir as well), that's happening because you kept the trailing slash for sourcedir:

cp -R <sourcedir>/ <destdir>

The above only copies the files and their directories inside of sourcedir. Typically, you want to include the directory you're copying, so drop the trailing slash:

cp -R <sourcedir> <destdir>

How do I get the domain originating the request in express.js?

Recently faced a problem with fetching 'Origin' request header, then I found this question. But pretty confused with the results, req.get('host') is deprecated, that's why giving Undefined. Use,

    req.header('Origin');
    req.header('Host');
    // this method can be used to access other request headers like, 'Referer', 'User-Agent' etc.

Twitter API - Display all tweets with a certain hashtag?

This answer was written in 2010. The API it uses has since been retired. It is kept for historical interest only.


Search for it.

Make sure include_entities is set to true to get hashtag results. See Tweet Entities

Returns 5 mixed results with Twitter.com user IDs plus entities for the term "blue angels":

GET http://search.twitter.com/search.json?q=blue%20angels&rpp=5&include_entities=true&with_twitter_user_id=true&result_type=mixed

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

I know I'm 4 years late but my answer is for anyone who may not have figured it out. I'm using a Samsung Galaxy S6, what worked for me was:

  1. Disable USB debugging

  2. Disable Developer mode

  3. Unplug the device from the USB cable

  4. Re-enable Developer mode

  5. Re-enable USB debugging

  6. Reconnect the USB cable to your device

It is important you do it in this order as it didn't work until it was done in this order.

Set encoding and fileencoding to utf-8 in Vim

set encoding=utf-8  " The encoding displayed.
set fileencoding=utf-8  " The encoding written to file.

You may as well set both in your ~/.vimrc if you always want to work with utf-8.

How do I left align these Bootstrap form items?

If you are saying that your problem is how to left align the form labels, see if this helps:
http://jsfiddle.net/panchroma/8gYPQ/

Try changing the text-align left / right in the CSS

.form-horizontal .control-label{
    /* text-align:right; */
    text-align:left;
    background-color:#ffa;
}

Good luck!

Checking if sys.argv[x] is defined

Pretty close to what the originator was trying to do. Here is a function I use:

def get_arg(index):
    try:
        sys.argv[index]
    except IndexError:
        return ''
    else:
        return sys.argv[index]

So a usage would be something like:

if __name__ == "__main__":
    banner(get_arg(1),get_arg(2))

Why emulator is very slow in Android Studio?

The Best Solution is to use Android Emulator with Intel Virtualization Technology.

Now if your system have a Processor that have a feature called as Intel Virtualization Technology, then Intel X86 images will be huge benefit for you. because it supports Intel® Hardware Accelerated Execution Manager (Intel® HAXM).

To check that your processor support HAXM or not : Click Here

You need to manually install the Intel HAXM in your system. Follow these steps for that.

  • First of all go to - adt -> extras -> intel -> Hardware_Accelerated_Execution_Manager
  • Make sure that Intel Virtualization is enabled from BIOS Settings.
  • Now install Intel HAXM in your system and select amount of memory(i prefer to set it as default value).
  • After installation create new Android Virtual Device (AVD) which should have a Target of API Level xx
  • Now set the CPU/ABI as Intel Atom(x86).
  • If you are on Windows then do not set RAM value more than 768 MB while setting up an emulator.
  • Run the emulator. It will be blazing fast then ordinary one.

Hope it will be helpful for you. :) Thanks.

Select unique values with 'select' function in 'dplyr' library

The dplyr select function selects specific columns from a data frame. To return unique values in a particular column of data, you can use the group_by function. For example:

library(dplyr)

# Fake data
set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE))

# Return the distinct values of x
dat %>%
  group_by(x) %>%
  summarise() 

    x
1   1
2   2
3   3
4   4
5   5
6   6
7   7
8   8
9   9
10 10

If you want to change the column name you can add the following:

dat %>%
  group_by(x) %>%
  summarise() %>%
  select(unique.x=x)

This both selects column x from among all the columns in the data frame that dplyr returns (and of course there's only one column in this case) and changes its name to unique.x.

You can also get the unique values directly in base R with unique(dat$x).

If you have multiple variables and want all unique combinations that appear in the data, you can generalize the above code as follows:

set.seed(5)
dat = data.frame(x=sample(1:10,100, replace=TRUE), 
                 y=sample(letters[1:5], 100, replace=TRUE))

dat %>% 
  group_by(x,y) %>%
  summarise() %>%
  select(unique.x=x, unique.y=y)

Handling very large numbers in Python

python supports arbitrarily large integers naturally:

In [1]: 59**3*61**4*2*3*5*7*3*5*7
Out[1]: 62702371781194950
In [2]: _ % 61**4
Out[2]: 0

PHP AES encrypt / decrypt

Here's an improved version based on code written by blade

  • add comments
  • overwrite arguments before throwing to avoid leaking secrets with the exception
  • check return values from openssl and hmac functions

The code:

class Crypto
{
    /**
     * Encrypt data using OpenSSL (AES-256-CBC)
     * @param string $plaindata Data to be encrypted
     * @param string $cryptokey key for encryption (with 256 bit of entropy)
     * @param string $hashkey key for hashing (with 256 bit of entropy)
     * @return string IV+Hash+Encrypted as raw binary string. The first 16
     *     bytes is IV, next 32 bytes is HMAC-SHA256 and the rest is
     *     $plaindata as encrypted.
     * @throws Exception on internal error
     *
     * Based on code from: https://stackoverflow.com/a/46872528
     */
    public static function encrypt($plaindata, $cryptokey, $hashkey)
    {
        $method = "AES-256-CBC";
        $key = hash('sha256', $cryptokey, true);
        $iv = openssl_random_pseudo_bytes(16);

        $cipherdata = openssl_encrypt($plaindata, $method, $key, OPENSSL_RAW_DATA, $iv);

        if ($cipherdata === false)
        {
            $cryptokey = "**REMOVED**";
            $hashkey = "**REMOVED**";
            throw new \Exception("Internal error: openssl_encrypt() failed:".openssl_error_string());
        }

        $hash = hash_hmac('sha256', $cipherdata.$iv, $hashkey, true);

        if ($hash === false)
        {
            $cryptokey = "**REMOVED**";
            $hashkey = "**REMOVED**";
            throw new \Exception("Internal error: hash_hmac() failed");
        }

        return $iv.$hash.$cipherdata;
    }

    /**
    * Decrypt data using OpenSSL (AES-256-CBC)
     * @param string $encrypteddata IV+Hash+Encrypted as raw binary string
     *     where the first 16 bytes is IV, next 32 bytes is HMAC-SHA256 and
     *     the rest is encrypted payload.
     * @param string $cryptokey key for decryption (with 256 bit of entropy)
     * @param string $hashkey key for hashing (with 256 bit of entropy)
     * @return string Decrypted data
     * @throws Exception on internal error
     *
     * Based on code from: https://stackoverflow.com/a/46872528
     */
    public static function decrypt($encrypteddata, $cryptokey, $hashkey)
    {
        $method = "AES-256-CBC";
        $key = hash('sha256', $cryptokey, true);
        $iv = substr($encrypteddata, 0, 16);
        $hash = substr($encrypteddata, 16, 32);
        $cipherdata = substr($encrypteddata, 48);

        if (!hash_equals(hash_hmac('sha256', $cipherdata.$iv, $hashkey, true), $hash))
        {
            $cryptokey = "**REMOVED**";
            $hashkey = "**REMOVED**";
            throw new \Exception("Internal error: Hash verification failed");
        }

        $plaindata = openssl_decrypt($cipherdata, $method, $key, OPENSSL_RAW_DATA, $iv);

        if ($plaindata === false)
        {
            $cryptokey = "**REMOVED**";
            $hashkey = "**REMOVED**";
            throw new \Exception("Internal error: openssl_decrypt() failed:".openssl_error_string());
        }

        return $plaindata;
    }
}

If you truly cannot have proper encryption and hash keys but have to use an user entered password as the only secret, you can do something like this:

/**
 * @param string $password user entered password as the only source of
 *   entropy to generate encryption key and hash key.
 * @return array($encryption_key, $hash_key) - note that PBKDF2 algorithm
 *   has been configured to take around 1-2 seconds per conversion
 *   from password to keys on a normal CPU to prevent brute force attacks.
 */
public static function generate_encryptionkey_hashkey_from_password($password)
{
    $hash = hash_pbkdf2("sha512", "$password", "salt$password", 1500000);
    return str_split($hash, 64);
}

SQL datetime format to date only

SELECT Subject, CONVERT(varchar(10),DeliveryDate) as DeliveryDate
from Email_Administration 
where MerchantId =@ MerchantID

Can you Run Xcode in Linux?

You can run Xcode on Linux NATIVELY using Darling:

Darling is a translation layer that lets you run macOS software on Linux

Once installed you can install Xcode via command-line developer tool following this link.

Parsing xml using powershell

[xml]$xmlfile = '<xml> <Section name="BackendStatus"> <BEName BE="crust" Status="1" /> <BEName BE="pizza" Status="1" /> <BEName BE="pie" Status="1" /> <BEName BE="bread" Status="1" /> <BEName BE="Kulcha" Status="1" /> <BEName BE="kulfi" Status="1" /> <BEName BE="cheese" Status="1" /> </Section> </xml>'

foreach ($bename in $xmlfile.xml.Section.BEName) {
    if($bename.Status -eq 1){
        #Do something
    }
}

How can I create basic timestamps or dates? (Python 3.4)

>>> import time
>>> print(time.strftime('%a %H:%M:%S'))
Mon 06:23:14

Appending values to dictionary in Python

You can use the update() method as well

d = {"a": 2}
d.update{"b": 4}
print(d) # {"a": 2, "b": 4}

How to delete or add column in SQLITE?

As others have pointed out, sqlite's ALTER TABLE statement does not support DROP COLUMN, and the standard recipe to do this does not preserve constraints & indices.

Here's some python code to do this generically, while maintaining all the key constraints and indices.

Please back-up your database before using! This function relies on doctoring the original CREATE TABLE statement and is potentially a bit unsafe - for instance it will do the wrong thing if an identifier contains an embedded comma or parenthesis.

If anyone would care to contribute a better way to parse the SQL, that would be great!

UPDATE I found a better way to parse using the open-source sqlparse package. If there is any interest I will post it here, just leave a comment asking for it ...

import re
import random

def DROP_COLUMN(db, table, column):
    columns = [ c[1] for c in db.execute("PRAGMA table_info(%s)" % table) ]
    columns = [ c for c in columns if c != column ]
    sql = db.execute("SELECT sql from sqlite_master where name = '%s'" 
        % table).fetchone()[0]
    sql = format(sql)
    lines = sql.splitlines()
    findcol = r'\b%s\b' % column
    keeplines = [ line for line in lines if not re.search(findcol, line) ]
    create = '\n'.join(keeplines)
    create = re.sub(r',(\s*\))', r'\1', create)
    temp = 'tmp%d' % random.randint(1e8, 1e9)
    db.execute("ALTER TABLE %(old)s RENAME TO %(new)s" % { 
        'old': table, 'new': temp })
    db.execute(create)
    db.execute("""
        INSERT INTO %(new)s ( %(columns)s ) 
        SELECT %(columns)s FROM %(old)s
    """ % { 
        'old': temp,
        'new': table,
        'columns': ', '.join(columns)
    })  
    db.execute("DROP TABLE %s" % temp)

def format(sql):
    sql = sql.replace(",", ",\n")
    sql = sql.replace("(", "(\n")
    sql = sql.replace(")", "\n)")
    return sql

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

  1. Goto build.gradle of app folder,
  2. set minSdkVersion to 21

Save and Run your app, it should run without the dex error now

Count multiple columns with group by in one query

One solution is to wrap it in a subquery

SELECT *
FROM
(
    SELECT COUNT(column1),column1 FROM table GROUP BY column1
    UNION ALL
    SELECT COUNT(column2),column2 FROM table GROUP BY column2
    UNION ALL
    SELECT COUNT(column3),column3 FROM table GROUP BY column3
) s

POST JSON to API using Rails and HTTParty

The :query_string_normalizer option is also available, which will override the default normalizer HashConversions.to_params(query)

query_string_normalizer: ->(query){query.to_json}

Getting parts of a URL (Regex)

//USING REGEX
/**
 * Parse URL to get information
 *
 * @param   url     the URL string to parse
 * @return  parsed  the URL parsed or null
 */
var UrlParser = function (url) {
    "use strict";

    var regx = /^(((([^:\/#\?]+:)?(?:(\/\/)((?:(([^:@\/#\?]+)(?:\:([^:@\/#\?]+))?)@)?(([^:\/#\?\]\[]+|\[[^\/\]@#?]+\])(?:\:([0-9]+))?))?)?)?((\/?(?:[^\/\?#]+\/+)*)([^\?#]*)))?(\?[^#]+)?)(#.*)?/,
        matches = regx.exec(url),
        parser = null;

    if (null !== matches) {
        parser = {
            href              : matches[0],
            withoutHash       : matches[1],
            url               : matches[2],
            origin            : matches[3],
            protocol          : matches[4],
            protocolseparator : matches[5],
            credhost          : matches[6],
            cred              : matches[7],
            user              : matches[8],
            pass              : matches[9],
            host              : matches[10],
            hostname          : matches[11],
            port              : matches[12],
            pathname          : matches[13],
            segment1          : matches[14],
            segment2          : matches[15],
            search            : matches[16],
            hash              : matches[17]
        };
    }

    return parser;
};

var parsedURL=UrlParser(url);
console.log(parsedURL);

Android: How do I prevent the soft keyboard from pushing my view up?

Try to use this:

android:windowSoftInputMode="stateHidden|adjustPan"

check the null terminating character in char*

Your '/0' should be '\0' .. you got the slash reversed/leaning the wrong way. Your while should look like:

while (*(forward++)!='\0') 

though the != '\0' part of your expression is optional here since the loop will continue as long as it evaluates to non-zero (null is considered zero and will terminate the loop).

All "special" characters (i.e., escape sequences for non-printable characters) use a backward slash, such as tab '\t', or newline '\n', and the same for null '\0' so it's easy to remember.

Is there a concise way to iterate over a stream with indices in Java 8?

As jean-baptiste-yunès said, if your stream is based on a java List then using an AtomicInteger and its incrementAndGet method is a very good solution to the problem and the returned integer does correspond to the index in the original List as long as you do not use a parallel stream.

Use "ENTER" key on softkeyboard instead of clicking button

<EditText
    android:id="@+id/search"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/search_hint"
    android:inputType="text"
    android:imeOptions="actionSend" />

You can then listen for presses on the action button by defining a TextView.OnEditorActionListener for the EditText element. In your listener, respond to the appropriate IME action ID defined in the EditorInfo class, such as IME_ACTION_SEND. For example:

EditText editText = (EditText) findViewById(R.id.search);
editText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            sendMessage();
            handled = true;
        }
        return handled;
    }
});

Source: https://developer.android.com/training/keyboard-input/style.html

wget/curl large file from google drive

the easy way to down file from google drive you can also download file on colab

pip install gdown

import gdown

Then

url = 'https://drive.google.com/uc?id=0B9P1L--7Wd2vU3VUVlFnbTgtS2c'
output = 'spam.txt'
gdown.download(url, output, quiet=False)

or

fileid='0B9P1L7Wd2vU3VUVlFnbTgtS2c'

gdown https://drive.google.com/uc?id=+fileid

Document https://pypi.org/project/gdown/

Making HTML page zoom by default

A better solution is not to make your page dependable on zoom settings. If you set limits like the one you are proposing, you are limiting accessibility. If someone cannot read your text well, they just won't be able to change that. I would use proper CSS to make it look nice in any zoom.

If your really insist, take a look at this question on how to detect zoom level using JavaScript (nightmare!): How to detect page zoom level in all modern browsers?

Is there an easy way to return a string repeated X number of times?

I don't have enough rep to comment on Adam's answer, but the best way to do it imo is like this:

public static string RepeatString(string content, int numTimes) {
        if(!string.IsNullOrEmpty(content) && numTimes > 0) {
            StringBuilder builder = new StringBuilder(content.Length * numTimes);

            for(int i = 0; i < numTimes; i++) builder.Append(content);

            return builder.ToString();
        }

        return string.Empty;
    }

You must check to see if numTimes is greater then zero, otherwise you will get an exception.

Writing a list to a file with Python

Using Python 3 and Python 2.6+ syntax:

with open(filepath, 'w') as file_handler:
    for item in the_list:
        file_handler.write("{}\n".format(item))

This is platform-independent. It also terminates the final line with a newline character, which is a UNIX best practice.

Starting with Python 3.6, "{}\n".format(item) can be replaced with an f-string: f"{item}\n".

How can I encode a string to Base64 in Swift?

After all struggle I did like this.

func conversion(str:NSString)
{

    if let decodedData = NSData(base64EncodedString: str as String, options:NSDataBase64DecodingOptions(rawValue: 0)),
        let decodedString = NSString(data: decodedData, encoding: NSUTF8StringEncoding) {

        print(decodedString)//Here we are getting decoded string

After I am calling another function for converting decoded string to dictionary

        self .convertStringToDictionary(decodedString as String)
    }


}//function close

//for string to dictionary

func convertStringToDictionary(text: String) -> [String:AnyObject]? {
    if let data = text.dataUsingEncoding(NSUTF8StringEncoding) {
        do {
            let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? [String:AnyObject]

            print(json)
            if let stack = json!["cid"]  //getting key value here
            {
                customerID = stack as! String
                print(customerID)
            }

        } catch let error as NSError {
            print(error)
        }
    }
    return nil
}

Selecting multiple columns in a Pandas dataframe

I've seen several answers on that, but one remained unclear to me. How would you select those columns of interest?

The answer to that is that if you have them gathered in a list, you can just reference the columns using the list.

Example

print(extracted_features.shape)
print(extracted_features)

(63,)
['f000004' 'f000005' 'f000006' 'f000014' 'f000039' 'f000040' 'f000043'
 'f000047' 'f000048' 'f000049' 'f000050' 'f000051' 'f000052' 'f000053'
 'f000054' 'f000055' 'f000056' 'f000057' 'f000058' 'f000059' 'f000060'
 'f000061' 'f000062' 'f000063' 'f000064' 'f000065' 'f000066' 'f000067'
 'f000068' 'f000069' 'f000070' 'f000071' 'f000072' 'f000073' 'f000074'
 'f000075' 'f000076' 'f000077' 'f000078' 'f000079' 'f000080' 'f000081'
 'f000082' 'f000083' 'f000084' 'f000085' 'f000086' 'f000087' 'f000088'
 'f000089' 'f000090' 'f000091' 'f000092' 'f000093' 'f000094' 'f000095'
 'f000096' 'f000097' 'f000098' 'f000099' 'f000100' 'f000101' 'f000103']

I have the following list/NumPy array extracted_features, specifying 63 columns. The original dataset has 103 columns, and I would like to extract exactly those, then I would use

dataset[extracted_features]

And you will end up with this

Enter image description here

This something you would use quite often in machine learning (more specifically, in feature selection). I would like to discuss other ways too, but I think that has already been covered by other Stack Overflower users.

How do I import a .sql file in mysql database using PHP?

// Import data 
$filename = 'database_file_name.sql';
import_tables('localhost','root','','database_name',$filename);

function import_tables($host,$uname,$pass,$database, $filename,$tables = '*'){
    $connection = mysqli_connect($host,$uname,$pass)
    or die("Database Connection Failed");
    $selectdb = mysqli_select_db($connection, $database) or die("Database could not be selected"); 

$templine = '';
$lines = file($filename); // Read entire file

foreach ($lines as $line){
    // Skip it if it's a comment
    if (substr($line, 0, 2) == '--' || $line == '' || substr($line, 0, 2) == '/*' )
        continue;

        // Add this line to the current segment
        $templine .= $line;
        // If it has a semicolon at the end, it's the end of the query
        if (substr(trim($line), -1, 1) == ';')
        {
            mysqli_query($connection, $templine)
            or print('Error performing query \'<strong>' . $templine . '\': ' . mysqli_error($connection) . '<br /><br />');
            $templine = '';
        }
    }
    echo "Tables imported successfully";
}




// Backup database from php script
backup_tables('hostname','UserName','pass','databses_name');

function backup_tables($host,$user,$pass,$name,$tables = '*'){
    $link = mysqli_connect($host,$user,$pass);
    if (mysqli_connect_errno()){
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

    mysqli_select_db($link,$name);
    //get all of the tables
    if($tables == '*'){
        $tables = array();
        $result = mysqli_query($link,'SHOW TABLES');
        while($row = mysqli_fetch_row($result))
        {
            $tables[] = $row[0];
        }
    }else{
        $tables = is_array($tables) ? $tables : explode(',',$tables);
    }

    $return = '';
    foreach($tables as $table)
    {
        $result = mysqli_query($link,'SELECT * FROM '.$table);
        $num_fields = mysqli_num_fields($result);
        $row_query = mysqli_query($link,'SHOW CREATE TABLE '.$table);
        $row2 = mysqli_fetch_row($row_query);
        $return.= "\n\n".$row2[1].";\n\n";

        for ($i = 0; $i < $num_fields; $i++) 
        {
            while($row = mysqli_fetch_row($result))
            {
                $return.= 'INSERT INTO '.$table.' VALUES(';
                for($j=0; $j < $num_fields; $j++) 
                {
                    $row[$j] = addslashes($row[$j]);
                    $row[$j] = str_replace("\n", '\n', $row[$j]);
                    if (isset($row[$j])) { 
                        $return.= '"'.$row[$j].'"' ; 
                    } else { 
                        $return.= '""'; 
                    }
                    if ($j < ($num_fields-1)) { $return.= ','; }
                }
                $return.= ");\n";
            }
        }
        $return.="\n\n\n";
    }

    //save file
    $handle = fopen('backup-'.date("d_m_Y__h_i_s_A").'-'.(md5(implode(',',$tables))).'.sql','w+');
    fwrite($handle,$return);
    fclose($handle);
}

PHP: How to check if image file exists?

Read first 5 bytes form HTTP using fopen() and fread() then use this:

DEFINE("GIF_START","GIF");
DEFINE("PNG_START",pack("C",0x89)."PNG");
DEFINE("JPG_START",pack("CCCCCC",0xFF,0xD8,0xFF,0xE0,0x00,0x10)); 

to detect image.

How to get to a particular element in a List in java?

The toString method of array types in Java isn't particularly meaningful, other than telling you what that is an array of.

You can use java.util.Arrays.toString for that.

Or if your lines only contain numbers, and you want a line as 1,2,3,4... instead of [1, 2, 3, ...], you can use:

java.util.Arrays.toString(someArray).replaceAll("\\]| |\\[","")

How to put a delay on AngularJS instant search?

Why does everyone wants to use watch? You could also use a function:

var tempArticleSearchTerm;
$scope.lookupArticle = function (val) {
    tempArticleSearchTerm = val;

    $timeout(function () {
        if (val == tempArticleSearchTerm) {
            //function you want to execute after 250ms, if the value as changed

        }
    }, 250);
}; 

Null check in VB

Your code is way more cluttered than necessary.

Replace (Not (X Is Nothing)) with X IsNot Nothing and omit the outer parentheses:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For i As Integer = 0 To comp.Container.Components.Count() - 1
        fixUIIn(comp.Container.Components(i), style)
    Next
End If

Much more readable. … Also notice that I’ve removed the redundant Step 1 and the probably redundant .Item.

But (as pointed out in the comments), index-based loops are out of vogue anyway. Don’t use them unless you absolutely have to. Use For Each instead:

If comp.Container IsNot Nothing AndAlso comp.Container.Components IsNot Nothing Then
    For Each component In comp.Container.Components
        fixUIIn(component, style)
    Next
End If

What do &lt; and &gt; stand for?

&lt; ==  lesser-than == <
&gt; == greater-than == >

Call to getLayoutInflater() in places not in activity

or

View.inflate(context, layout, parent)

How to install PostgreSQL's pg gem on Ubuntu?

After reading and thrashing around for 2 days, and trying many things found in other notes the following single line was the cure for me on Ubuntu Lucid 10.04 mixed with some Maverick packages and RVM (ruby 1.9.2-p290, rvm 1.10.2 rubygems 1.8.15, rails 3.0.1, postgres 8.4.10) :

gem install pg  --   --with-pg-lib=/usr/lib   

the result:

Building native extensions.  This could take a while...  
Successfully installed pg-0.13.1  
1 gem installed  
Installing ri documentation for pg-0.13.1...  
Installing RDoc documentation for pg-0.13.1...  

{yea - finally success} !! !note that the output from running pg_config lacks the item -lpq in the LIBS variable on my Ubuntu / Postresql install!!

and why the switch from pq to pg in certain places -- confusing to newbie ??

the thing I still do not understand is the double set of -- and --with(option but I'm way beyond my depth anyway

Return a "NULL" object if search result not found

There are several possible answers here. You want to return something that might exist. Here are some options, ranging from my least preferred to most preferred:

  • Return by reference, and signal can-not-find by exception.

    Attr& getAttribute(const string& attribute_name) const 
    {
       //search collection
       //if found at i
            return attributes[i];
       //if not found
            throw no_such_attribute_error;
    }

It's likely that not finding attributes is a normal part of execution, and hence not very exceptional. The handling for this would be noisy. A null value cannot be returned because it's undefined behaviour to have null references.

  • Return by pointer

    Attr* getAttribute(const string& attribute_name) const 
    {
       //search collection
       //if found at i
            return &attributes[i];
       //if not found
            return nullptr;
    }

It's easy to forget to check whether a result from getAttribute would be a non-NULL pointer, and is an easy source of bugs.

  • Use Boost.Optional

    boost::optional<Attr&> getAttribute(const string& attribute_name) const 
    {
       //search collection
       //if found at i
            return attributes[i];
       //if not found
            return boost::optional<Attr&>();
    }

A boost::optional signifies exactly what is going on here, and has easy methods for inspecting whether such an attribute was found.


Side note: std::optional was recently voted into C++17, so this will be a "standard" thing in the near future.

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

McAfee was blocking it for me. I had to allow the program in the access protection rules

  1. Open VirusScan
  2. Right click on Access Protection and choose Properties
  3. Click on "Anti-virus Standard Protection"
  4. Select rule "Prevent mass mailing worms from sending mail" and click edit
  5. Add the application to the Processes to exclude list and click OK

See http://www.symantec.com/connect/articles/we-are-unable-send-your-email-caused-mcafee

Count distinct values

You can do a distinct count as follows:

SELECT COUNT(DISTINCT column_name) FROM table_name;

EDIT:

Following your clarification and update to the question, I see now that it's quite a different question than we'd originally thought. "DISTINCT" has special meaning in SQL. If I understand correctly, you want something like this:

  • 2 customers had 1 pets
  • 3 customers had 2 pets
  • 1 customers had 3 pets

Now you're probably going to want to use a subquery:

select COUNT(*) column_name FROM (SELECT DISTINCT column_name);

Let me know if this isn't quite what you're looking for.

Java Regex Replace with Capturing Group

How about:

if (regexMatcher.find()) {
    resultString = regexMatcher.replaceAll(
            String.valueOf(3 * Integer.parseInt(regexMatcher.group(1))));
}

To get the first match, use #find(). After that, you can use #group(1) to refer to this first match, and replace all matches by the first maches value multiplied by 3.

And in case you want to replace each match with that match's value multiplied by 3:

    Pattern p = Pattern.compile("(\\d{1,2})");
    Matcher m = p.matcher("12 54 1 65");
    StringBuffer s = new StringBuffer();
    while (m.find())
        m.appendReplacement(s, String.valueOf(3 * Integer.parseInt(m.group(1))));
    System.out.println(s.toString());

You may want to look through Matcher's documentation, where this and a lot more stuff is covered in detail.

Arrays in unix shell?

An array can be loaded in twoways.

set -A TEST_ARRAY alpha beta gamma

or

X=0 # Initialize counter to zero.

-- Load the array with the strings alpha, beta, and gamma

for ELEMENT in alpha gamma beta
do
    TEST_ARRAY[$X]=$ELEMENT
    ((X = X + 1))
done

Also, I think below information may help:

The shell supports one-dimensional arrays. The maximum number of array elements is 1,024. When an array is defined, it is automatically dimensioned to 1,024 elements. A one-dimensional array contains a sequence of array elements, which are like the boxcars connected together on a train track.

In case you want to access the array:

echo ${MY_ARRAY[2] # Show the third array element
 gamma 


echo ${MY_ARRAY[*] # Show all array elements
-   alpha beta gamma


echo ${MY_ARRAY[@] # Show all array elements
 -  alpha beta gamma


echo ${#MY_ARRAY[*]} # Show the total number of array elements
-   3


echo ${#MY_ARRAY[@]} # Show the total number of array elements
-   3

echo ${MY_ARRAY} # Show array element 0 (the first element)
-  alpha

Selenium and xpath: finding a div with a class/id and verifying text inside

To verify this:-

<div class="Caption">
  Model saved
</div>

Write this -

//div[contains(@class, 'Caption') and text()='Model saved']

And to verify this:-

<div id="alertLabel" class="gwt-HTML sfnStandardLeftMargin sfnStandardRightMargin sfnStandardTopMargin">
  Save to server successful
</div>

Write this -

//div[@id='alertLabel' and text()='Save to server successful']

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

There are 10^6 values in a range of 10^8, so there's one value per hundred code points on average. Store the distance from the Nth point to the (N+1)th. Duplicate values have a skip of 0. This means that the skip needs an average of just under 7 bits to store, so a million of them will happily fit into our 8 million bits of storage.

These skips need to be encoded into a bitstream, say by Huffman encoding. Insertion is by iterating through the bitstream and rewriting after the new value. Output by iterating through and writing out the implied values. For practicality, it probably wants to be done as, say, 10^4 lists covering 10^4 code points (and an average of 100 values) each.

A good Huffman tree for random data can be built a priori by assuming a Poisson distribution (mean=variance=100) on the length of the skips, but real statistics can be kept on the input and used to generate an optimal tree to deal with pathological cases.

JavaScript: get code to run every minute

You could use setInterval for this.

<script type="text/javascript">
function myFunction () {
    console.log('Executed!');
}

var interval = setInterval(function () { myFunction(); }, 60000);
</script>

Disable the timer by setting clearInterval(interval).

See this Fiddle: http://jsfiddle.net/p6NJt/2/

Elegant Python function to convert CamelCase to snake_case?

I don't get idea why using both .sub() calls? :) I'm not regex guru, but I simplified function to this one, which is suitable for my certain needs, I just needed a solution to convert camelCasedVars from POST request to vars_with_underscore:

def myFunc(...):
  return re.sub('(.)([A-Z]{1})', r'\1_\2', "iTriedToWriteNicely").lower()

It does not work with such names like getHTTPResponse, cause I heard it is bad naming convention (should be like getHttpResponse, it's obviously, that it's much easier memorize this form).

How can I view array structure in JavaScript with alert()?

Better use Firebug (chrome console etc) and use console.dir()

Avoid duplicates in INSERT INTO SELECT query in SQL Server

A simple DELETE before the INSERT would suffice:

DELETE FROM Table2 WHERE Id = (SELECT Id FROM Table1)
INSERT INTO Table2 (Id, name) SELECT Id, name FROM Table1

Switching Table1 for Table2 depending on which table's Id and name pairing you want to preserve.

Python: Continuing to next iteration in outer loop

for ii in range(200):
    for jj in range(200, 400):
        ...block0...
        if something:
            break
    else:
        ...block1...

Break will break the inner loop, and block1 won't be executed (it will run only if the inner loop is exited normally).

How to sort an array of associative arrays by value of a given key in PHP?

$arr1 = array(

    array('id'=>1,'name'=>'aA','cat'=>'cc'),
    array('id'=>2,'name'=>'aa','cat'=>'dd'),
    array('id'=>3,'name'=>'bb','cat'=>'cc'),
    array('id'=>4,'name'=>'bb','cat'=>'dd')
);

$result1 = array_msort($arr1, array('name'=>SORT_DESC);

$result2 = array_msort($arr1, array('cat'=>SORT_ASC);

$result3 = array_msort($arr1, array('name'=>SORT_DESC, 'cat'=>SORT_ASC));


function array_msort($array, $cols)
{
    $colarr = array();
    foreach ($cols as $col => $order) {
    $colarr[$col] = array();
    foreach ($array as $k => $row) { $colarr[$col]['_'.$k] = strtolower($row[$col]); }
}

$eval = 'array_multisort(';

foreach ($cols as $col => $order) {
    $eval .= '$colarr[\''.$col.'\'],'.$order.',';
}

$eval = substr($eval,0,-1).');';
eval($eval);
$ret = array();
foreach ($colarr as $col => $arr) {
    foreach ($arr as $k => $v) {
        $k = substr($k,1);
        if (!isset($ret[$k])) $ret[$k] = $array[$k];
        $ret[$k][$col] = $array[$k][$col];
    }
}
return $ret;


} 

"echo -n" prints "-n"

Try with

echo -e "Some string...\c"

It works for me as expected (as I understood from your question).

Note that I got this information from the man page. The man page also notes the shell may have its own version of echo, and I am not sure if bash has its own version.

Autocompletion in Vim

You can use a plugin like AutoComplPop to get automatic code completion as you type.

2015 Edit: I personally use YouCompleteMe now.

Finding what branch a Git commit came from

For example, to find that c0118fa commit came from redesign_interactions:

* ccfd449 (HEAD -> develop) Require to return undef if no digits found
*   93dd5ff Merge pull request #4 from KES777/clean_api
|\
| * 39d82d1 Fix tc0118faests for debugging debugger internals
| * ed67179 Move &push_frame out of core
| * 2fd84b5 Do not lose info about call point
| * 3ab09a2 Improve debugger output: Show info about emitted events
| *   a435005 Merge branch 'redesign_interactions' into clean_api
| |\
| | * a06cc29 Code comments
| | * d5d6266 Remove copy/paste code
| | * c0118fa Allow command to choose how continue interaction
| | * 19cb534 Emit &interact event

You should run:

git log c0118fa..HEAD --ancestry-path --merges

And scroll down to find last merge commit. Which is:

commit a435005445a6752dfe788b8d994e155b3cd9778f
Merge: 0953cac a06cc29
Author: Eugen Konkov
Date:   Sat Oct 1 00:54:18 2016 +0300

    Merge branch 'redesign_interactions' into clean_api

Update

Or just one command:

git log c0118fa..HEAD --ancestry-path --merges --oneline --color | tail -n 1

How to set password for Redis?

using redis-cli:

root@server:~# redis-cli 
127.0.0.1:6379> CONFIG SET requirepass secret_password
OK

this will set password temporarily (until redis or server restart)

test password:

root@server:~# redis-cli 
127.0.0.1:6379> AUTH secret_password
OK

Fetch API with Cookie

Just adding to the correct answers here for .net webapi2 users.

If you are using cors because your client site is served from a different address as your webapi then you need to also include SupportsCredentials=true on the server side configuration.

        // Access-Control-Allow-Origin
        // https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
        var cors = new EnableCorsAttribute(Settings.CORSSites,"*", "*");
        cors.SupportsCredentials = true;
        config.EnableCors(cors);

Set a persistent environment variable from cmd.exe

An example with VBScript (.vbs)

Sub sety(wsh, action, typey, vary, value)
  Dim wu
  Set wu = wsh.Environment(typey)
  wui = wu.Item(vary)
  Select Case action
    Case "ls"
      WScript.Echo wui
    Case "del"
      On Error Resume Next
      wu.remove(vary)
      On Error Goto 0
    Case "set"
      wu.Item(vary) = value
    Case "add"
      If wui = "" Then
        wu.Item(vary) = value
      ElseIf InStr(UCase(";" & wui & ";"), UCase(";" & value & ";")) = 0 Then
        wu.Item(vary) = value & ";" & wui
      End If
    Case Else
      WScript.Echo "Bad action"
  End Select
End Sub

Dim wsh, args
Set wsh = WScript.CreateObject("WScript.Shell")
Set args = WScript.Arguments
Select Case WScript.Arguments.Length
  Case 3
    value = ""
  Case 4
    value = args(3)
  Case Else
    WScript.Echo "Arguments - 0: ls,del,set,add; 1: user,system, 2: variable; 3: value"
    value = "```"
End Select
If Not value = "```" Then
  ' 0: ls,del,set,add; 1: user,system, 2: variable; 3: value
  sety wsh, args(0), args(1), UCase(args(2)), value
End If

Add new column in Pandas DataFrame Python

You just do an opposite comparison. if Col2 <= 1. This will return a boolean Series with False values for those greater than 1 and True values for the other. If you convert it to an int64 dtype, True becomes 1 and False become 0,

df['Col3'] = (df['Col2'] <= 1).astype(int)

If you want a more general solution, where you can assign any number to Col3 depending on the value of Col2 you should do something like:

df['Col3'] = df['Col2'].map(lambda x: 42 if x > 1 else 55)

Or:

df['Col3'] = 0
condition = df['Col2'] > 1
df.loc[condition, 'Col3'] = 42
df.loc[~condition, 'Col3'] = 55

Iterating through array - java

Using java 8 Stream API could simplify your job.

public static boolean inArray(int[] array, int check) {
    return Stream.of(array).anyMatch(i -> i == check);
}

It's just you have the overhead of creating a new Stream from Array, but this gives exposure to use other Stream API. In your case you may not want to create new method for one-line operation, unless you wish to use this as utility. Hope this helps!

How to create a button programmatically?

Uilabel code 

var label: UILabel = UILabel()
label.frame = CGRectMake(50, 50, 200, 21)
label.backgroundColor = UIColor.blackColor()
label.textColor = UIColor.whiteColor()
label.textAlignment = NSTextAlignment.Center
label.text = "test label"
self.view.addSubview(label)

Logger slf4j advantages of formatting with {} instead of string concatenation

I think from the author's point of view, the main reason is to reduce the overhead for string concatenation.I just read the logger's documentation, you could find following words:

/**
* <p>This form avoids superfluous string concatenation when the logger
* is disabled for the DEBUG level. However, this variant incurs the hidden
* (and relatively small) cost of creating an <code>Object[]</code> before 
  invoking the method,
* even if this logger is disabled for DEBUG. The variants taking
* {@link #debug(String, Object) one} and {@link #debug(String, Object, Object) two}
* arguments exist solely in order to avoid this hidden cost.</p>
*/
*
 * @param format    the format string
 * @param arguments a list of 3 or more arguments
 */
public void debug(String format, Object... arguments);

How to consume REST in Java

JAX-RS but you can also use regular DOM that comes with standard Java

Find all elements with a certain attribute value in jquery

You can use partial value of an attribute to detect a DOM element using (^) sign. For example you have divs like this:

<div id="abc_1"></div>
<div id="abc_2"></div>
<div id="xyz_3"></div>
<div id="xyz_4"></div>...

You can use the code:

var abc = $('div[id^=abc]')

This will return a DOM array of divs which have id starting with abc:

<div id="abc_1"></div>
<div id="abc_2"></div>

Here is the demo: http://jsfiddle.net/mCuWS/

How to override Bootstrap's Panel heading background color?

Bootstrap sometimes uses contextual class constructs. Those are what you should target to change styling.

You don't need to create your own custom class as suggested in the answer from Kiran Varti.

So you only need:

CSS:

.panel-default > .panel-heading {
  background: #black;
}

HTML:

<div class="panel panel-default">

Explanation here. Also see contextual class section here.

To match navbar-inverse use #222. Panel-inverse was requested in V3, but rejected due to larger priorities.

You can change the foreground color in that heading override or you can do it separately for panel titles. Depends what you are trying to achieve.

.panel-title {
  color: white;
}

Converting a value to 2 decimal places within jQuery

You need to use the .toFixed() method

It takes as a parameter the number of digits to show after the decimal point.

$(document).ready(function() {
  $('.add').click(function() {
     var value = parseFloat($('#total').text()) + parseFloat($(this).data('amount'))/100
     $('#total').text( value.toFixed(2) );
  });
})

ExecutorService that interrupts tasks after a timeout

It seems problem is not in JDK bug 6602600 ( it was solved at 2010-05-22), but in incorrect call of sleep(10) in circle. Addition note, that the main Thread must give directly CHANCE to other threads to realize thier tasks by invoke SLEEP(0) in EVERY branch of outer circle. It is better, I think, to use Thread.yield() instead of Thread.sleep(0)

The result corrected part of previous problem code is such like this:

.......................
........................
Thread.yield();         

if (i % 1000== 0) {
System.out.println(i + "/" + counter.get()+ "/"+service.toString());
}

//                
//                while (i > counter.get()) {
//                    Thread.sleep(10);
//                } 

It works correctly with amount of outer counter up to 150 000 000 tested circles.

How to publish a website made by Node.js to Github Pages?

It's very simple steps to push your node js application from local to GitHub.

Steps:

  1. First create a new repository on GitHub
  2. Open Git CMD installed to your system (Install GitHub Desktop)
  3. Clone the repository to your system with the command: git clone repo-url
  4. Now copy all your application files to this cloned library if it's not there
  5. Get everything ready to commit: git add -A
  6. Commit the tracked changes and prepares them to be pushed to a remote repository: git commit -a -m "First Commit"
  7. Push the changes in your local repository to GitHub: git push origin master

Filtering a spark dataframe based on date

The following solutions are applicable since spark 1.5 :

For lower than :

// filter data where the date is lesser than 2015-03-14
data.filter(data("date").lt(lit("2015-03-14")))      

For greater than :

// filter data where the date is greater than 2015-03-14
data.filter(data("date").gt(lit("2015-03-14"))) 

For equality, you can use either equalTo or === :

data.filter(data("date") === lit("2015-03-14"))

If your DataFrame date column is of type StringType, you can convert it using the to_date function :

// filter data where the date is greater than 2015-03-14
data.filter(to_date(data("date")).gt(lit("2015-03-14"))) 

You can also filter according to a year using the year function :

// filter data where year is greater or equal to 2016
data.filter(year($"date").geq(lit(2016))) 

Is there such a thing as min-font-size and max-font-size?

CSS min() and max() have fairly good usage rates in 2020.

The code below uses max() to get the largest of the [variablevalue] and [minimumvalue] and then passes that through to min() against the [maximumvalue] to get the smaller of the two. This creates an allowable font range (3.5rem is minimum, 6.5rem is maximum, 6vw is used only when in between).

font-size: min(max([variablevalue], [minimumvalue]), [maximumvalue]);
font-size: min(max(6vw, 3.5rem), 6.5rem);

I'm using this specifically with font-awesome as a video-play icon over an image within a bootstrap container element where max-width is set.

How can I get a channel ID from YouTube?

To obtain the channel id you can view the source code of the channel page and find either data-channel-external-id="UCjXfkj5iapKHJrhYfAF9ZGg" or "externalId":"UCjXfkj5iapKHJrhYfAF9ZGg".

UCjXfkj5iapKHJrhYfAF9ZGg will be the channel ID you are looking for.

What’s the best RESTful method to return total number of items in an object?

I have been doing some extensive research into this and other REST paging related questions lately and thought it constructive to add some of my findings here. I'm expanding the question a bit to include thoughts on paging as well as the count as they are intimitely related.

Headers

The paging metadata is included in the response in the form of response headers. The big benefit of this approach is that the response payload itself is just the actual data requestor was asking for. Making processing the response easier for clients that are not interested in the paging information.

There are a bunch of (standard and custom) headers used in the wild to return paging related information, including the total count.

X-Total-Count

X-Total-Count: 234

This is used in some APIs I found in the wild. There are also NPM packages for adding support for this header to e.g. Loopback. Some articles recommend setting this header as well.

It is often used in combination with the Link header, which is a pretty good solution for paging, but lacks the total count information.

Link

Link: </TheBook/chapter2>;
      rel="previous"; title*=UTF-8'de'letztes%20Kapitel,
      </TheBook/chapter4>;
      rel="next"; title*=UTF-8'de'n%c3%a4chstes%20Kapitel

I feel, from reading a lot on this subject, that the general consensus is to use the Link header to provide paging links to clients using rel=next, rel=previous etc. The problem with this is that it lacks the information of how many total records there are, which is why many APIs combine this with the X-Total-Count header.

Alternatively, some APIs and e.g. the JsonApi standard, use the Link format, but add the information in a response envelope instead of to a header. This simplifies access to the metadata (and creates a place to add the total count information) at the expense of increasing complexity of accessing the actual data itself (by adding an envelope).

Content-Range

Content-Range: items 0-49/234

Promoted by a blog article named Range header, I choose you (for pagination)!. The author makes a strong case for using the Range and Content-Range headers for pagination. When we carefully read the RFC on these headers, we find that extending their meaning beyond ranges of bytes was actually anticipated by the RFC and is explicitly permitted. When used in the context of items instead of bytes, the Range header actually gives us a way to both request a certain range of items and indicate what range of the total result the response items relate to. This header also gives a great way to show the total count. And it is a true standard that mostly maps one-to-one to paging. It is also used in the wild.

Envelope

Many APIs, including the one from our favorite Q&A website use an envelope, a wrapper around the data that is used to add meta information about the data. Also, OData and JsonApi standards both use a response envelope.

The big downside to this (imho) is that processing the response data becomes more complex as the actual data has to be found somewhere in the envelope. Also there are many different formats for that envelope and you have to use the right one. It is telling that the response envelopes from OData and JsonApi are wildly different, with OData mixing in metadata at multiple points in the response.

Separate endpoint

I think this has been covered enough in the other answers. I did not investigate this much because I agree with the comments that this is confusing as you now have multiple types of endpoints. I think it's nicest if every endpoint represents a (collection of) resource(s).

Further thoughts

We don't only have to communicate the paging meta information related to the response, but also allow the client to request specific pages/ranges. It is interesting to also look at this aspect to end up with a coherent solution. Here too we can use headers (the Range header seems very suitable), or other mechanisms such as query parameters. Some people advocate treating pages of results as separate resources, which may make sense in some use cases (e.g. /books/231/pages/52. I ended up selecting a wild range of frequently used request parameters such as pagesize, page[size] and limit etc in addition to supporting the Range header (and as request parameter as well).

Bootstrap: align input with button

Bootstrap 4:

<div class="input-group">
  <input type="text" class="form-control">
  <div class="input-group-append">
    <button class="btn btn-success" type="button">Button</button>
  </div>
</div>

https://getbootstrap.com/docs/4.0/components/input-group/

Replace characters from a column of a data frame R

chartr is also convenient for these types of substitutions:

chartr("_", "-", data1$c)
#  [1] "A-B" "A-B" "A-B" "A-B" "A-C" "A-C" "A-C" "A-C" "A-C" "A-C"

Thus, you can just do:

data1$c <- chartr("_", "-", data1$c)

How do you get a directory listing in C?

The strict answer is "you can't", as the very concept of a folder is not truly cross-platform.

On MS platforms you can use _findfirst, _findnext and _findclose for a 'c' sort of feel, and FindFirstFile and FindNextFile for the underlying Win32 calls.

Here's the C-FAQ answer:

http://c-faq.com/osdep/readdir.html

How to cast the size_t to double or int C++

You can use Boost numeric_cast.

This throws an exception if the source value is out of range of the destination type, but it doesn't detect loss of precision when converting to double.

Whatever function you use, though, you should decide what you want to happen in the case where the value in the size_t is greater than INT_MAX. If you want to detect it use numeric_cast or write your own code to check. If you somehow know that it cannot possibly happen then you could use static_cast to suppress the warning without the cost of a runtime check, but in most cases the cost doesn't matter anyway.

How can I go back/route-back on vue-router?

Use router.back() directly to go back/route-back programmatic on vue-router.

Android replace the current fragment with another fragment

Latest Stuff

Okay. So this is a very old question and has great answers from that time. But a lot has changed since then.

Now, in 2020, if you are working with Kotlin and want to change the fragment then you can do the following.

  1. Add Kotlin extension for Fragments to your project.

In your app level build.gradle file add the following,

dependencies {
    def fragment_version = "1.2.5"

    // Kotlin
    implementation "androidx.fragment:fragment-ktx:$fragment_version"
    // Testing Fragments in Isolation
    debugImplementation "androidx.fragment:fragment-testing:$fragment_version"
}
  1. Then simple code to replace the fragment,

In your activity

supportFragmentManager.commit {
    replace(R.id.frame_layout, YourFragment.newInstance(), "Your_TAG")
    addToBackStack(null)
}

References

Check latest version of Fragment extension

More on Fragments

Check whether a table contains rows or not sql server 2005

Fast:

SELECT TOP (1) CASE 
        WHEN **NOT_NULL_COLUMN** IS NULL
            THEN 'empty table'
        ELSE 'not empty table'
        END AS info
FROM **TABLE_NAME**

SQL Query to search schema of all tables

I would query the information_schema - this has views that are much more readable than the underlying tables.

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE COLUMN_NAME LIKE '%create%'

How to disable/enable select field using jQuery?

Disabled is a Boolean Attribute of the select element as stated by WHATWG, that means the RIGHT WAY TO DISABLE with jQuery would be

jQuery("#selectId").attr('disabled',true);

This would make this HTML

<select id="selectId" name="gender" disabled="disabled">
    <option value="-1">--Select a Gender--</option>
    <option value="0">Male</option>
    <option value="1">Female</option>
</select>

This works for both XHTML and HTML (W3School reference)

Yet it also can be done using it as property

jQuery("#selectId").prop('disabled', 'disabled');

getting

<select id="selectId" name="gender" disabled>

Which only works for HTML and not XTML

NOTE: A disabled element will not be submitted with the form as answered in this question: The disabled form element is not submitted

NOTE2: A disabled element may be greyed out.

NOTE3:

A form control that is disabled must prevent any click events that are queued on the user interaction task source from being dispatched on the element.

TL;DR

<script>
    var update_pizza = function () {
        if ($("#pizza").is(":checked")) {
            $('#pizza_kind').attr('disabled', false);
        } else {
            $('#pizza_kind').attr('disabled', true);
        }
    };
    $(update_pizza);
    $("#pizza").change(update_pizza);
</script>

Vertical rulers in Visual Studio Code

In addition to global "editor.rulers" setting, it's also possible to set this on a per-language level.

For example, style guides for Python projects often specify either 79 or 120 characters vs. Git commit messages should be no longer than 50 characters.

So in your settings.json, you'd put:

"[git-commit]": {"editor.rulers": [50]},
"[python]": {
    "editor.rulers": [
        79,
        120
    ]
}

Javascript querySelector vs. getElementById

"Better" is subjective.

querySelector is the newer feature.

getElementById is better supported than querySelector.

querySelector is better supported than getElementsByClassName.

querySelector lets you find elements with rules that can't be expressed with getElementById and getElementsByClassName

You need to pick the appropriate tool for any given task.

(In the above, for querySelector read querySelector / querySelectorAll).

How can I get LINQ to return the object which has the max value for a given property?

You could use a captured variable.

Item result = items.FirstOrDefault();
items.ForEach(x =>
{
  if(result.ID < x.ID)
    result = x;
});

How to trigger a phone call when clicking a link in a web page on mobile phone

Essentially, use an <a> element with an href attr pointing to the phone number prefixed by tel:. Note that pluses can be used to specify country code, and hyphens can be included simply for human eyes.

MDN Web Docs

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Creating_a_phone_link

The HTML <a> element (or anchor element), along with its href attribute, creates a hyperlink to other web pages, files, locations within the same page, email addresses, or any other URL.

[…]

Offering phone links is helpful for users viewing web documents and laptops connected to phones.

<a href="tel:+491570156">+49 157 0156</a>

IETF Documents

https://tools.ietf.org/html/rfc3966

The tel URI for Telephone Numbers

The "tel" URI has the following syntax:

telephone-uri = "tel:" telephone-subscriber

[…]

Examples

tel:+1-201-555-0123: This URI points to a phone number in the United States. The hyphens are included to make the number more human readable; they separate country, area code and subscriber number.

tel:7042;phone-context=example.com: The URI describes a local phone number valid within the context "example.com".

tel:863-1234;phone-context=+1-914-555: The URI describes a local phone number that is valid within a particular phone prefix.

Something like 'contains any' for Java set?

There's a bit rough method to do that. If and only if the A set contains some B's element than the call

A.removeAll(B)

will modify the A set. In this situation removeAll will return true (As stated at removeAll docs). But probably you don't want to modify the A set so you may think to act on a copy, like this way:

new HashSet(A).removeAll(B)

and the returning value will be true if the sets are not distinct, that is they have non-empty intersection.

Also see Apache Commons Collections

Visual Studio Code Automatic Imports

I got this working by installing the various plugins below.

Most of the time things just import by themselves as soon as I type the class name. Alternatively, a lightbulb appears that you can click on. Or you can push F1, and type "import..." and there are various options there too. I kinda use all of them. Also F1 Implement for implementing an interface is helpful, but doesn't always work.

List of Plugins

Screenshot of Extensions

screenshot of extensions
*click for full resolution

How can I get the CheckBoxList selected values, what I have doesn't seem to work C#.NET/VisualWebPart

// aspx.cs

// Load CheckBoxList selected items into ListBox

    int status = 1;
    foreach (ListItem  s in chklstStates.Items  )
    {
        if (s.Selected == true)
        {
            if (ListBox1.Items.Count == 0)
            {
                ListBox1.Items.Add(s.Text);

            }
            else
            {
                foreach (ListItem list in ListBox1.Items)
                {
                    if (list.Text == s.Text)
                    {
                        status = status * 0;

                    }
                    else
                    {
                        status = status * 1;
                    }
                }
                if (status == 0)
                { }
               else
                {
                    ListBox1.Items.Add(s.Text);
                }
                status = 1;
            }
        }
    }
}

Can I prevent text in a div block from overflowing?

there is another css property :

white-space : normal;

The white-space property controls how text is handled on the element it is applied to.

div {

  /* This is the default, you don't need to
     explicitly declare it unless overriding
     another declaration */
  white-space: normal; 

}

What are the date formats available in SimpleDateFormat class?

Let me throw out some example code that I got from http://www3.ntu.edu.sg/home/ehchua/programming/java/DateTimeCalendar.html Then you can play around with different options until you understand it.

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateTest {
   public static void main(String[] args) {
       Date now = new Date();

       //This is just Date's toString method and doesn't involve SimpleDateFormat
       System.out.println("toString(): " + now);  // dow mon dd hh:mm:ss zzz yyyy
       //Shows  "Mon Oct 08 08:17:06 EDT 2012"

       SimpleDateFormat dateFormatter = new SimpleDateFormat("E, y-M-d 'at' h:m:s a z");
       System.out.println("Format 1:   " + dateFormatter.format(now));
       // Shows  "Mon, 2012-10-8 at 8:17:6 AM EDT"

       dateFormatter = new SimpleDateFormat("E yyyy.MM.dd 'at' hh:mm:ss a zzz");
       System.out.println("Format 2:   " + dateFormatter.format(now));
       // Shows  "Mon 2012.10.08 at 08:17:06 AM EDT"

       dateFormatter = new SimpleDateFormat("EEEE, MMMM d, yyyy");
       System.out.println("Format 3:   " + dateFormatter.format(now));
       // Shows  "Monday, October 8, 2012"

       // SimpleDateFormat can be used to control the date/time display format:
       //   E (day of week): 3E or fewer (in text xxx), >3E (in full text)
       //   M (month): M (in number), MM (in number with leading zero)
       //              3M: (in text xxx), >3M: (in full text full)
       //   h (hour): h, hh (with leading zero)
       //   m (minute)
       //   s (second)
       //   a (AM/PM)
       //   H (hour in 0 to 23)
       //   z (time zone)
       //  (there may be more listed under the API - I didn't check)

   }

}

Good luck!

Intellij reformat on file save

IntellIJ 14 && 15: When you are checking in code in Commit changes dialog, tick the Reformat code checkbox, then IntelliJ will reformatting all the code that you are checking in.

Source: www.udemy.com/intellij-idea-secrets-double-your-coding-speed-in-2-hours

SQL Server : SUM() of multiple rows including where clauses

sounds like you want something like:

select PropertyID, SUM(Amount)
from MyTable
Where EndDate is null
Group by PropertyID

Cannot enqueue Handshake after invoking quit

inplace of connection.connect(); use -

if(!connection._connectCalled ) 
{
connection.connect();
}

if it is already called then connection._connectCalled =true,
& it will not execute connection.connect();

note - don't use connection.end();

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

C# : 'is' keyword and checking for Not

The extension method IsNot<T> is a nice way to extend the syntax. Keep in mind

var container = child as IContainer;
if(container != null)
{
  // do something w/ contianer
}

performs better than doing something like

if(child is IContainer)
{
  var container = child as IContainer;
  // do something w/ container
}

In your case, it doesn't matter as you are returning from the method. In other words, be careful to not do both the check for type and then the type conversion immediately after.

IP to Location using Javascript

Either one of the following links should take care of this:

http://ipinfodb.com/ip_location_api_json.php

http://www.adam-mcfarland.net/2009/11/19/simple-ip-geolocation-using-javascript-and-the-google-ajax-search-api/

Those links have tutorials for getting a users location through Javascript. However, they do so through an API to an external data service. If you have an extremely high traffic site, you might want to hosting the data yourself (or getting a premium api service). To host everything yourself, you will have to host a database with IP Geolocation and use ajax to feed the users location into Javascript. If this is the approach you want to take, you can get a free database of IP information below:

http://www.ipinfodb.com/ip_database.php

Please note that this method entails having to periodically update the database to stay accurate in tracing ips to locations.

JavaScript listener, "keypress" doesn't detect backspace?

Use one of keyup / keydown / beforeinput events instead.

based on this reference, keypress is deprecated and no longer recommended.

The keypress event is fired when a key that produces a character value is pressed down. Examples of keys that produce a character value are alphabetic, numeric, and punctuation keys. Examples of keys that don't produce a character value are modifier keys such as Alt, Shift, Ctrl, or Meta.

if you use "beforeinput" be careful about it's Browser compatibility. the difference between "beforeinput" and the other two is that "beforeinput" is fired when input value is about to changed, so with characters that can't change the input value, it is not fired (e.g shift, ctr ,alt).

I had the same problem and by using keyup it was solved.

How do you remove a specific revision in the git history?

So here is the scenario that I faced, and how I solved it.

[branch-a]

[Hundreds of commits] -> [R] -> [I]

here R is the commit that I needed to be removed, and I is a single commit that comes after R

I made a revert commit and squashed them together

git revert [commit id of R]
git rebase -i HEAD~3

During the interactive rebase squash the last 2 commits.

scp from remote host to local host

You need the ip of the other pc and do:

scp user@ip_of_remote_pc:/home/user/stuff.php /Users/djorge/Desktop

it will ask you for 'user's password on the other pc.

How to declare a variable in MySQL?

There are mainly three types of variables in MySQL:

  1. User-defined variables (prefixed with @):

    You can access any user-defined variable without declaring it or initializing it. If you refer to a variable that has not been initialized, it has a value of NULL and a type of string.

    SELECT @var_any_var_name
    

    You can initialize a variable using SET or SELECT statement:

    SET @start = 1, @finish = 10;    
    

    or

    SELECT @start := 1, @finish := 10;
    
    SELECT * FROM places WHERE place BETWEEN @start AND @finish;
    

    User variables can be assigned a value from a limited set of data types: integer, decimal, floating-point, binary or nonbinary string, or NULL value.

    User-defined variables are session-specific. That is, a user variable defined by one client cannot be seen or used by other clients.

    They can be used in SELECT queries using Advanced MySQL user variable techniques.

  2. Local Variables (no prefix) :

    Local variables needs to be declared using DECLARE before accessing it.

    They can be used as local variables and the input parameters inside a stored procedure:

    DELIMITER //
    
    CREATE PROCEDURE sp_test(var1 INT) 
    BEGIN   
        DECLARE start  INT unsigned DEFAULT 1;  
        DECLARE finish INT unsigned DEFAULT 10;
    
        SELECT  var1, start, finish;
    
        SELECT * FROM places WHERE place BETWEEN start AND finish; 
    END; //
    
    DELIMITER ;
    
    CALL sp_test(5);
    

    If the DEFAULT clause is missing, the initial value is NULL.

    The scope of a local variable is the BEGIN ... END block within which it is declared.

  3. Server System Variables (prefixed with @@):

    The MySQL server maintains many system variables configured to a default value. They can be of type GLOBAL, SESSION or BOTH.

    Global variables affect the overall operation of the server whereas session variables affect its operation for individual client connections.

    To see the current values used by a running server, use the SHOW VARIABLES statement or SELECT @@var_name.

    SHOW VARIABLES LIKE '%wait_timeout%';
    
    SELECT @@sort_buffer_size;
    

    They can be set at server startup using options on the command line or in an option file. Most of them can be changed dynamically while the server is running using SET GLOBAL or SET SESSION:

    -- Syntax to Set value to a Global variable:
    SET GLOBAL sort_buffer_size=1000000;
    SET @@global.sort_buffer_size=1000000;
    
    -- Syntax to Set value to a Session variable:
    SET sort_buffer_size=1000000;
    SET SESSION sort_buffer_size=1000000;
    SET @@sort_buffer_size=1000000;
    SET @@local.sort_buffer_size=10000;
    

arranging div one below the other

If you want the two divs to be displayed one above the other, the simplest answer is to remove the float: left;from the css declaration, as this causes them to collapse to the size of their contents (or the css defined size), and, well float up against each other.

Alternatively, you could simply add clear:both; to the divs, which will force the floated content to clear previous floats.

How to make a great R reproducible example

Guidelines:


Your main objective in crafting your questions should be to make it as easy as possible for readers to understand and reproduce your problem on their systems. To do so:

  1. Provide input data
  2. Provide expected output
  3. Explain your problem succinctly
    • if you have over 20 lines of text + code, you can probably go back and simplify
    • simplify your code as much as possible while preserving the problem/error

This does take some work, but it seems like a fair trade-off since you ask others to do work for you.

Providing Data:


Built-in Data Sets

The best option by far is to rely on built-in datasets. This makes it very easy for others to work on your problem. Type data() at the R prompt to see what data is available to you. Some classic examples:

  • iris
  • mtcars
  • ggplot2::diamonds (external package, but almost everyone has it)

Inspect the built-in datasets to find one suitable for your problem.

If you can rephrase your problem to use the built-in datasets, you are much more likely to get good answers (and upvotes).

Self Generated Data

If your problem is specific to a type of data that is not represented in the existing data sets, then provide the R code that generates the smallest possible dataset that your problem manifests itself on. For example

set.seed(1)  # important to make random data reproducible
myData <- data.frame(a=sample(letters[1:5], 20, rep=T), b=runif(20))

Someone trying to answer my question can copy/paste those two lines and start working on the problem immediately.

dput

As a last resort, you can use dput to transform a data object to R code (e.g. dput(myData)). I say as a "last resort" because the output of dput is often fairly unwieldy, annoying to copy-paste, and obscures the rest of your question.

Provide Expected Output:


Someone once said:

A picture of expected output is worth 1000 words

-- a sage person

If you can add something like "I expected to get this result":

   cyl   mean.hp
1:   6 122.28571
2:   4  82.63636
3:   8 209.21429

to your question, people are much more likely to understand what you are trying to do quickly. If your expected result is large and unwieldy, then you probably haven't thought enough about how to simplify your problem (see next).

Explain Your Problem Succinctly


The main thing to do is simplify your problem as much as possible before you ask your question. Re-framing the problem to work with the built-in datasets will help a lot in this regard. You will also often find that just by going through the process of simplification, you will answer your own problem.

Here are some examples of good questions:

In both cases, the user's problems are almost certainly not with the simple examples they provide. Rather they abstracted the nature of their problem and applied it to a simple data set to ask their question.

Why Yet Another Answer To This Question?


This answer focuses on what I think is the best practice: use built-in data sets and provide what you expect as a result in a minimal form. The most prominent answers focus on other aspects. I don't expect this answer to rising to any prominence; this is here solely so that I can link to it in comments to newbie questions.

Show a leading zero if a number is less than 10

There's no built-in JavaScript function to do this, but you can write your own fairly easily:

function pad(n) {
    return (n < 10) ? ("0" + n) : n;
}

EDIT:

Meanwhile there is a native JS function that does that. See String#padStart

_x000D_
_x000D_
console.log(String(5).padStart(2, '0'));
_x000D_
_x000D_
_x000D_

ReDim Preserve to a Multi-Dimensional Array in Visual Basic 6

I haven't tested every single one of these answers but you don't need to use complicated functions to accomplish this. It's so much easier than that! My code below will work in any office VBA application (Word, Access, Excel, Outlook, etc.) and is very simple. Hope this helps:

''Dimension 2 Arrays
Dim InnerArray(1 To 3) As Variant ''The inner is for storing each column value of the current row
Dim OuterArray() As Variant ''The outer is for storing each row in
Dim i As Byte

    i = 1
    Do While i <= 5

        ''Enlarging our outer array to store a/another row
        ReDim Preserve OuterArray(1 To i)

        ''Loading the current row column data in
        InnerArray(1) = "My First Column in Row " & i
        InnerArray(2) = "My Second Column in Row " & i
        InnerArray(3) = "My Third Column in Row " & i

        ''Loading the entire row into our array
        OuterArray(i) = InnerArray

        i = i + 1
    Loop

    ''Example print out of the array to the Intermediate Window
    Debug.Print OuterArray(1)(1)
    Debug.Print OuterArray(1)(2)
    Debug.Print OuterArray(2)(1)
    Debug.Print OuterArray(2)(2)

How to align this span to the right of the div?

You can do this without modifying the html. http://jsfiddle.net/8JwhZ/1085/

<div class="title">
<span>Cumulative performance</span>
<span>20/02/2011</span>
</div>

.title span:nth-of-type(1) { float:right }
.title span:nth-of-type(2) { float:left }

How to reload the current route with the angular 2 router

This works for me like a charm

this.router.navigateByUrl('/', {skipLocationChange: true}).then(()=>
this.router.navigate([<route>]));

The simplest possible JavaScript countdown timer?

If you want a real timer you need to use the date object.

Calculate the difference.

Format your string.

window.onload=function(){
      var start=Date.now(),r=document.getElementById('r');
      (function f(){
      var diff=Date.now()-start,ns=(((3e5-diff)/1e3)>>0),m=(ns/60)>>0,s=ns-m*60;
      r.textContent="Registration closes in "+m+':'+((''+s).length>1?'':'0')+s;
      if(diff>3e5){
         start=Date.now()
      }
      setTimeout(f,1e3);
      })();
}

Example

Jsfiddle

not so precise timer

var time=5*60,r=document.getElementById('r'),tmp=time;

setInterval(function(){
    var c=tmp--,m=(c/60)>>0,s=(c-m*60)+'';
    r.textContent='Registration closes in '+m+':'+(s.length>1?'':'0')+s
    tmp!=0||(tmp=time);
},1000);

JsFiddle

Will Google Android ever support .NET?

A modified port of Mono is also entirely possible.

Perform debounce in React.js

2019: try hooks + promise debouncing

This is the most up to date version of how I would solve this problem. I would use:

This is some initial wiring but you are composing primitive blocks on your own, and you can make your own custom hook so that you only need to do this once.

// Generic reusable hook
const useDebouncedSearch = (searchFunction) => {

  // Handle the input text state
  const [inputText, setInputText] = useState('');

  // Debounce the original search async function
  const debouncedSearchFunction = useConstant(() =>
    AwesomeDebouncePromise(searchFunction, 300)
  );

  // The async callback is run each time the text changes,
  // but as the search function is debounced, it does not
  // fire a new request on each keystroke
  const searchResults = useAsync(
    async () => {
      if (inputText.length === 0) {
        return [];
      } else {
        return debouncedSearchFunction(inputText);
      }
    },
    [debouncedSearchFunction, inputText]
  );

  // Return everything needed for the hook consumer
  return {
    inputText,
    setInputText,
    searchResults,
  };
};

And then you can use your hook:

const useSearchStarwarsHero = () => useDebouncedSearch(text => searchStarwarsHeroAsync(text))

const SearchStarwarsHeroExample = () => {
  const { inputText, setInputText, searchResults } = useSearchStarwarsHero();
  return (
    <div>
      <input value={inputText} onChange={e => setInputText(e.target.value)} />
      <div>
        {searchResults.loading && <div>...</div>}
        {searchResults.error && <div>Error: {search.error.message}</div>}
        {searchResults.result && (
          <div>
            <div>Results: {search.result.length}</div>
            <ul>
              {searchResults.result.map(hero => (
                <li key={hero.name}>{hero.name}</li>
              ))}
            </ul>
          </div>
        )}
      </div>
    </div>
  );
};

You will find this example running here and you should read react-async-hook documentation for more details.


2018: try promise debouncing

We often want to debounce API calls to avoid flooding the backend with useless requests.

In 2018, working with callbacks (Lodash/Underscore) feels bad and error-prone to me. It's easy to encounter boilerplate and concurrency issues due to API calls resolving in an arbitrary order.

I've created a little library with React in mind to solve your pains: awesome-debounce-promise.

This should not be more complicated than that:

const searchAPI = text => fetch('/search?text=' + encodeURIComponent(text));

const searchAPIDebounced = AwesomeDebouncePromise(searchAPI, 500);

class SearchInputAndResults extends React.Component {
  state = {
    text: '',
    results: null,
  };

  handleTextChange = async text => {
    this.setState({ text, results: null });
    const result = await searchAPIDebounced(text);
    this.setState({ result });
  };
}

The debounced function ensures that:

  • API calls will be debounced
  • the debounced function always returns a promise
  • only the last call's returned promise will resolve
  • a single this.setState({ result }); will happen per API call

Eventually, you may add another trick if your component unmounts:

componentWillUnmount() {
  this.setState = () => {};
}

Note that Observables (RxJS) can also be a great fit for debouncing inputs, but it's a more powerful abstraction which may be harder to learn/use correctly.


< 2017: still want to use callback debouncing?

The important part here is to create a single debounced (or throttled) function per component instance. You don't want to recreate the debounce (or throttle) function everytime, and you don't want either multiple instances to share the same debounced function.

I'm not defining a debouncing function in this answer as it's not really relevant, but this answer will work perfectly fine with _.debounce of underscore or lodash, as well as any user-provided debouncing function.


GOOD IDEA:

Because debounced functions are stateful, we have to create one debounced function per component instance.

ES6 (class property): recommended

class SearchBox extends React.Component {
    method = debounce(() => { 
      ...
    });
}

ES6 (class constructor)

class SearchBox extends React.Component {
    constructor(props) {
        super(props);
        this.method = debounce(this.method.bind(this),1000);
    }
    method() { ... }
}

ES5

var SearchBox = React.createClass({
    method: function() {...},
    componentWillMount: function() {
       this.method = debounce(this.method.bind(this),100);
    },
});

See JsFiddle: 3 instances are producing 1 log entry per instance (that makes 3 globally).


NOT a good idea:

var SearchBox = React.createClass({
  method: function() {...},
  debouncedMethod: debounce(this.method, 100);
});

It won't work, because during class description object creation, this is not the object created itself. this.method does not return what you expect because the this context is not the object itself (which actually does not really exist yet BTW as it is just being created).


NOT a good idea:

var SearchBox = React.createClass({
  method: function() {...},
  debouncedMethod: function() {
      var debounced = debounce(this.method,100);
      debounced();
  },
});

This time you are effectively creating a debounced function that calls your this.method. The problem is that you are recreating it on every debouncedMethod call, so the newly created debounce function does not know anything about former calls! You must reuse the same debounced function over time or the debouncing will not happen.


NOT a good idea:

var SearchBox = React.createClass({
  debouncedMethod: debounce(function () {...},100),
});

This is a little bit tricky here.

All the mounted instances of the class will share the same debounced function, and most often this is not what you want!. See JsFiddle: 3 instances are producting only 1 log entry globally.

You have to create a debounced function for each component instance, and not a single debounced function at the class level, shared by each component instance.


Take care of React's event pooling

This is related because we often want to debounce or throttle DOM events.

In React, the event objects (i.e., SyntheticEvent) that you receive in callbacks are pooled (this is now documented). This means that after the event callback has be called, the SyntheticEvent you receive will be put back in the pool with empty attributes to reduce the GC pressure.

So if you access SyntheticEvent properties asynchronously to the original callback (as may be the case if you throttle/debounce), the properties you access may be erased. If you want the event to never be put back in the pool, you can use the persist() method.

Without persist (default behavior: pooled event)

onClick = e => {
  alert(`sync -> hasNativeEvent=${!!e.nativeEvent}`);
  setTimeout(() => {
    alert(`async -> hasNativeEvent=${!!e.nativeEvent}`);
  }, 0);
};

The 2nd (async) will print hasNativeEvent=false because the event properties have been cleaned up.

With persist

onClick = e => {
  e.persist();
  alert(`sync -> hasNativeEvent=${!!e.nativeEvent}`);
  setTimeout(() => {
    alert(`async -> hasNativeEvent=${!!e.nativeEvent}`);
  }, 0);
};

The 2nd (async) will print hasNativeEvent=true because persist allows you to avoid putting the event back in the pool.

You can test these 2 behaviors here: JsFiddle

Read Julen's answer for an example of using persist() with a throttle/debounce function.