Programs & Examples On #Rim 4.3

What are the basic rules and idioms for operator overloading?

Why can't operator<< function for streaming objects to std::cout or to a file be a member function?

Let's say you have:

struct Foo
{
   int a;
   double b;

   std::ostream& operator<<(std::ostream& out) const
   {
      return out << a << " " << b;
   }
};

Given that, you cannot use:

Foo f = {10, 20.0};
std::cout << f;

Since operator<< is overloaded as a member function of Foo, the LHS of the operator must be a Foo object. Which means, you will be required to use:

Foo f = {10, 20.0};
f << std::cout

which is very non-intuitive.

If you define it as a non-member function,

struct Foo
{
   int a;
   double b;
};

std::ostream& operator<<(std::ostream& out, Foo const& f)
{
   return out << f.a << " " << f.b;
}

You will be able to use:

Foo f = {10, 20.0};
std::cout << f;

which is very intuitive.

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

How to do what @connor said:

iOS

  • Open platforms/ios on XCode
  • Find & Replace io.ionic.starter in all files for a unique identifier
  • Click the project to open settings
  • Signing > Select a team
  • Go to your device Settings > General > DeviceManagement
    • Trust your account/team
  • ionic cordova run ios --device --livereload

Clicking HTML 5 Video element to play, pause video, breaks play button

I had this same problem and solved it by adding an event handler for the play action in addition to the click action. I hide the controls while playing to avoid the pause button issue.

    var v = document.getElementById('videoID');
    v.addEventListener(
       'play', 
          function() { 
             v.play();
          }, 
        false);

    v.onclick = function() {
      if (v.paused) {
        v.play();
        v.controls=null;
      } else {
        v.pause();
        v.controls="controls";
      }
    };

Seeking still acts funny though, but at least the confusion with the play control is gone. Hope this helps.

Anyone have a solution to that?

How to avoid Sql Query Timeout

This is happen because another instance of sql server is running. So you need to kill first then you can able to login to SQL Server.

For that go to Task Manager and Kill or End Task the SQL Server service then go to Services.msc and start the SQL Server service.

How can I solve the error 'TS2532: Object is possibly 'undefined'?

With the release of TypeScript 3.7, optional chaining (the ? operator) is now officially available.

As such, you can simplify your expression to the following:

const data = change?.after?.data();

You may read more about it from that version's release notes, which cover other interesting features released on that version.

Run the following to install the latest stable release of TypeScript.

npm install typescript

That being said, Optional Chaining can be used alongside Nullish Coalescing to provide a fallback value when dealing with null or undefined values

const data = change?.after?.data() ?? someOtherData();

Sample settings.xml

A standard Maven settings.xml file is as follows:

<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>

  <proxies>
    <proxy>
      <active/>
      <protocol/>
      <username/>
      <password/>
      <port/>
      <host/>
      <nonProxyHosts/>
      <id/>
    </proxy>
  </proxies>

  <servers>
    <server>
      <username/>
      <password/>
      <privateKey/>
      <passphrase/>
      <filePermissions/>
      <directoryPermissions/>
      <configuration/>
      <id/>
    </server>
  </servers>

  <mirrors>
    <mirror>
      <mirrorOf/>
      <name/>
      <url/>
      <layout/>
      <mirrorOfLayouts/>
      <id/>
    </mirror>
  </mirrors>

  <profiles>
    <profile>
      <activation>
        <activeByDefault/>
        <jdk/>
        <os>
          <name/>
          <family/>
          <arch/>
          <version/>
        </os>
        <property>
          <name/>
          <value/>
        </property>
        <file>
          <missing/>
          <exists/>
        </file>
      </activation>
      <properties>
        <key>value</key>
      </properties>

      <repositories>
        <repository>
          <releases>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </releases>
          <snapshots>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </snapshots>
          <id/>
          <name/>
          <url/>
          <layout/>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <releases>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </releases>
          <snapshots>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </snapshots>
          <id/>
          <name/>
          <url/>
          <layout/>
        </pluginRepository>
      </pluginRepositories>
      <id/>
    </profile>
  </profiles>

  <activeProfiles/>
  <pluginGroups/>
</settings>

To access a proxy, you can find detailed information on the official Maven page here:

Maven-Settings - Settings

I hope it helps for someone.

NULL values inside NOT IN clause

Query A is the same as:

select 'true' where 3 = 1 or 3 = 2 or 3 = 3 or 3 = null

Since 3 = 3 is true, you get a result.

Query B is the same as:

select 'true' where 3 <> 1 and 3 <> 2 and 3 <> null

When ansi_nulls is on, 3 <> null is UNKNOWN, so the predicate evaluates to UNKNOWN, and you don't get any rows.

When ansi_nulls is off, 3 <> null is true, so the predicate evaluates to true, and you get a row.

How to write header row with csv.DictWriter?

Edit:
In 2.7 / 3.2 there is a new writeheader() method. Also, John Machin's answer provides a simpler method of writing the header row.
Simple example of using the writeheader() method now available in 2.7 / 3.2:

from collections import OrderedDict
ordered_fieldnames = OrderedDict([('field1',None),('field2',None)])
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=ordered_fieldnames)
    dw.writeheader()
    # continue on to write data

Instantiating DictWriter requires a fieldnames argument.
From the documentation:

The fieldnames parameter identifies the order in which values in the dictionary passed to the writerow() method are written to the csvfile.

Put another way: The Fieldnames argument is required because Python dicts are inherently unordered.
Below is an example of how you'd write the header and data to a file.
Note: with statement was added in 2.6. If using 2.5: from __future__ import with_statement

with open(infile,'rb') as fin:
    dr = csv.DictReader(fin, delimiter='\t')

# dr.fieldnames contains values from first row of `f`.
with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    headers = {} 
    for n in dw.fieldnames:
        headers[n] = n
    dw.writerow(headers)
    for row in dr:
        dw.writerow(row)

As @FM mentions in a comment, you can condense header-writing to a one-liner, e.g.:

with open(outfile,'wb') as fou:
    dw = csv.DictWriter(fou, delimiter='\t', fieldnames=dr.fieldnames)
    dw.writerow(dict((fn,fn) for fn in dr.fieldnames))
    for row in dr:
        dw.writerow(row)

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

HTML set image on browser tab

<link rel="SHORTCUT ICON" href="favicon.ico" type="image/x-icon" />
<link rel="ICON" href="favicon.ico" type="image/ico" />

Excellent tool for cross-browser favicon - http://www.convertico.com/

"Uncaught TypeError: Illegal invocation" in Chrome

In your code you are assigning a native method to a property of custom object. When you call support.animationFrame(function () {}) , it is executed in the context of current object (ie support). For the native requestAnimationFrame function to work properly, it must be executed in the context of window.

So the correct usage here is support.animationFrame.call(window, function() {});.

The same happens with alert too:

var myObj = {
  myAlert : alert //copying native alert to an object
};

myObj.myAlert('this is an alert'); //is illegal
myObj.myAlert.call(window, 'this is an alert'); // executing in context of window 

Another option is to use Function.prototype.bind() which is part of ES5 standard and available in all modern browsers.

var _raf = window.requestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        window.oRequestAnimationFrame;

var support = {
   animationFrame: _raf ? _raf.bind(window) : null
};

How to get input field value using PHP

If its a get request use, $_GET['subject'] or if its a post request use, $_POST['subject']

Pandas - Get first row value of a given column

To select the ith row, use iloc:

In [31]: df_test.iloc[0]
Out[31]: 
ATime     1.2
X         2.0
Y        15.0
Z         2.0
Btime     1.2
C        12.0
D        25.0
E        12.0
Name: 0, dtype: float64

To select the ith value in the Btime column you could use:

In [30]: df_test['Btime'].iloc[0]
Out[30]: 1.2

There is a difference between df_test['Btime'].iloc[0] (recommended) and df_test.iloc[0]['Btime']:

DataFrames store data in column-based blocks (where each block has a single dtype). If you select by column first, a view can be returned (which is quicker than returning a copy) and the original dtype is preserved. In contrast, if you select by row first, and if the DataFrame has columns of different dtypes, then Pandas copies the data into a new Series of object dtype. So selecting columns is a bit faster than selecting rows. Thus, although df_test.iloc[0]['Btime'] works, df_test['Btime'].iloc[0] is a little bit more efficient.

There is a big difference between the two when it comes to assignment. df_test['Btime'].iloc[0] = x affects df_test, but df_test.iloc[0]['Btime'] may not. See below for an explanation of why. Because a subtle difference in the order of indexing makes a big difference in behavior, it is better to use single indexing assignment:

df.iloc[0, df.columns.get_loc('Btime')] = x

df.iloc[0, df.columns.get_loc('Btime')] = x (recommended):

The recommended way to assign new values to a DataFrame is to avoid chained indexing, and instead use the method shown by andrew,

df.loc[df.index[n], 'Btime'] = x

or

df.iloc[n, df.columns.get_loc('Btime')] = x

The latter method is a bit faster, because df.loc has to convert the row and column labels to positional indices, so there is a little less conversion necessary if you use df.iloc instead.


df['Btime'].iloc[0] = x works, but is not recommended:

Although this works, it is taking advantage of the way DataFrames are currently implemented. There is no guarantee that Pandas has to work this way in the future. In particular, it is taking advantage of the fact that (currently) df['Btime'] always returns a view (not a copy) so df['Btime'].iloc[n] = x can be used to assign a new value at the nth location of the Btime column of df.

Since Pandas makes no explicit guarantees about when indexers return a view versus a copy, assignments that use chained indexing generally always raise a SettingWithCopyWarning even though in this case the assignment succeeds in modifying df:

In [22]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])
In [24]: df['bar'] = 100
In [25]: df['bar'].iloc[0] = 99
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
  self._setitem_with_indexer(indexer, value)

In [26]: df
Out[26]: 
  foo  bar
0   A   99  <-- assignment succeeded
2   B  100
1   C  100

df.iloc[0]['Btime'] = x does not work:

In contrast, assignment with df.iloc[0]['bar'] = 123 does not work because df.iloc[0] is returning a copy:

In [66]: df.iloc[0]['bar'] = 123
/home/unutbu/data/binky/bin/ipython:1: SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame

See the caveats in the documentation: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy

In [67]: df
Out[67]: 
  foo  bar
0   A   99  <-- assignment failed
2   B  100
1   C  100

Warning: I had previously suggested df_test.ix[i, 'Btime']. But this is not guaranteed to give you the ith value since ix tries to index by label before trying to index by position. So if the DataFrame has an integer index which is not in sorted order starting at 0, then using ix[i] will return the row labeled i rather than the ith row. For example,

In [1]: df = pd.DataFrame({'foo':list('ABC')}, index=[0,2,1])

In [2]: df
Out[2]: 
  foo
0   A
2   B
1   C

In [4]: df.ix[1, 'foo']
Out[4]: 'C'

Using variables inside a bash heredoc

Don't use quotes with <<EOF:

var=$1
sudo tee "/path/to/outfile" > /dev/null <<EOF
Some text that contains my $var
EOF

Variable expansion is the default behavior inside of here-docs. You disable that behavior by quoting the label (with single or double quotes).

Modifying local variable from inside lambda

I had a slightly different problem. Instead of incrementing a local variable in the forEach, I needed to assign an object to the local variable.

I solved this by defining a private inner domain class that wraps both the list I want to iterate over (countryList) and the output I hope to get from that list (foundCountry). Then using Java 8 "forEach", I iterate over the list field, and when the object I want is found, I assign that object to the output field. So this assigns a value to a field of the local variable, not changing the local variable itself. I believe that since the local variable itself is not changed, the compiler doesn't complain. I can then use the value that I captured in the output field, outside of the list.

Domain Object:

public class Country {

    private int id;
    private String countryName;

    public Country(int id, String countryName){
        this.id = id;
        this.countryName = countryName;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getCountryName() {
        return countryName;
    }

    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
}

Wrapper object:

private class CountryFound{
    private final List<Country> countryList;
    private Country foundCountry;
    public CountryFound(List<Country> countryList, Country foundCountry){
        this.countryList = countryList;
        this.foundCountry = foundCountry;
    }
    public List<Country> getCountryList() {
        return countryList;
    }
    public void setCountryList(List<Country> countryList) {
        this.countryList = countryList;
    }
    public Country getFoundCountry() {
        return foundCountry;
    }
    public void setFoundCountry(Country foundCountry) {
        this.foundCountry = foundCountry;
    }
}

Iterate operation:

int id = 5;
CountryFound countryFound = new CountryFound(countryList, null);
countryFound.getCountryList().forEach(c -> {
    if(c.getId() == id){
        countryFound.setFoundCountry(c);
    }
});
System.out.println("Country found: " + countryFound.getFoundCountry().getCountryName());

You could remove the wrapper class method "setCountryList()" and make the field "countryList" final, but I did not get compilation errors leaving these details as-is.

How to create a checkbox with a clickable label?

You could also use CSS pseudo elements to pick and display your labels from all your checkbox's value attributes (respectively).
Edit: This will only work with webkit and blink based browsers (Chrome(ium), Safari, Opera....) and thus most mobile browsers. No Firefox or IE support here.
This may only be useful when embedding webkit/blink onto your apps.

<input type="checkbox" value="My checkbox label value" />
<style>
[type=checkbox]:after {
    content: attr(value);
    margin: -3px 15px;
    vertical-align: top;
    white-space:nowrap;
    display: inline-block;
}
</style>

All pseudo element labels will be clickable.

Demo:http://codepen.io/mrmoje/pen/oteLl, + The gist of it

This app won't run unless you update Google Play Services (via Bazaar)

I've been trying to run an Android Google Maps v2 under an emulator, and I found many ways to do that, but none of them worked for me. I have always this warning in the Logcat Google Play services out of date. Requires 3025100 but found 2010110 and when I want to update Google Play services on the emulator nothing happened. The problem was that the com.google.android.gms APK was not compatible with the version of the library in my Android SDK.

I installed these files "com.google.android.gms.apk", "com.android.vending.apk" on my emulator and my app Google Maps v2 worked fine. None of the other steps regarding /system/app were required.

Jenkins / Hudson environment variables

Couldn't you just add it as an environment variable in Jenkins settings:

Manage Jenkins -> Global properties > Environment variables: And then click "Add" to add a property PATH and its value to what you need.

How to set div width using ng-style

ngStyle accepts a map:

$scope.myStyle = {
    "width" : "900px",
    "background" : "red"
};

Fiddle

Spring Boot War deployed to Tomcat

Hey make sure to do this changes to the pom.xml

<packaging>war</packaging>

in the dependencies section make sure to indicated the tomcat is provided so you dont need the embeded tomcat plugin.

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>       

    <dependency>
        <groupId>org.apache.tomcat.embed</groupId>
        <artifactId>tomcat-embed-jasper</artifactId>
        <scope>provided</scope>
    </dependency>       

This is the whole pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.4.0.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <start-class>com.example.Application</start-class>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>       

        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>       

    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>


</project>

And the Application class should be like this

Application.java

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

@SpringBootApplication
public class Application extends SpringBootServletInitializer {


    /**
     * Used when run as JAR
     */
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    /**
     * Used when run as WAR
     */
    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(Application.class);
    }

}

And you can add a controller for testing MyController.java

package com.example;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class MyController {

    @RequestMapping("/hi")
    public @ResponseBody String hiThere(){
        return "hello world!";
    }
}

Then you can run the project in a tomcat 8 version and access the controller like this

http://localhost:8080/demo/hi

If for some reason you are not able to add the project to tomcat do a right click in the project and then go to the Build Path->configure build path->Project Faces

make sure only this 3 are selected

Dynamic web Module 3.1 Java 1.8 Javascript 1.0

I want to load another HTML page after a specific amount of time

<script>
    setTimeout(function(){
        window.location.href = 'form2.html';
    }, 5000);
</script>

And for home page add only '/'

<script>
    setTimeout(function(){
        window.location.href = '/';
    }, 5000);
</script>

SVN undo delete before commit

What worked for me is

svn revert --depth infinity deletedDir

Merge 2 DataTables and store in a new one

dtAll = dtOne.Copy();
dtAll.Merge(dtTwo,true);

The parameter TRUE preserve the changes.

For more details refer to MSDN.

Visual Studio C# IntelliSense not automatically displaying

Sometimes i've found Intellisense to be slow. Hit the . and wait for a minute and see if it appears after a delay. If so, then I believe there may be a cache that can be deleted to get it to rescan.

How to handle click event in Button Column in Datagridview?

Most voted solution is wrong, as cannot work with few buttons in one row.

Best solution will be the following code:

private void dataGridView_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            var senderGrid = (DataGridView)sender;

            if (e.ColumnIndex == senderGrid.Columns["Opn"].Index && e.RowIndex >= 0)
            {
                MessageBox.Show("Opn Click");
            }

            if (e.ColumnIndex == senderGrid.Columns["VT"].Index && e.RowIndex >= 0)
            {
                MessageBox.Show("VT Click");
            }
        }

Using reCAPTCHA on localhost

It's so easy:

  1. Go to your google reCaptcha admin panel
  2. Add localhost & 127.0.0.1 to domains of a new site like the following image.

enter image description here


Update:

If your question is how to set reCaptcha in Google site for using it in localhost, then i has been wrote it above but if you are curious that how you can using reCAPTCHA on both localhost and website host by minimal codes in your controller and prevent some codes like ConfigurationManager.AppSettings["ReCaptcha:SiteKey"] in it then I help you with this extra description and codes in my answer.

Do you like the following GET and POST actions?

It support reCaptcha and doesn't need any other codes for handling reCaptcha.

[HttpGet]
[Recaptcha]
public ActionResult Register()
{
    // Your codes in GET action
}

[HttpPost]
[Recaptcha]
[ValidateAntiForgeryToken]
public ActionResult Register(RegisterViewModel model, string reCaptcha_SecretKey){
   // Your codes in POST action
   if (!ModelState.IsValid || !ReCaptcha.Validate(reCaptcha_SecretKey))
   {
       // Your codes
   }
   // Your codes
}

In View: (reference)

@ReCaptcha.GetHtml(@ViewBag.publicKey)

@if (ViewBag.RecaptchaLastErrors != null)
{
    <div>Oops! Invalid reCAPTCHA =(</div>
}

To use it

A) Add the following ActionFilter to your Web project:

public class RecaptchaAttribute : FilterAttribute, IActionFilter
{
    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var setting_Key = filterContext.HttpContext.Request.IsLocal ? "ReCaptcha_Local" : "ReCaptcha";
        filterContext.ActionParameters["ReCaptcha_SecretKey"] = ConfigurationManager.AppSettings[$"{setting_Key}:SecretKey"];
    }

    public void OnActionExecuted(ActionExecutedContext filterContext)
    {
        var setting_Key = filterContext.HttpContext.Request.IsLocal ? "ReCaptcha_Local" : "ReCaptcha";
        filterContext.Controller.ViewBag.Recaptcha = ReCaptcha.GetHtml(publicKey: ConfigurationManager.AppSettings[$"{setting_Key}:SiteKey"]);
        filterContext.Controller.ViewBag.publicKey = ConfigurationManager.AppSettings[$"{setting_Key}:SiteKey"];
    }
}

B) Add the reCaptcha settings keys for both localhost & website like it in your webconfig file:

<appSettings>

    <!-- RECAPTCHA SETTING KEYS FOR LOCALHOST -->
    <add key="ReCaptcha_Local:SiteKey" value="[Localhost SiteKey]" />
    <add key="ReCaptcha_Local:SecretKey" value="[Localhost SecretKey]" />
    <!-- RECAPTCHA SETTING KEYS FOR WEBSITE -->
    <!--<add key="ReCaptcha:SiteKey" value="[Webite SiteKey]" />
    <add key="ReCaptcha:SecretKey" value="[Webite SecretKey]" />-->

    <!-- OTHER SETTING KEYS OF YOUR PROJECT -->

</appSettings>

Note: By this way you did not need set reCaptcha_SecretKey parameter in the post action or any ViewBag for reCaptcha manually in your Actions and Views, all of them will be filled automatically at runtime with appropriate values depending on you have run the project on the localhost or website.

How to randomize Excel rows

Perhaps the whole column full of random numbers is not the best way to do it, but it seems like probably the most practical as @mariusnn mentioned.

On that note, this stomped me for a while with Office 2010, and while generally answers like the one in lifehacker work,I just wanted to share an extra step required for the numbers to be unique:

  1. Create a new column next to the list that you're going to randomize
  2. Type in =rand() in the first cell of the new column - this will generate a random number between 0 and 1
  3. Fill the column with that formula. The easiest way to do this may be to:

    • go down along the new column up until the last cell that you want to randomize
    • hold down Shift and click on the last cell
    • press Ctrl+D
  4. Now you should have a column of identical numbers, even though they are all generated randomly.

    Random numbers... that are the same...

    The trick here is to recalculate them! Go to the Formulas tab and then click on Calculate Now (or press F9).

    Actually random numbers!

    Now all the numbers in the column will be actually generated randomly.

  5. Go to the Home tab and click on Sort & Filter. Choose whichever order you want (Smallest to Largest or Largest to Smallest) - whichever one will give you a random order with respect to the original order. Then click OK when the Sort Warning prompts you to Expand the selection.

  6. Your list should be randomized now! You can get rid of the column of random numbers if you want.

Changing background color of text box input not working when empty

<! DOCTYPE html>
<html>
<head></head>
<body>

    <input type="text" id="subEmail">


    <script type="text/javascript">

        window.onload = function(){

        var subEmail = document.getElementById("subEmail");

        subEmail.onchange = function(){

            if(subEmail.value == "")
            {
                subEmail.style.backgroundColor = "red";
            }
            else
            {
               subEmail.style.backgroundColor = "yellow"; 
            }
        };

    };



    </script>

</body>

Can I use Objective-C blocks as properties?

Here's an example of how you would accomplish such a task:

#import <Foundation/Foundation.h>
typedef int (^IntBlock)();

@interface myobj : NSObject
{
    IntBlock compare;
}

@property(readwrite, copy) IntBlock compare;

@end

@implementation myobj

@synthesize compare;

- (void)dealloc 
{
   // need to release the block since the property was declared copy. (for heap
   // allocated blocks this prevents a potential leak, for compiler-optimized 
   // stack blocks it is a no-op)
   // Note that for ARC, this is unnecessary, as with all properties, the memory management is handled for you.
   [compare release];
   [super dealloc];
}
@end

int main () {
    @autoreleasepool {
        myobj *ob = [[myobj alloc] init];
        ob.compare = ^
        {
            return rand();
        };
        NSLog(@"%i", ob.compare());
        // if not ARC
        [ob release];
    }

    return 0;
}

Now, the only thing that would need to change if you needed to change the type of compare would be the typedef int (^IntBlock)(). If you need to pass two objects to it, change it to this: typedef int (^IntBlock)(id, id), and change your block to:

^ (id obj1, id obj2)
{
    return rand();
};

I hope this helps.

EDIT March 12, 2012:

For ARC, there are no specific changes required, as ARC will manage the blocks for you as long as they are defined as copy. You do not need to set the property to nil in your destructor, either.

For more reading, please check out this document: http://clang.llvm.org/docs/AutomaticReferenceCounting.html

How to sum columns in a dataTable?

It's a pity to use .NET and not use collections and lambda to save your time and code lines This is an example of how this works: Transform yourDataTable to Enumerable, filter it if you want , according a "FILTER_ROWS_FIELD" column, and if you want, group your data by a "A_GROUP_BY_FIELD". Then get the count, the sum, or whatever you wish. If you want a count and a sum without grouby don't group the data

var groupedData = from b in yourDataTable.AsEnumerable().Where(r=>r.Field<int>("FILTER_ROWS_FIELD").Equals(9999))
                          group b by b.Field<string>("A_GROUP_BY_FIELD") into g
                          select new
                          {
                              tag = g.Key,
                              count = g.Count(),
                              sum = g.Sum(c => c.Field<double>("rvMoney"))
                          };

Can an AJAX response set a cookie?

According to the w3 spec section 4.6.3 for XMLHttpRequest a user agent should honor the Set-Cookie header. So the answer is yes you should be able to.

Quotation:

If the user agent supports HTTP State Management it should persist, discard and send cookies (as received in the Set-Cookie response header, and sent in the Cookie header) as applicable.

How to declare an array in Python?

I would normally just do a = [1,2,3] which is actually a list but for arrays look at this formal definition

How to get min, seconds and milliseconds from datetime.now() in python?

This solution is very similar to that provided by @gdw2 , only that the string formatting is correctly done to match what you asked for - "Should be as compact as possible"

>>> import datetime
>>> a = datetime.datetime.now()
>>> "%s:%s.%s" % (a.minute, a.second, str(a.microsecond)[:2])
'31:45.57'

How to get user name using Windows authentication in asp.net?

This should work:

User.Identity.Name

Identity returns an IPrincipal

Here is the link to the Microsoft documentation.

How to copy selected files from Android with adb pull

You can move your files to other folder and then pull whole folder.

adb shell mkdir /sdcard/tmp
adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir
adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end)
adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back
adb shell rmdir /sdcard/tmp # remove temporary directory

Solving a "communications link failure" with JDBC and MySQL

It is majorly because of weak connection between mysql client and remote mysql server.

In my case it is because of flaky VPN connection.

String comparison in bash. [[: not found

Is the first line in your script:

#!/bin/bash

or

#!/bin/sh

the sh shell produces this error messages, not bash

What linux shell command returns a part of a string?

expr(1) has a substr subcommand:

expr substr <string> <start-index> <length>

This may be useful if you don't have bash (perhaps embedded Linux) and you don't want the extra "echo" process you need to use cut(1).

Checking if a variable is initialized

If you mean how to check whether member variables have been initialized, you can do this by assigning them sentinel values in the constructor. Choose sentinel values as values that will never occur in normal usage of that variable. If a variables entire range is considered valid, you can create a boolean to indicate whether it has been initialized.

#include <limits>

class MyClass
{
    void SomeMethod();

    char mCharacter;
    bool isCharacterInitialized;
    double mDecimal;

    MyClass()
    : isCharacterInitialized(false)
    , mDecimal( std::numeric_limits<double>::quiet_NaN() )
    {}


};


void MyClass::SomeMethod()
{
    if ( isCharacterInitialized == false )
    {
        // do something with mCharacter.
    }

    if ( mDecimal != mDecimal ) // if true, mDecimal == NaN
    {
        // define mDecimal.
    }
}

Check if file is already open

On Windows I found the answer https://stackoverflow.com/a/13706972/3014879 using

fileIsLocked = !file.renameTo(file)

most useful, as it avoids false positives when processing write protected (or readonly) files.

Connecting to a network folder with username/password in Powershell

PowerShell 3 supports this out of the box now.

If you're stuck on PowerShell 2, you basically have to use the legacy net use command (as suggested earlier).

Extract year from date

This is more advice than a specific answer, but my suggestion is to convert dates to date variables immediately, rather than keeping them as strings. This way you can use date (and time) functions on them, rather than trying to use very troublesome workarounds.

As pointed out, the lubridate package has nice extraction functions.

For some projects, I have found that piecing dates out from the start is helpful: create year, month, day (of month) and day (of week) variables to start with. This can simplify summaries, tables and graphs, because the extraction code is separate from the summary/table/graph code, and because if you need to change it, you don't have to roll out those changes in multiple spots.

Redirect stderr and stdout in Bash

The following functions can be used to automate the process of toggling outputs beetwen stdout/stderr and a logfile.

#!/bin/bash

    #set -x

    # global vars
    OUTPUTS_REDIRECTED="false"
    LOGFILE=/dev/stdout

    # "private" function used by redirect_outputs_to_logfile()
    function save_standard_outputs {
        if [ "$OUTPUTS_REDIRECTED" == "true" ]; then
            echo "[ERROR]: ${FUNCNAME[0]}: Cannot save standard outputs because they have been redirected before"
            exit 1;
        fi
        exec 3>&1
        exec 4>&2

        trap restore_standard_outputs EXIT
    }

    # Params: $1 => logfile to write to
    function redirect_outputs_to_logfile {
        if [ "$OUTPUTS_REDIRECTED" == "true" ]; then
            echo "[ERROR]: ${FUNCNAME[0]}: Cannot redirect standard outputs because they have been redirected before"
            exit 1;
        fi
        LOGFILE=$1
        if [ -z "$LOGFILE" ]; then
            echo "[ERROR]: ${FUNCNAME[0]}: logfile empty [$LOGFILE]"

        fi
        if [ ! -f $LOGFILE ]; then
            touch $LOGFILE
        fi
        if [ ! -f $LOGFILE ]; then
            echo "[ERROR]: ${FUNCNAME[0]}: creating logfile [$LOGFILE]"
            exit 1
        fi

        save_standard_outputs

        exec 1>>${LOGFILE%.log}.log
        exec 2>&1
        OUTPUTS_REDIRECTED="true"
    }

    # "private" function used by save_standard_outputs() 
    function restore_standard_outputs {
        if [ "$OUTPUTS_REDIRECTED" == "false" ]; then
            echo "[ERROR]: ${FUNCNAME[0]}: Cannot restore standard outputs because they have NOT been redirected"
            exit 1;
        fi
        exec 1>&-   #closes FD 1 (logfile)
        exec 2>&-   #closes FD 2 (logfile)
        exec 2>&4   #restore stderr
        exec 1>&3   #restore stdout

        OUTPUTS_REDIRECTED="false"
    }

Example of usage inside script:

echo "this goes to stdout"
redirect_outputs_to_logfile /tmp/one.log
echo "this goes to logfile"
restore_standard_outputs 
echo "this goes to stdout"

BigDecimal equals() versus compareTo()

The answer is in the JavaDoc of the equals() method:

Unlike compareTo, this method considers two BigDecimal objects equal only if they are equal in value and scale (thus 2.0 is not equal to 2.00 when compared by this method).

In other words: equals() checks if the BigDecimal objects are exactly the same in every aspect. compareTo() "only" compares their numeric value.

As to why equals() behaves this way, this has been answered in this SO question.

How to use systemctl in Ubuntu 14.04

I ran across this while on a hunt for answers myself after attempting to follow a guide using pm2. The goal is to automatically start a node.js application on a server. Some guides call out using pm2 startup systemd, which is the path that leads to the question of using systemctl on Ubuntu 14.04. Instead, use pm2 startup ubuntu.

Source: https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-14-04

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

Route::group(['middleware' => 'web'], function () {
Route::auth();

Route::get('/', ['as' => 'home', 'uses' => 'BaseController@index']);

Route::group(['namespace' => 'User', 'prefix' => 'user'], function(){
    Route::get('{nickname}/settings', ['as' => 'user.settings', 'uses' => 'SettingsController@index']);
    Route::get('{nickname}/profile', ['as' => 'user.profile', 'uses' => 'ProfileController@index']);
});
});

500 internal server error, how to debug

Try writing all the errors to a file.

error_reporting(-1); // reports all errors
ini_set("display_errors", "1"); // shows all errors
ini_set("log_errors", 1);
ini_set("error_log", "/tmp/php-error.log");

Something like that.

:: (double colon) operator in Java 8

In java-8 Streams Reducer in simple works is a function which takes two values as input and returns result after some calculation. this result is fed in next iteration.

in case of Math:max function, method keeps returning max of two values passed and in the end you have largest number in hand.

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

Edit the .csproj or vbproj file. Find and replace these entries

<UseIIS>true</UseIIS> by <UseIIS>false</UseIIS>
<UseIISExpress>true</UseIISExpress> by <UseIISExpress>false</UseIISExpress>

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

How do I check if string contains substring?

You can use this Polyfill in ie and chrome

if (!('contains' in String.prototype)) {
    String.prototype.contains = function (str, startIndex) {
        "use strict";
        return -1 !== String.prototype.indexOf.call(this, str, startIndex);
    };
}

splitting a string into an array in C++ without using vector

#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

int main() {

    string s1="split on     whitespace";
    istringstream iss(s1);
    vector<string> result;
    for(string s;iss>>s;)
        result.push_back(s);
    int n=result.size();
    for(int i=0;i<n;i++)
        cout<<result[i]<<endl;
    return 0;
}

Output:-

split
on
whitespace

ASP.NET MVC DropDownListFor with model of type List<string>

To make a dropdown list you need two properties:

  1. a property to which you will bind to (usually a scalar property of type integer or string)
  2. a list of items containing two properties (one for the values and one for the text)

In your case you only have a list of string which cannot be exploited to create a usable drop down list.

While for number 2. you could have the value and the text be the same you need a property to bind to. You could use a weakly typed version of the helper:

@model List<string>
@Html.DropDownList(
    "Foo", 
    new SelectList(
        Model.Select(x => new { Value = x, Text = x }),
        "Value",
        "Text"
    )
)

where Foo will be the name of the ddl and used by the default model binder. So the generated markup might look something like this:

<select name="Foo" id="Foo">
    <option value="item 1">item 1</option>
    <option value="item 2">item 2</option>
    <option value="item 3">item 3</option>
    ...
</select>

This being said a far better view model for a drop down list is the following:

public class MyListModel
{
    public string SelectedItemId { get; set; }
    public IEnumerable<SelectListItem> Items { get; set; }
}

and then:

@model MyListModel
@Html.DropDownListFor(
    x => x.SelectedItemId,
    new SelectList(Model.Items, "Value", "Text")
)

and if you wanted to preselect some option in this list all you need to do is to set the SelectedItemId property of this view model to the corresponding Value of some element in the Items collection.

How to see what privileges are granted to schema of another user

Login into the database. then run the below query

select * from dba_role_privs where grantee = 'SCHEMA_NAME';

All the role granted to the schema will be listed.

Thanks Szilagyi Donat for the answer. This one is taken from same and just where clause added.

Should I add the Visual Studio .suo and .user files to source control?

Others have explained that no, you don't want this in version control. You should configure your version control system to ignore the file (e.g. via a .gitignore file).

To really understand why, it helps to see what's actually in this file. I wrote a command line tool that lets you see the .suo file's contents.

Install it on your machine via:

dotnet tool install -g suo

It has two sub-commands, keys and view.

suo keys <path-to-suo-file>

This will dump out the key for each value in the file. For example (abridged):

nuget
ProjInfoEx
BookmarkState
DebuggerWatches
HiddenSlnFolders
ObjMgrContentsV8
UnloadedProjects
ClassViewContents
OutliningStateDir
ProjExplorerState
TaskListShortcuts
XmlPackageOptions
BackgroundLoadData
DebuggerExceptions
DebuggerFindSource
DebuggerFindSymbol
ILSpy-234190A6EE66
MRU Solution Files
UnloadedProjectsEx
ApplicationInsights
DebuggerBreakpoints
OutliningStateV1674
...

As you can see, lots of IDE features use this file to store their state.

Use the view command to see a given key's value. For example:

$ suo view nuget --format=utf8 .suo
nuget

?{"WindowSettings":{"project:MyProject":{"SourceRepository":"nuget.org","ShowPreviewWindow":false,"ShowDeprecatedFrameworkWindow":true,"RemoveDependencies":false,"ForceRemove":false,"IncludePrerelease":false,"SelectedFilter":"UpdatesAvailable","DependencyBehavior":"Lowest","FileConflictAction":"PromptUser","OptionsExpanded":false,"SortPropertyName":"ProjectName","SortDirection":"Ascending"}}}

More information on the tool here: https://github.com/drewnoakes/suo

How to call javascript from a href?

If you only want to process a function and not process the href it self, add the return false statement at the end of your function:

 <a href="#" onclick="javascript: function() {... ; return false} return false">click</>

Autoreload of modules in IPython

You can use:

  import ipy_autoreload
  %autoreload 2 
  %aimport your_mod

Getter and Setter?

Update: Don't use this answer since this is very dumb code that I found while I learn. Just use plain getter and setter, it's much better.


I usually using that variable name as function name, and add optional parameter to that function so when that optional parameter is filled by caller, then set it to the property and return $this object (chaining) and then when that optional parameter not specified by caller, i just return the property to the caller.

My example:

class Model
{
     private $propOne;
     private $propTwo;

     public function propOne($propVal = '')
     {
          if ($propVal === '') {
              return $this->propOne;
          } else {
              $this->propOne = $propVal;
              return $this;
          }
     }

     public function propTwo($propVal = '')
     {
          if ($propVal === '') {
              return $this->propTwo;
          } else {
              $this->propTwo = $propVal;
              return $this;
          }
     }
}

SQL Server stored procedure Nullable parameter

You can/should set your parameter to value to DBNull.Value;

if (variable == "")
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = DBNull.Value;
}
else
{
     cmd.Parameters.Add("@Param", SqlDbType.VarChar, 500).Value = variable;
}

Or you can leave your server side set to null and not pass the param at all.

Installing Android Studio, does not point to a valid JVM installation error

Using c:/Program Files/Java/jre1.8.0_73/ instead of C:/Program Files/Java/jdk1.8.0_73 as JAVA_HOME variable solved the problem for me. Android studio now launches without problems.

const vs constexpr on variables

No difference here, but it matters when you have a type that has a constructor.

struct S {
    constexpr S(int);
};

const S s0(0);
constexpr S s1(1);

s0 is a constant, but it does not promise to be initialized at compile-time. s1 is marked constexpr, so it is a constant and, because S's constructor is also marked constexpr, it will be initialized at compile-time.

Mostly this matters when initialization at runtime would be time-consuming and you want to push that work off onto the compiler, where it's also time-consuming, but doesn't slow down execution time of the compiled program

"The given path's format is not supported."

Rather than using str_uploadpath + fileName, try using System.IO.Path.Combine instead:

Path.Combine(str_uploadpath, fileName);

which returns a string.

Prevent linebreak after </div>

try this (in CSS) for preventing line breaks in div texts:

white-space: nowrap;

Read text file into string array (and write)

Note: ioutil is deprecated as of Go 1.16.

If the file isn't too large, this can be done with the ioutil.ReadFile and strings.Split functions like so:

content, err := ioutil.ReadFile(filename)
if err != nil {
    //Do something
}
lines := strings.Split(string(content), "\n")

You can read the documentation on ioutil and strings packages.

How do I calculate power-of in C#?

You are looking for the static method Math.Pow().

Find and replace - Add carriage return OR Newline

If you want to avoid the hassle of escaping the special characters in your search and replacement string when using regular expressions, do the following steps:

  1. Search for your original string, and replace it with "UniqueString42", with regular expressions off.
  2. Search for "UniqueString42" and replace it with "UniqueString42\nUniqueString1337", with regular expressions on
  3. Search for "UniqueString42" and replace it with the first line of your replacement (often your original string), with regular expressions off.
  4. Search for "UniqueString42" and replace it with the second line of your replacement, with regular expressions off.

Note that even if you want to manually pich matches for the first search and replace, you can safely use "replace all" for the three last steps.

Example

For example, if you want to replace this:

public IFoo SomeField { get { return this.SomeField; } }

with that:

public IFoo Foo { get { return this.MyFoo; } }
public IBar Bar { get { return this.MyBar; } }

You would do the following substitutions:

  1. public IFoo SomeField { get { return this.SomeField; } } ? XOXOXOXO (regex off).
  2. XOXOXOXO ? XOXOXOXO\nHUHUHUHU (regex on).
  3. XOXOXOXO ? public IFoo Foo { get { return this.MyFoo; } } (regex off).
  4. HUHUHUHU ? public IFoo Bar { get { return this.MyBar; } } (regex off).

Zsh: Conda/Pip installs command not found

Simply copy your Anaconda bin directory and paste it at the bottom of ~/.zshrc.

For me the path is /home/theorangeguy/miniconda3/bin, so I ran:

echo ". /home/theorangeguy/miniconda3/bin" >> ~/.zshrc

This edited the ~/.zshrc. Now do:

source ~/.zshrc

It worked like a charm.

Create ArrayList from array

Use below script

Object[] myNum = {10, 20, 30, 40};
List<Object> newArr = new ArrayList<>(Arrays.asList(myNum));

How to add Options Menu to Fragment in Android

Call the super method:

Java:

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        // TODO Add your menu entries here
        super.onCreateOptionsMenu(menu, inflater);
    }

Kotlin:

    override fun void onCreate(savedInstanceState: Bundle) {
        super.onCreate(savedInstanceState)
        setHasOptionsMenu(true)
    }

    override fun onCreateOptionsMenu(menu: Menu, inflater: MenuInflater) {
        // TODO Add your menu entries here
        super.onCreateOptionsMenu(menu, inflater)
    }

Put log statements in the code to see if the method is not being called or if the menu is not being amended by your code.

Also ensure you are calling setHasOptionsMenu(boolean) in onCreate(Bundle) to notify the fragment that it should participate in options menu handling.

How to add values in a variable in Unix shell scripting?

I don't have a unix system under my hands, but try this:

count7=$((${count7} + ${count1}))

Or maybe you have a shell that doesn't support this expression. I think bash does support it, but sh doesn't.

EDIT: There is another syntax, try:

count7=`expr $count7 + $count1`

How do you get a list of the names of all files present in a directory in Node.js?

Out of the box

In case you want an object with the directory structure out-of-the-box I highly reccomend you to check directory-tree.

Lets say you have this structure:

photos
¦   june
¦   +-- windsurf.jpg
+-- january
    +-- ski.png
    +-- snowboard.jpg
const dirTree = require("directory-tree");
const tree = dirTree("/path/to/photos");

Will return:

{
  path: "photos",
  name: "photos",
  size: 600,
  type: "directory",
  children: [
    {
      path: "photos/june",
      name: "june",
      size: 400,
      type: "directory",
      children: [
        {
          path: "photos/june/windsurf.jpg",
          name: "windsurf.jpg",
          size: 400,
          type: "file",
          extension: ".jpg"
        }
      ]
    },
    {
      path: "photos/january",
      name: "january",
      size: 200,
      type: "directory",
      children: [
        {
          path: "photos/january/ski.png",
          name: "ski.png",
          size: 100,
          type: "file",
          extension: ".png"
        },
        {
          path: "photos/january/snowboard.jpg",
          name: "snowboard.jpg",
          size: 100,
          type: "file",
          extension: ".jpg"
        }
      ]
    }
  ]
}

Custom Object

Otherwise if you want to create an directory tree object with your custom settings have a look at the following snippet. A live example is visible on this codesandbox.

// my-script.js
const fs = require("fs");
const path = require("path");

const isDirectory = filePath => fs.statSync(filePath).isDirectory();
const isFile = filePath => fs.statSync(filePath).isFile();

const getDirectoryDetails = filePath => {
  const dirs = fs.readdirSync(filePath);
  return {
    dirs: dirs.filter(name => isDirectory(path.join(filePath, name))),
    files: dirs.filter(name => isFile(path.join(filePath, name)))
  };
};

const getFilesRecursively = (parentPath, currentFolder) => {
  const currentFolderPath = path.join(parentPath, currentFolder);
  let currentDirectoryDetails = getDirectoryDetails(currentFolderPath);

  const final = {
    current_dir: currentFolder,
    dirs: currentDirectoryDetails.dirs.map(dir =>
      getFilesRecursively(currentFolderPath, dir)
    ),
    files: currentDirectoryDetails.files
  };

  return final;
};

const getAllFiles = relativePath => {
  const fullPath = path.join(__dirname, relativePath);
  const parentDirectoryPath = path.dirname(fullPath);
  const leafDirectory = path.basename(fullPath);

  const allFiles = getFilesRecursively(parentDirectoryPath, leafDirectory);
  return allFiles;
};

module.exports = { getAllFiles };

Then you can simply do:

// another-file.js 

const { getAllFiles } = require("path/to/my-script");

const allFiles = getAllFiles("/path/to/my-directory");

How to split the screen with two equal LinearLayouts?

In order to split the ui into two equal parts you can use weightSum of 2 in the parent LinearLayout and assign layout_weight of 1 to each as shown below

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:weightSum="2">

        <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

        </LinearLayout>

       <LinearLayout
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical">

       </LinearLayout>


</LinearLayout>

How can I get zoom functionality for images?

Something like below will do it.

@Override public boolean onTouch(View v,MotionEvent e)
{

    tap=tap2=drag=pinch=none;
    int mask=e.getActionMasked();
    posx=e.getX();posy=e.getY();

    float midx= img.getWidth()/2f;
    float midy=img.getHeight()/2f;
    int fingers=e.getPointerCount();

    switch(mask)
    {
        case MotionEvent.ACTION_POINTER_UP:
            tap2=1;break;

        case MotionEvent.ACTION_UP:
            tap=1;break;

        case MotionEvent.ACTION_MOVE:
            drag=1;
    }
    if(fingers==2){nowsp=Math.abs(e.getX(0)-e.getX(1));}
    if((fingers==2)&&(drag==0)){ tap2=1;tap=0;drag=0;}
    if((fingers==2)&&(drag==1)){ tap2=0;tap=0;drag=0;pinch=1;}

    if(pinch==1)

    {
        if(nowsp>oldsp)scale+=0.1;
        if(nowsp<oldsp)scale-=0.1;
        tap2=tap=drag=0;    
    }
    if(tap2==1)
        {
            scale-=0.1;
            tap=0;drag=0;
        }
    if(tap==1)
        {
            tap2=0;drag=0;
            scale+=0.1;
        }
    if(drag==1)
        {
            movx=posx-oldx;
            movy=posy-oldy;
            x+=movx;
            y+=movy;
            tap=0;tap2=0;
        }
    m.setTranslate(x,y);
    m.postScale(scale,scale,midx,midy);
    img.setImageMatrix(m);img.invalidate();
    tap=tap2=drag=none;
    oldx=posx;oldy=posy;
    oldsp=nowsp;
    return true;
}


public void onCreate(Bundle b)
{
        super.onCreate(b);

    img=new ImageView(this);
    img.setScaleType(ImageView.ScaleType.MATRIX);
    img.setOnTouchListener(this);

    path=Environment.getExternalStorageDirectory().getPath();   
    path=path+"/DCIM"+"/behala.jpg";
    byte[] bytes;
    bytes=null;
    try{
        FileInputStream fis;
        fis=new FileInputStream(path);
        BufferedInputStream bis;
        bis=new BufferedInputStream(fis);
        bytes=new byte[bis.available()];
        bis.read(bytes);
        if(bis!=null)bis.close();
        if(fis!=null)fis.close();

     }
    catch(Exception e)
        {
        ret="Nothing";
        }
    Bitmap bmp=BitmapFactory.decodeByteArray(bytes,0,bytes.length);

    img.setImageBitmap(bmp);

    setContentView(img);
}

For viewing complete program see here: Program to zoom image in android

How to create a jQuery plugin with methods?

Here's the pattern I have used for creating plugins with additional methods. You would use it like:

$('selector').myplugin( { key: 'value' } );

or, to invoke a method directly,

$('selector').myplugin( 'mymethod1', 'argument' );

Example:

;(function($) {

    $.fn.extend({
        myplugin: function(options,arg) {
            if (options && typeof(options) == 'object') {
                options = $.extend( {}, $.myplugin.defaults, options );
            }

            // this creates a plugin for each element in
            // the selector or runs the function once per
            // selector.  To have it do so for just the
            // first element (once), return false after
            // creating the plugin to stop the each iteration 
            this.each(function() {
                new $.myplugin(this, options, arg );
            });
            return;
        }
    });

    $.myplugin = function( elem, options, arg ) {

        if (options && typeof(options) == 'string') {
           if (options == 'mymethod1') {
               myplugin_method1( arg );
           }
           else if (options == 'mymethod2') {
               myplugin_method2( arg );
           }
           return;
        }

        ...normal plugin actions...

        function myplugin_method1(arg)
        {
            ...do method1 with this and arg
        }

        function myplugin_method2(arg)
        {
            ...do method2 with this and arg
        }

    };

    $.myplugin.defaults = {
       ...
    };

})(jQuery);

Why do we have to override the equals() method in Java?

To answer your question, firstly I would strongly recommend looking at the Documentation.

Without overriding the equals() method, it will act like "==". When you use the "==" operator on objects, it simply checks to see if those pointers refer to the same object. Not if their members contain the same value.

We override to keep our code clean, and abstract the comparison logic from the If statement, into the object. This is considered good practice and takes advantage of Java's heavily Object Oriented Approach.

Issue with background color and Google Chrome

After trying all of the other solutions here without success, I skeptically tried the solution found in this article, and got it to work.

Essentially, it boils down to removing @charset "utf-8"; from your CSS.

This seems like a poor implementation in DreamWeaver - but it did fix the issue for me, regardless.

how to sort order of LEFT JOIN in SQL query?

This will get you the most expensive car for the user:

SELECT users.userName, MAX(cars.carPrice)
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName

However, this statement makes me think that you want all of the cars prices sorted, descending:

So question: How do I set the LEFT JOIN table to be ordered by carPrice, DESC ?

So you could try this:

SELECT users.userName, cars.carPrice
FROM users
LEFT JOIN cars ON cars.belongsToUser=users.id
WHERE users.id=4
GROUP BY users.userName
ORDER BY users.userName ASC, cars.carPrice DESC

Angularjs: input[text] ngChange fires while the value is changing

Isn't using $scope.$watch to reflect the changes of scope variable better?

Javascript Debugging line by line using Google Chrome

...How can I step through my javascript code line by line using Google Chromes developer tools without it going into javascript libraries?...


For the record: At this time (Feb/2015) both Google Chrome and Firefox have exactly what you (and I) need to avoid going inside libraries and scripts, and go beyond the code that we are interested, It's called Black Boxing:

enter image description here

When you blackbox a source file, the debugger will not jump into that file when stepping through code you're debugging.

More info:

Convert serial.read() into a useable string using Arduino?

From Help with Serial.Read() getting string:

char inData[20]; // Allocate some space for the string
char inChar=-1; // Where to store the character read
byte index = 0; // Index into array; where to store the character

void setup() {
    Serial.begin(9600);
    Serial.write("Power On");
}

char Comp(char* This) {
    while (Serial.available() > 0) // Don't read unless
                                       // there you know there is data
    {
       if(index < 19) // One less than the size of the array
       {
           inChar = Serial.read(); // Read a character
           inData[index] = inChar; // Store it
           index++; // Increment where to write next
           inData[index] = '\0'; // Null terminate the string
       }
    }

    if (strcmp(inData,This)  == 0) {
       for (int i=0;i<19;i++) {
            inData[i]=0;
       }
       index=0;
       return(0);
    }
    else {
       return(1);
    }
}

void loop()
{
    if (Comp("m1 on")==0) {
        Serial.write("Motor 1 -> Online\n");
    }
    if (Comp("m1 off")==0) {
       Serial.write("Motor 1 -> Offline\n");
    }
}

How do I get the time of day in javascript/Node.js?

This function will return you the date and time in the following format: YYYY:MM:DD:HH:MM:SS. It also works in Node.js.

function getDateTime() {

    var date = new Date();

    var hour = date.getHours();
    hour = (hour < 10 ? "0" : "") + hour;

    var min  = date.getMinutes();
    min = (min < 10 ? "0" : "") + min;

    var sec  = date.getSeconds();
    sec = (sec < 10 ? "0" : "") + sec;

    var year = date.getFullYear();

    var month = date.getMonth() + 1;
    month = (month < 10 ? "0" : "") + month;

    var day  = date.getDate();
    day = (day < 10 ? "0" : "") + day;

    return year + ":" + month + ":" + day + ":" + hour + ":" + min + ":" + sec;

}

Where is Java's Array indexOf?

Unlike in C# where you have the Array.IndexOf method, and JavaScript where you have the indexOf method, Java's API (the Array and Arrays classes in particular) have no such method.

This method indexOf (together with its complement lastIndexOf) is defined in the java.util.List interface. Note that indexOf and lastIndexOf are not overloaded and only take an Object as a parameter.

If your array is sorted, you are in luck because the Arrays class defines a series of overloads of the binarySearch method that will find the index of the element you are looking for with best possible performance (O(log n) instead of O(n), the latter being what you can expect from a sequential search done by indexOf). There are four considerations:

  1. The array must be sorted either in natural order or in the order of a Comparator that you provide as an argument, or at the very least all elements that are "less than" the key must come before that element in the array and all elements that are "greater than" the key must come after that element in the array;

  2. The test you normally do with indexOf to determine if a key is in the array (verify if the return value is not -1) does not hold with binarySearch. You need to verify that the return value is not less than zero since the value returned will indicate the key is not present but the index at which it would be expected if it did exist;

  3. If your array contains multiple elements that are equal to the key, what you get from binarySearch is undefined; this is different from indexOf that will return the first occurrence and lastIndexOf that will return the last occurrence.

  4. An array of booleans might appear to be sorted if it first contains all falses and then all trues, but this doesn't count. There is no override of the binarySearch method that accepts an array of booleans and you'll have to do something clever there if you want O(log n) performance when detecting where the first true appears in an array, for instance using an array of Booleans and the constants Boolean.FALSE and Boolean.TRUE.

If your array is not sorted and not primitive type, you can use List's indexOf and lastIndexOf methods by invoking the asList method of java.util.Arrays. This method will return an AbstractList interface wrapper around your array. It involves minimal overhead since it does not create a copy of the array. As mentioned, this method is not overloaded so this will only work on arrays of reference types.

If your array is not sorted and the type of the array is primitive, you are out of luck with the Java API. Write your own for loop, or your own static utility method, which will certainly have performance advantages over the asList approach that involves some overhead of an object instantiation. In case you're concerned that writing a brute force for loop that iterates over all of the elements of the array is not an elegant solution, accept that that is exactly what the Java API is doing when you call indexOf. You can make something like this:

public static int indexOfIntArray(int[] array, int key) {
    int returnvalue = -1;
    for (int i = 0; i < array.length; ++i) {
        if (key == array[i]) {
            returnvalue = i;
            break;
        }
    }
    return returnvalue;
}

If you want to avoid writing your own method here, consider using one from a development framework like Guava. There you can find an implementation of indexOf and lastIndexOf.

PostgreSQL: Resetting password of PostgreSQL on Ubuntu

Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf file (in the /etc/postgresql/9.1/main directory), it should contain this line as the first rule:

# Database administrative login by Unix domain socket  
local   all             postgres                                peer

(About the file location: 9.1 is the major postgres version and main the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters command to obtain this information for your version/system).

Anyway, if the pg_hba.conf file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload.

Then you should be able to log in with psql as the postgres superuser with this shell command:

sudo -u postgres psql

Once inside psql, issue the SQL command:

ALTER USER postgres PASSWORD 'newpassword';

In this command, postgres is the name of a superuser. If the user whose password is forgotten was ritesh, the command would be:

ALTER USER ritesh PASSWORD 'newpassword';

References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication

Keep in mind that you need to type postgres with a single S at the end

If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD:

\password username

It asks for the password with a double blind input, then hashes it according to the password_encryption setting and issue the ALTER USER command to the server with the hashed version of the password, instead of the clear text version.

What are good message queue options for nodejs?

Shameless plug: I'm working on Bokeh: a simple, scalable and blazing-fast task queue built on ZeroMQ. It supports pluggable data stores for persisting tasks, currently in-memory, Redis and Riak are supported. Check it out.

How to return a class object by reference in C++?

You're probably returning an object that's on the stack. That is, return_Object() probably looks like this:

Object& return_Object()
{
    Object object_to_return;
    // ... do stuff ...

    return object_to_return;
}

If this is what you're doing, you're out of luck - object_to_return has gone out of scope and been destructed at the end of return_Object, so myObject refers to a non-existent object. You either need to return by value, or return an Object declared in a wider scope or newed onto the heap.

String split on new line, tab and some number of spaces

>>> for line in s.splitlines():
...     line = line.strip()
...     if not line:continue
...     ary.append(line.split(":"))
...
>>> ary
[['Name', ' John Smith'], ['Home', ' Anytown USA'], ['Misc', ' Data with spaces'
]]
>>> dict(ary)
{'Home': ' Anytown USA', 'Misc': ' Data with spaces', 'Name': ' John Smith'}
>>>

How to print in C

try this:

printf("%d", addNumber(a,b))

Here's the documentation for printf.

Inserting records into a MySQL table using Java

no that cannot work(not with real data):

String sql = "INSERT INTO course " +
        "VALUES (course_code, course_desc, course_chair)";
    stmt.executeUpdate(sql);

change it to:

String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
        "VALUES (?, ?, ?)";

Create a PreparedStatment with that sql and insert the values with index:

PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate(); 

How to clear a textbox using javascript

just set empty string

    <input type="text" id="textId" value="A new value">
    document.getElementById('textId').value = '';

"Unknown class <MyClass> in Interface Builder file" error at runtime

This doesn't really have anything to do with Interface Builder, what's happening here is the symbols aren't being loaded from your static library by Xcode. To resolve this problem you need to add the -all_load -ObjC flags to the Other Linker Flags key the Project (and possibly the Target) Build Settings.

Since Objective-C only generates one symbol per class we must force the linker to load the members of the class too by using the -ObjC flag, and we must also force inclusion of all our objects from our static library by adding the -all_load linker flag. If you skip these flags sooner or later you will run into the error of unrecognized selector or get other exceptions such as the one you've observed here.

How do you Change a Package's Log Level using Log4j?

I encountered the exact same problem today, Ryan.

In my src (or your root) directory, my log4j.properties file now has the following addition

# https://issues.apache.org/jira/browse/AXIS2-4363
log4j.category.org.apache.axiom=WARN

Thanks for the heads up as to how to do this, Benjamin.

Specifying onClick event type with Typescript and React.Konva

As posted in my update above, a potential solution would be to use Declaration Merging as suggested by @Tyler-sebastion. I was able to define two additional interfaces and add the index property on the EventTarget in this way.

interface KonvaTextEventTarget extends EventTarget {
  index: number
}

interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
  target: KonvaTextEventTarget
}

I then can declare the event as KonvaMouseEvent in my onclick MouseEventHandler function.

onClick={(event: KonvaMouseEvent) => {
          makeMove(ownMark, event.target.index)
}}

I'm still not 100% if this is the best approach as it feels a bit Kludgy and overly verbose just to get past the tslint error.

possible EventEmitter memory leak detected

I was having this till today when I start grunt watch. Finally solved by

watch: {
  options: {
    maxListeners: 99,
    livereload: true
  },
}

The annoying message is gone.

Drawing a dot on HTML5 canvas

For performance reasons, don't draw a circle if you can avoid it. Just draw a rectangle with a width and height of one:

ctx.fillRect(10,10,1,1); // fill in the pixel at (10,10)

Replace last occurrence of character in string

You can use this code

_x000D_
_x000D_
var str="test_String_ABC";_x000D_
var strReplacedWith=" and ";_x000D_
var currentIndex = str.lastIndexOf("_");_x000D_
str = str.substring(0, currentIndex) + strReplacedWith + str.substring(currentIndex + 1, str.length);_x000D_
_x000D_
alert(str);
_x000D_
_x000D_
_x000D_

How to use OpenFileDialog to select a folder?

Here is another solution, that has all the source available in a single, simple ZIP file.

It presents the OpenFileDialog with additional windows flags that makes it work like the Windows 7+ Folder Selection dialog.

Per the website, it is public domain: "There’s no license as such as you are free to take and do with the code what you will."

Archive.org links:

C++ error 'Undefined reference to Class::Function()'

What are you using to compile this? If there's an undefined reference error, usually it's because the .o file (which gets created from the .cpp file) doesn't exist and your compiler/build system is not able to link it.

Also, in your card.cpp, the function should be Card::Card() instead of void Card. The Card:: is scoping; it means that your Card() function is a member of the Card class (which it obviously is, since it's the constructor for that class). Without this, void Card is just a free function. Similarly,

void Card(Card::Rank rank, Card::Suit suit)

should be

Card::Card(Card::Rank rank, Card::Suit suit)

Also, in deck.cpp, you are saying #include "Deck.h" even though you referred to it as deck.h. The includes are case sensitive.

node.js require() cache - possible to invalidate?

Yes, you can invalidate cache.

The cache is stored in an object called require.cache which you can access directly according to filenames (e.g. - /projects/app/home/index.js as opposed to ./home which you would use in a require('./home') statement).

delete require.cache['/projects/app/home/index.js'];

Our team has found the following module useful. To invalidate certain groups of modules.

https://www.npmjs.com/package/node-resource

List an Array of Strings in alphabetical order

Here is code that works:

import java.util.Arrays;
import java.util.Collections;

public class Test
{
    public static void main(String[] args)
    {
        orderedGuests1(new String[] { "c", "a", "b" });
        orderedGuests2(new String[] { "c", "a", "b" });
    }

    public static void orderedGuests1(String[] hotel)
    {
        Arrays.sort(hotel);
        System.out.println(Arrays.toString(hotel));
    }

    public static void orderedGuests2(String[] hotel)
    {
        Collections.sort(Arrays.asList(hotel));
        System.out.println(Arrays.toString(hotel));
    }

}

SQL: How to get the id of values I just INSERTed?

In TransactSQL, you can use OUTPUT clause to achieve that.

INSERT INTO my_table(col1,col2,col3) OUTPUT INSERTED.id VALUES('col1Value','col2Value','col3Value')

FRI: http://msdn.microsoft.com/en-us/library/ms177564.aspx

How to remove text before | character in notepad++

To replace anything that starts with "text" until the last character:

text.+(.*)$

Example

text             hsjh sdjh sd          jhsjhsdjhsdj hsd
                                                      ^
                                                      last character


To replace anything that starts with "text" until "123"

text.+(\ 123)

Example

text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e
^                                   ^
From here                     To here

How do I install the ext-curl extension with PHP 7?

I got an error that the CURL extension was missing whilst installing WebMail Lite 8 on WAMP (so on Windows).

After reading that libeay32.dll was required which was only present in some of the PHP installation folders (such as 7.1.26), I switched the PHP version in use from 7.2.14 to 7.1.26 in the WAMP PHP version menu, and the error went away.

jquery disable form submit on enter

How about this:

$(":submit").closest("form").submit(function(){
    $(':submit').attr('disabled', 'disabled');
});

This should disable all forms with submit buttons in your app.

How do I grep for all non-ASCII characters?

Here is another variant I found that produced completely different results from the grep search for [\x80-\xFF] in the accepted answer. Perhaps it will be useful to someone to find additional non-ascii characters:

grep --color='auto' -P -n "[^[:ascii:]]" myfile.txt

Note: my computer's grep (a Mac) did not have -P option, so I did brew install grep and started the call above with ggrep instead of grep.

Code snippet or shortcut to create a constructor in Visual Studio

If you want to see the list of all available snippets:

Press Ctrl + K and then X.

How can I connect to a Tor hidden service using cURL in PHP?

I use Privoxy and cURL to scrape Tor pages:

<?php
    $ch = curl_init('http://jhiwjjlqpyawmpjx.onion'); // Tormail URL
    curl_setopt($ch, CURLOPT_HEADER, 1);
    curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, 1);
    curl_setopt($ch, CURLOPT_PROXY, "localhost:8118"); // Default privoxy port
    curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_HTTP);
    curl_exec($ch);
    curl_close($ch);
?>

After installing Privoxy you need to add this line to the configuration file (/etc/privoxy/config). Note the space and '.' a the end of line.

forward-socks4a / localhost:9050 .

Then restart Privoxy.

/etc/init.d/privoxy restart

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

Check if you are returning a @ResponseBody or a @ResponseStatus

I had a similar problem. My Controller looked like that:

@RequestMapping(value="/user", method = RequestMethod.POST)
public String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

When calling with a POST request I always got the following error:

HTTP Status 405 - Request method 'POST' not supported

After a while I figured out that the method was actually called, but because there is no @ResponseBody and no @ResponseStatus Spring MVC raises the error.

To fix this simply add a @ResponseBody

@RequestMapping(value="/user", method = RequestMethod.POST)
public @ResponseBody String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

or a @ResponseStatus to your method.

@RequestMapping(value="/user", method = RequestMethod.POST)
@ResponseStatus(value=HttpStatus.OK)
public String updateUser(@RequestBody User user){
    return userService.updateUser(user).getId();
}

React navigation goBack() and update parent state

I was facing a similar issue, so here is how I solved it by going more into details.

Option one is to navigate back to parent with parameters, just define a callback function in it like this in parent component:

updateData = data => {
  console.log(data);
  alert("come back status: " + data);
  // some other stuff
};

and navigate to the child:

onPress = () => {
  this.props.navigation.navigate("ParentScreen", {
    name: "from parent",
    updateData: this.updateData
  });
};

Now in the child it can be called:

 this.props.navigation.state.params.updateData(status);
 this.props.navigation.goBack();

Option two. In order to get data from any component, as the other answer explained, AsyncStorage can be used either synchronously or not.

Once data is saved it can be used anywhere.

// to get
AsyncStorage.getItem("@item")
  .then(item => {
    item = JSON.parse(item);
    this.setState({ mystate: item });
  })
  .done();
// to set
AsyncStorage.setItem("@item", JSON.stringify(someData));

or either use an async function to make it self-update when it gets new value doing like so.

this.state = { item: this.dataUpdate() };
async function dataUpdate() {
  try {
    let item = await AsyncStorage.getItem("@item");
    return item;
  } catch (e) {
    console.log(e.message);
  }
}

See the AsyncStorage docs for more details.

How to check python anaconda version installed on Windows 10 PC?

If you want to check the python version in a particular cond environment you can also use conda list python

Select rows which are not present in other table

There are basically 4 techniques for this task, all of them standard SQL.

NOT EXISTS

Often fastest in Postgres.

SELECT ip 
FROM   login_log l 
WHERE  NOT EXISTS (
   SELECT  -- SELECT list mostly irrelevant; can just be empty in Postgres
   FROM   ip_location
   WHERE  ip = l.ip
   );

Also consider:

LEFT JOIN / IS NULL

Sometimes this is fastest. Often shortest. Often results in the same query plan as NOT EXISTS.

SELECT l.ip 
FROM   login_log l 
LEFT   JOIN ip_location i USING (ip)  -- short for: ON i.ip = l.ip
WHERE  i.ip IS NULL;

EXCEPT

Short. Not as easily integrated in more complex queries.

SELECT ip 
FROM   login_log

EXCEPT ALL  -- "ALL" keeps duplicates and makes it faster
SELECT ip
FROM   ip_location;

Note that (per documentation):

duplicates are eliminated unless EXCEPT ALL is used.

Typically, you'll want the ALL keyword. If you don't care, still use it because it makes the query faster.

NOT IN

Only good without NULL values or if you know to handle NULL properly. I would not use it for this purpose. Also, performance can deteriorate with bigger tables.

SELECT ip 
FROM   login_log
WHERE  ip NOT IN (
   SELECT DISTINCT ip  -- DISTINCT is optional
   FROM   ip_location
   );

NOT IN carries a "trap" for NULL values on either side:

Similar question on dba.SE targeted at MySQL:

Is <img> element block level or inline level?

IMG elements are inline, meaning that unless they are floated they will flow horizontally with text and other inline elements.

They are "block" elements in that they have a width and a height. But they behave more like "inline-block" in that respect.

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

What does "request for member '*******' in something not a structure or union" mean?

It also happens if you're trying to access an instance when you have a pointer, and vice versa:

struct foo
{
  int x, y, z;
};

struct foo a, *b = &a;

b.x = 12;  /* This will generate the error, should be b->x or (*b).x */

As pointed out in a comment, this can be made excruciating if someone goes and typedefs a pointer, i.e. includes the * in a typedef, like so:

typedef struct foo* Foo;

Because then you get code that looks like it's dealing with instances, when in fact it's dealing with pointers:

Foo a_foo = get_a_brand_new_foo();
a_foo->field = FANTASTIC_VALUE;

Note how the above looks as if it should be written a_foo.field, but that would fail since Foo is a pointer to struct. I strongly recommend against typedef:ed pointers in C. Pointers are important, don't hide your asterisks. Let them shine.

Mysql Compare two datetime fields

Your query apparently returned all correct dates, even considering the time.

If you're still not happy with the results, give DATEDIFF a shot and look for negaive/positive results between the two dates.

Make sure your mydate column is a datetime type.

What is the difference between json.dumps and json.load?

json loads -> returns an object from a string representing a json object.

json dumps -> returns a string representing a json object from an object.

load and dump -> read/write from/to file instead of string

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

For LINQ -> SQL:

SingleOrDefault

  • will generate query like "select * from users where userid = 1"
  • Select matching record, Throws exception if more than one records found
  • Use if you are fetching data based on primary/unique key column

FirstOrDefault

  • will generate query like "select top 1 * from users where userid = 1"
  • Select first matching rows
  • Use if you are fetching data based on non primary/unique key column

Convert string into integer in bash script - "Leading Zero" number error

How about sed?

hour=`echo $hour|sed -e "s/^0*//g"`

Javascript - Replace html using innerHTML

You should chain the replace() together instead of assigning the result and replacing again.

var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML
                        .replace(/aaaaaa./g,'<a href=\"http://www.google.com/')
                        .replace(/.bbbbbb/g,'/world\">Helloworld</a>');

See DEMO.

How does Google reCAPTCHA v2 work behind the scenes?

This is speculation, but based on Google's reference to the "risk analysis engine" they use (http://googleonlinesecurity.blogspot.com/2014/12/are-you-robot-introducing-no-captcha.html)

I would assume it looks at how you behaved prior to clicking, how your cursor moved on its way to the check (organic path/acceleration), which part of the checkbox was clicked (random places, or dead on center every time), browser fingerprint, Google cookies & contents, click location history tied to your fingerprint or account if it detects one etc.

It's fairly difficult to fake "organic" behavior in such a way that it would fool a continuously learning pattern detection engine. In the cases where it's not sure, it still prompts you to match an actual CAPTCHA string.

Using OR operator in a jquery if statement

The code you wrote will always return true because state cannot be both 10 and 15 for the statement to be false. if ((state != 10) && (state != 15).... AND is what you need not OR.

Use $.inArray instead. This returns the index of the element in the array.

JSFIDDLE DEMO

var statesArray = [10, 15, 19]; // list out all

var index = $.inArray(state, statesArray);

if(index == -1) {
    console.log("Not there in array");
    return true;

} else {
    console.log("Found it");
    return false;
}

PHP: if !empty & empty

if(!empty($youtube) && empty($link)) {

}
else if(empty($youtube) && !empty($link)) {

}
else if(empty($youtube) && empty($link)) {
}

CSS scale height to match width - possibly with a formfactor

Let me describe the JS solution as a separate answer:

function handleResize()
{
  var mapElement = document.getElementById("map");
  mapElement.style.height = (mapElement.offsetWidth * 1.72) + "px";
}

<div id="map" onresize="handleResize()">...</div>

(or register the event listener dynamically).

mapElement.style.width * 1.72 will not work, since it requires that the width be set explicitly on the element, either using the width DOM attribute or in the inline style's width CSS property.

How to start automatic download of a file in Internet Explorer?

For those trying to trigger the download using a dynamic link it's tricky to get it working consistently across browsers.

I had trouble in IE10+ downloading a PDF and used @dandavis' download function (https://github.com/rndme/download).

IE10+ needs msSaveBlob.

Currency Formatting in JavaScript

You could use toPrecision() and toFixed() methods of Number type. Check this link How can I format numbers as money in JavaScript?

In Python, how do I create a string of n characters in one line of code?

if you just want any letters:

 'a'*10  # gives 'aaaaaaaaaa'

if you want consecutive letters (up to 26):

 ''.join(['%c' % x for x in range(97, 97+10)])  # gives 'abcdefghij'

Instagram API to fetch pictures with specific hashtags

Take a look here in order to get started: http://instagram.com/developer/

and then in order to retrieve pictures by tag, look here: http://instagram.com/developer/endpoints/tags/

Getting tags from Instagram doesn't require OAuth, so you can make the calls via these URLs:

GET IMAGES https://api.instagram.com/v1/tags/{tag-name}/media/recent?access_token={TOKEN}

SEARCH https://api.instagram.com/v1/tags/search?q={tag-query}&access_token={TOKEN}

TAG INFO https://api.instagram.com/v1/tags/{tag-name}?access_token={TOKEN}

error C2220: warning treated as error - no 'object' file generated

Go to project properties -> configurations properties -> C/C++ -> treats warning as error -> No (/WX-).

What is the difference between an expression and a statement in Python?

An expression is something that can be reduced to a value, for example "1+3" is an expression, but "foo = 1+3" is not.

It's easy to check:

print(foo = 1+3)

If it doesn't work, it's a statement, if it does, it's an expression.

Another statement could be:

class Foo(Bar): pass

as it cannot be reduced to a value.

How to check if an item is selected from an HTML drop down list?

<label class="paylabel" for="cardtype">Card Type:</label>
<select id="cardtype" name="cards">
<option value="selectcard">--- Please select ---</option>
<option value="mastercard" selected="selected">Mastercard</option>
<option value="maestro">Maestro</option>
<option value="solo">Solo (UK only)</option>
<option value="visaelectron">Visa Electron</option>
<option value="visadebit">Visa Debit</option>
</select><br />

<script>
    var card = document.getElementById("cardtype");
    if (card.options[card.selectedIndex].value == 'selectcard') {
          alert("Please select a card type");
          return false;
    }
</script>

Ruby: Easiest Way to Filter Hash Keys?

As for bonus question:

  1. If you have output from #select method like this (list of 2-element arrays):

    [[:choice1, "Oh look, another one"], [:choice2, "Even more strings"], [:choice3, "But wait"]]
    

    then simply take this result and execute:

    filtered_params.join("\t")
    # or if you want only values instead of pairs key-value
    filtered_params.map(&:last).join("\t")
    
  2. If you have output from #delete_if method like this (hash):

    {:choice1=>"Oh look, another one", :choice2=>"Even more strings", :choice3=>"But wait"}
    

    then:

    filtered_params.to_a.join("\t")
    # or
    filtered_params.values.join("\t")
    

Find out the history of SQL queries

    select v.SQL_TEXT,
           v.PARSING_SCHEMA_NAME,
           v.FIRST_LOAD_TIME,
           v.DISK_READS,
           v.ROWS_PROCESSED,
           v.ELAPSED_TIME,
           v.service
      from v$sql v
where to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss')>ADD_MONTHS(trunc(sysdate,'MM'),-2)

where clause is optional. You can sort the results according to FIRST_LOAD_TIME and find the records up to 2 months ago.

How to downgrade the installed version of 'pip' on windows?

well the only thing that will work is

python -m pip install pip==

you can and should run it under IDE terminal (mine was pycharm)

How to set the authorization header using curl

This worked for me:

 curl -H "Authorization: Token xxxxxxxxxxxxxx" https://www.example.com/

What is the difference between null and System.DBNull.Value?

DBNull.Value is annoying to have to deal with.

I use static methods that check if it's DBNull and then return the value.

SqlDataReader r = ...;
String firstName = getString(r[COL_Firstname]);

private static String getString(Object o) {
   if (o == DBNull.Value) return null;
   return (String) o;
}

Also, when inserting values into a DataRow, you can't use "null", you have to use DBNull.Value.

Have two representations of "null" is a bad design for no apparent benefit.

How to convert binary string value to decimal

int num = Integer.parseInt("binaryString",2);

Wpf control size to content?

If you are using the grid or alike component: In XAML, make sure that the elements in the grid have Grid.Row and Grid.Column defined, and ensure tha they don't have margins. If you used designer mode, or Expression Blend, it could have assigned margins relative to the whole grid instead of to particular cells. As for cell sizing, I add an extra cell that fills up the rest of the space:

    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>

How to POST JSON request using Apache HttpClient?

Apache HttpClient doesn't know anything about JSON, so you'll need to construct your JSON separately. To do so, I recommend checking out the simple JSON-java library from json.org. (If "JSON-java" doesn't suit you, json.org has a big list of libraries available in different languages.)

Once you've generated your JSON, you can use something like the code below to POST it

StringRequestEntity requestEntity = new StringRequestEntity(
    JSON_STRING,
    "application/json",
    "UTF-8");

PostMethod postMethod = new PostMethod("http://example.com/action");
postMethod.setRequestEntity(requestEntity);

int statusCode = httpClient.executeMethod(postMethod);

Edit

Note - The above answer, as asked for in the question, applies to Apache HttpClient 3.1. However, to help anyone looking for an implementation against the latest Apache client:

StringEntity requestEntity = new StringEntity(
    JSON_STRING,
    ContentType.APPLICATION_JSON);

HttpPost postMethod = new HttpPost("http://example.com/action");
postMethod.setEntity(requestEntity);

HttpResponse rawResponse = httpclient.execute(postMethod);

JavaScript DOM: Find Element Index In Container

For just elements this can be used to find the index of an element amongst it's sibling elements:

function getElIndex(el) {
    for (var i = 0; el = el.previousElementSibling; i++);
    return i;
}

Note that previousElementSibling isn't supported in IE<9.

Python read-only property

Here is a way to avoid the assumption that

all users are consenting adults, and thus are responsible for using things correctly themselves.

please see my update below

Using @property, is very verbose e.g.:

   class AClassWithManyAttributes:
        '''refactored to properties'''
        def __init__(a, b, c, d, e ...)
             self._a = a
             self._b = b
             self._c = c
             self.d = d
             self.e = e

        @property
        def a(self):
            return self._a
        @property
        def b(self):
            return self._b
        @property
        def c(self):
            return self._c
        # you get this ... it's long

Using

No underscore: it's a public variable.
One underscore: it's a protected variable.
Two underscores: it's a private variable.

Except the last one, it's a convention. You can still, if you really try hard, access variables with double underscore.

So what do we do? Do we give up on having read only properties in Python?

Behold! read_only_properties decorator to the rescue!

@read_only_properties('readonly', 'forbidden')
class MyClass(object):
    def __init__(self, a, b, c):
        self.readonly = a
        self.forbidden = b
        self.ok = c

m = MyClass(1, 2, 3)
m.ok = 4
# we can re-assign a value to m.ok
# read only access to m.readonly is OK 
print(m.ok, m.readonly) 
print("This worked...")
# this will explode, and raise AttributeError
m.forbidden = 4

You ask:

Where is read_only_properties coming from?

Glad you asked, here is the source for read_only_properties:

def read_only_properties(*attrs):

    def class_rebuilder(cls):
        "The class decorator"

        class NewClass(cls):
            "This is the overwritten class"
            def __setattr__(self, name, value):
                if name not in attrs:
                    pass
                elif name not in self.__dict__:
                    pass
                else:
                    raise AttributeError("Can't modify {}".format(name))

                super().__setattr__(name, value)
        return NewClass
    return class_rebuilder

update

I never expected this answer will get so much attention. Surprisingly it does. This encouraged me to create a package you can use.

$ pip install read-only-properties

in your python shell:

In [1]: from rop import read_only_properties

In [2]: @read_only_properties('a')
   ...: class Foo:
   ...:     def __init__(self, a, b):
   ...:         self.a = a
   ...:         self.b = b
   ...:         

In [3]: f=Foo('explodes', 'ok-to-overwrite')

In [4]: f.b = 5

In [5]: f.a = 'boom'
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-5-a5226072b3b4> in <module>()
----> 1 f.a = 'boom'

/home/oznt/.virtualenvs/tracker/lib/python3.5/site-packages/rop.py in __setattr__(self, name, value)
    116                     pass
    117                 else:
--> 118                     raise AttributeError("Can't touch {}".format(name))
    119 
    120                 super().__setattr__(name, value)

AttributeError: Can't touch a

CMake complains "The CXX compiler identification is unknown"

Your /home/gnu/bin/c++ seem to require additional flag to link things properly and CMake doesn't know about that.

To use /usr/bin/c++ as your compiler run cmake with -DCMAKE_CXX_COMPILER=/usr/bin/c++.

Also, CMAKE_PREFIX_PATH variable sets destination dir where your project' files should be installed. It has nothing to do with CMake installation prefix and CMake itself already know this.

Pyspark replace strings in Spark dataframe column

For scala

import org.apache.spark.sql.functions.regexp_replace
import org.apache.spark.sql.functions.col
data.withColumn("addr_new", regexp_replace(col("addr_line"), "\\*", ""))

How to get a vCard (.vcf file) into Android contacts from website

I had problems with importing a VERSION:4.0 vcard file on Android 7 (LineageOS) with the standard Contacts app.

Since this is on the top search hits for "android vcard format not supported", I just wanted to note that I was able to import them with the Simple Contacts app (Play or F-Droid).

How to include jQuery in ASP.Net project?

There are actually a few ways this can be done:

1: Download

You can download the latest version of jQuery and then include it in your page with a standard HTML script tag. This can be done within the master or an individual page.

HTML5

<script src="/scripts/jquery-2.1.0.min.js"></script>

HTML4

<script src="/scripts/jquery-2.1.0.min.js" type="text/javascript"></script>

2: Content Delivery Network

You can include jQuery to your site using a CDN (Content Delivery Network) such as Google's. This should help reduce page load times if the user has already visited a site using the same version from the same CDN.

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

3: NuGet Package Manager

Lastly, (my preferred) use NuGet which is shipped with Visual Studio and Visual Studio Express. This is accessed from right-clicking on your project and clicking Manage NuGet Packages.

NuGet is an open source Library Package Manager that comes as a Visual Studio extension and that makes it very easy to add, remove, and update external libraries in your Visual Studio projects and websites. Beginning ASP.NET 4.5 in C# and VB.NET, WROX, 2013

enter image description here

Once installed, a new Folder group will appear in your Solution Explorer called Scripts. Simply drag and drop the file you wish to include onto your page of choice.

This method is ideal for larger projects because if you choose to remove the files, or change versions later (though the package manager) if will automatically remove/update any reference to that file within your project.

The only downside to this approach is it does not use a CDN to host the file so page load time may be slightly slower the first time the user visits your site.

How to differentiate single click event and double click event?

Well in order to double click (click twice) you must first click once. The click() handler fires on your first click, and since the alert pops up, you don't have a chance to make the second click to fire the dblclick() handler.

Change your handlers to do something other than an alert() and you'll see the behaviour. (perhaps change the background color of the element):

$("#my_id").click(function() { 
    $(this).css('backgroundColor', 'red')
});

$("#my_id").dblclick(function() {
    $(this).css('backgroundColor', 'green')
});

Is there a wikipedia API just for retrieve content summary?

My approach was as follows (in PHP):

$url = "whatever_you_need"

$html = file_get_contents('https://en.wikipedia.org/w/api.php?action=opensearch&search='.$url);
$utf8html = html_entity_decode(preg_replace("/U\+([0-9A-F]{4})/", "&#x\\1;", $html), ENT_NOQUOTES, 'UTF-8');

$utf8html might need further cleaning, but that's basically it.

Do I need a content-type header for HTTP GET requests?

GET requests can have "Accept" headers, which say which types of content the client understands. The server can then use that to decide which content type to send back.

They're optional though.

http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1

Conditional WHERE clause in SQL Server

The problem with your query is that in CASE expressions, the THEN and ELSE parts have to have an expression that evaluates to a number or a varchar or any other datatype but not to a boolean value.

You just need to use boolean logic (or rather the ternary logic that SQL uses) and rewrite it:

WHERE 
    DateDropped = 0
AND ( @JobsOnHold = 1 AND DateAppr >= 0 
   OR (@JobsOnHold <> 1 OR @JobsOnHold IS NULL) AND DateAppr <> 0
    )

How to manage local vs production settings in Django?

In order to use different settings configuration on different environment, create different settings file. And in your deployment script, start the server using --settings=<my-settings.py> parameter, via which you can use different settings on different environment.

Benefits of using this approach:

  1. Your settings will be modular based on each environment

  2. You may import the master_settings.py containing the base configuration in the environmnet_configuration.py and override the values that you want to change in that environment.

  3. If you have huge team, each developer may have their own local_settings.py which they can add to the code repository without any risk of modifying the server configuration. You can add these local settings to .gitnore if you use git or .hginore if you Mercurial for Version Control (or any other). That way local settings won't even be the part of actual code base keeping it clean.

Remove all git files from a directory?

In case someone else stumbles onto this topic - here's a more "one size fits all" solution.

If you are using .git or .svn, you can use the --exclude-vcs option for tar. This will ignore many different files/folders required by different version control systems.

If you want to read more about it, check out: http://www.gnu.org/software/tar/manual/html_section/exclude.html

Xlib: extension "RANDR" missing on display ":21". - Trying to run headless Google Chrome

Try this:

Xvfb :21 -screen 0 1024x768x24 +extension RANDR &
Xvfb --help

+extension name        Enable extension
-extension name        Disable extension

Include another HTML file in a HTML file

Expanding lolo's answer from above, here is a little more automation if you have to include a lot of files. Use this JS code:

$(function () {
  var includes = $('[data-include]')
  $.each(includes, function () {
    var file = 'views/' + $(this).data('include') + '.html'
    $(this).load(file)
  })
})

And then to include something in the html:

<div data-include="header"></div>
<div data-include="footer"></div>

Which would include the file views/header.html and views/footer.html.

copy-item With Alternate Credentials

Bringing this back from the dead again. I got around a similar credentials problem by wrapping the .ps1 in a batch file and doing the Win7, Shift + r.Click RunAs. If you wanted to, you can also use PsExec thus:

psexec.exe /accepteula /h /u user /p pwd cmd /c "echo. | powershell.exe -File script.ps1"

Check for false

You can use something simpler:

if(!var){
    console.log('var is false'); 
}

Context.startForegroundService() did not then call Service.startForeground()

Since everybody visiting here is suffering the same thing, I want to share my solution that nobody else has tried before (in this question anyways). I can assure you that it is working, even on a stopped breakpoint which confirms this method.

The issue is to call Service.startForeground(id, notification) from the service itself, right? Android Framework unfortunately does not guarantee to call Service.startForeground(id, notification) within Service.onCreate() in 5 seconds but throws the exception anyway, so I've come up with this way.

  1. Bind the service to a context with a binder from the service before calling Context.startForegroundService()
  2. If the bind is successful, call Context.startForegroundService() from the service connection and immediately call Service.startForeground() inside the service connection.
  3. IMPORTANT NOTE: Call the Context.bindService() method inside a try-catch because in some occasions the call can throw an exception, in which case you need to rely on calling Context.startForegroundService() directly and hope it will not fail. An example can be a broadcast receiver context, however getting application context does not throw an exception in that case, but using the context directly does.

This even works when I'm waiting on a breakpoint after binding the service and before triggering the "startForeground" call. Waiting between 3-4 seconds do not trigger the exception while after 5 seconds it throws the exception. (If the device cannot execute two lines of code in 5 seconds, then it's time to throw that in the trash.)

So, start with creating a service connection.

// Create the service connection.
ServiceConnection connection = new ServiceConnection()
{
    @Override
    public void onServiceConnected(ComponentName name, IBinder service)
    {
        // The binder of the service that returns the instance that is created.
        MyService.LocalBinder binder = (MyService.LocalBinder) service;

        // The getter method to acquire the service.
        MyService myService = binder.getService();

        // getServiceIntent(context) returns the relative service intent 
        context.startForegroundService(getServiceIntent(context));

        // This is the key: Without waiting Android Framework to call this method
        // inside Service.onCreate(), immediately call here to post the notification.
        myService.startForeground(myNotificationId, MyService.getNotification());

        // Release the connection to prevent leaks.
        context.unbindService(this);
    }

    @Override
    public void onBindingDied(ComponentName name)
    {
        Log.w(TAG, "Binding has dead.");
    }

    @Override
    public void onNullBinding(ComponentName name)
    {
        Log.w(TAG, "Bind was null.");
    }

    @Override
    public void onServiceDisconnected(ComponentName name)
    {
        Log.w(TAG, "Service is disconnected..");
    }
};

Inside your service, create a binder that returns the instance of your service.

public class MyService extends Service
{
    public class LocalBinder extends Binder
    {
        public MyService getService()
        {
            return MyService.this;
        }
    }

    // Create the instance on the service.
    private final LocalBinder binder = new LocalBinder();

    // Return this instance from onBind method.
    // You may also return new LocalBinder() which is
    // basically the same thing.
    @Nullable
    @Override
    public IBinder onBind(Intent intent)
    {
        return binder;
    }
}

Then, try to bind the service from that context. If it succeeds, it will call ServiceConnection.onServiceConnected() method from the service connection that you're using. Then, handle the logic in the code that's shown above. An example code would look like this:

// Try to bind the service
try
{
     context.bindService(getServiceIntent(context), connection,
                    Context.BIND_AUTO_CREATE);
}
catch (RuntimeException ignored)
{
     // This is probably a broadcast receiver context even though we are calling getApplicationContext().
     // Just call startForegroundService instead since we cannot bind a service to a
     // broadcast receiver context. The service also have to call startForeground in
     // this case.
     context.startForegroundService(getServiceIntent(context));
}

It seems to be working on the applications that I develop, so it should work when you try as well.

What is git tag, How to create tags & How to checkout git remote tag(s)

In order to checkout a git tag , you would execute the following command

git checkout tags/tag-name -b branch-name

eg as mentioned below.

 git checkout tags/v1.0 -b v1.0-branch

To fetch the all tags use the command

git fetch --all --tags

The difference between fork(), vfork(), exec() and clone()

  1. fork() - creates a new child process, which is a complete copy of the parent process. Child and parent processes use different virtual address spaces, which is initially populated by the same memory pages. Then, as both processes are executed, the virtual address spaces begin to differ more and more, because the operating system performs a lazy copying of memory pages that are being written by either of these two processes and assigns an independent copies of the modified pages of memory for each process. This technique is called Copy-On-Write (COW).
  2. vfork() - creates a new child process, which is a "quick" copy of the parent process. In contrast to the system call fork(), child and parent processes share the same virtual address space. NOTE! Using the same virtual address space, both the parent and child use the same stack, the stack pointer and the instruction pointer, as in the case of the classic fork()! To prevent unwanted interference between parent and child, which use the same stack, execution of the parent process is frozen until the child will call either exec() (create a new virtual address space and a transition to a different stack) or _exit() (termination of the process execution). vfork() is the optimization of fork() for "fork-and-exec" model. It can be performed 4-5 times faster than the fork(), because unlike the fork() (even with COW kept in the mind), implementation of vfork() system call does not include the creation of a new address space (the allocation and setting up of new page directories).
  3. clone() - creates a new child process. Various parameters of this system call, specify which parts of the parent process must be copied into the child process and which parts will be shared between them. As a result, this system call can be used to create all kinds of execution entities, starting from threads and finishing by completely independent processes. In fact, clone() system call is the base which is used for the implementation of pthread_create() and all the family of the fork() system calls.
  4. exec() - resets all the memory of the process, loads and parses specified executable binary, sets up new stack and passes control to the entry point of the loaded executable. This system call never return control to the caller and serves for loading of a new program to the already existing process. This system call with fork() system call together form a classical UNIX process management model called "fork-and-exec".

uint8_t vs unsigned char

In my experience there are two places where we want to use uint8_t to mean 8 bits (and uint16_t, etc) and where we can have fields smaller than 8 bits. Both places are where space matters and we often need to look at a raw dump of the data when debugging and need to be able to quickly determine what it represents.

The first is in RF protocols, especially in narrow-band systems. In this environment we may need to pack as much information as we can into a single message. The second is in flash storage where we may have very limited space (such as in embedded systems). In both cases we can use a packed data structure in which the compiler will take care of the packing and unpacking for us:

#pragma pack(1)
typedef struct {
  uint8_t    flag1:1;
  uint8_t    flag2:1;
  padding1   reserved:6;  /* not necessary but makes this struct more readable */
  uint32_t   sequence_no;
  uint8_t    data[8];
  uint32_t   crc32;
} s_mypacket __attribute__((packed));
#pragma pack()

Which method you use depends on your compiler. You may also need to support several different compilers with the same header files. This happens in embedded systems where devices and servers can be completely different - for example you may have an ARM device that communicates with an x86 Linux server.

There are a few caveats with using packed structures. The biggest gotcha is that you must avoid dereferencing the address of a member. On systems with mutibyte aligned words, this can result in a misaligned exception - and a coredump.

Some folks will also worry about performance and argue that using these packed structures will slow down your system. It is true that, behind the scenes, the compiler adds code to access the unaligned data members. You can see that by looking at the assembly code in your IDE.

But since packed structures are most useful for communication and data storage then the data can be extracted into a non-packed representation when working with it in memory. Normally we do not need to be working with the entire data packet in memory anyway.

Here is some relevant discussion:

pragma pack(1) nor __attribute__ ((aligned (1))) works

Is gcc's __attribute__((packed)) / #pragma pack unsafe?

http://solidsmoke.blogspot.ca/2010/07/woes-of-structure-packing-pragma-pack.html

How can I change a button's color on hover?

Seems your selector is wrong, try using:

a.button:hover{
     background: #383;
}

Your code

a.button a:hover

Means it is going to search for an a element inside a with class button.

How to register ASP.NET 2.0 to web server(IIS7)?

The system I was working on is Windows Server 2008 Standard with IIS 7 (I guess that my experience will apply for all Windows systems of the same age).

Running

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir

SEEMED to work, as

C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -lv

showed the .Net framework v4 registered with IIS.

But, running the same for .Net v2, namely

C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -ir

did NOT result in

C:\Windows\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis.exe -lv

showing the framework registered.

(And, for me, the installer for Kofax Capture Network Server was still missing ASP.NET.)

The solution was:

  • Open Server Manager
  • Go to Roles/Web Server (IIS)
  • Push Add Role Services
  • check ASP.NET under Application Development (and press Install)

After that, aspnet_regiis.exe -lv (either version) shows the framework registered. (And the Kofax installer was also happy and worked.)

How to check if array is empty or does not exist?

You want to do the check for undefined first. If you do it the other way round, it will generate an error if the array is undefined.

if (array === undefined || array.length == 0) {
    // array empty or does not exist
}

Update

This answer is getting a fair amount of attention, so I'd like to point out that my original answer, more than anything else, addressed the wrong order of the conditions being evaluated in the question. In this sense, it fails to address several scenarios, such as null values, other types of objects with a length property, etc. It is also not very idiomatic JavaScript.

The foolproof approach
Taking some inspiration from the comments, below is what I currently consider to be the foolproof way to check whether an array is empty or does not exist. It also takes into account that the variable might not refer to an array, but to some other type of object with a length property.

if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
  // ? do not attempt to process array
}

To break it down:

  1. Array.isArray(), unsurprisingly, checks whether its argument is an array. This weeds out values like null, undefined and anything else that is not an array.
    Note that this will also eliminate array-like objects, such as the arguments object and DOM NodeList objects. Depending on your situation, this might not be the behavior you're after.

  2. The array.length condition checks whether the variable's length property evaluates to a truthy value. Because the previous condition already established that we are indeed dealing with an array, more strict comparisons like array.length != 0 or array.length !== 0 are not required here.

The pragmatic approach
In a lot of cases, the above might seem like overkill. Maybe you're using a higher order language like TypeScript that does most of the type-checking for you at compile-time, or you really don't care whether the object is actually an array, or just array-like.

In those cases, I tend to go for the following, more idiomatic JavaScript:

if (!array || !array.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or, more frequently, its inverse:

if (array && array.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

With the introduction of the optional chaining operator (Elvis operator) in ECMAScript 2020, this can be shortened even further:

if (!array?.length) {
    // array or array.length are falsy
    // ? do not attempt to process array
}

Or the opposite:

if (array?.length) {
    // array and array.length are truthy
    // ? probably OK to process array
}

Text size of android design TabLayout tabs

Work on api 22 & 23 Make this style :

<style name="TabLayoutStyle" parent="Base.Widget.Design.TabLayout">
    <item name="android:textSize">12sp</item>
    <item name="android:textAllCaps">true</item>
</style>

And apply it to your tablayout :

<android.support.design.widget.TabLayout
    android:id="@+id/contentTabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dp"
    android:background="@drawable/list_gray_border"
    app:tabTextAppearance="@style/TabLayoutStyle"
    app:tabSelectedTextColor="@color/colorPrimaryDark"
    app:tabTextColor="@color/colorGrey"
    app:tabMode="fixed"
    app:tabGravity="fill"/>

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

If there is an on-screen keyboard, focusing a text field that is near the bottom of the viewport will cause Safari to scroll the text field into view. There might be some way to exploit this phenomenon to detect the presence of the keyboard (having a tiny text field at the bottom of the page which gains focus momentarily, or something like that).

SQL keys, MUL vs PRI vs UNI

UNI: For UNIQUE:

  • It is a set of one or more columns of a table to uniquely identify the record.
  • A table can have multiple UNIQUE key.
  • It is quite like primary key to allow unique values but can accept one null value which primary key does not.

PRI: For PRIMARY:

  • It is also a set of one or more columns of a table to uniquely identify the record.
  • A table can have only one PRIMARY key.
  • It is quite like UNIQUE key to allow unique values but does not allow any null value.

MUL: For MULTIPLE:

  • It is also a set of one or more columns of a table which does not identify the record uniquely.
  • A table can have more than one MULTIPLE key.
  • It can be created in table on index or foreign key adding, it does not allow null value.
  • It allows duplicate entries in column.
  • If we do not specify MUL column type then it is quite like a normal column but can allow null entries too hence; to restrict such entries we need to specify it.
  • If we add indexes on column or add foreign key then automatically MUL key type added.

Cannot read property 'getContext' of null, using canvas

I guess the problem is your js runs before the html is loaded.

If you are using jquery, you can use the document ready function to wrap your code:

$(function() {
    var Grid = function(width, height) {
        // codes...
    }
});

Or simply put your js after the <canvas>.

jQuery DatePicker with today as maxDate

For those who dont want to use datepicker method

var alldatepicker=  $("[class$=hasDatepicker]");

alldatepicker.each(function(){

var value=$(this).val();

var today = new Date();

var dd = today.getDate();

var mm = today.getMonth()+1; //January is 0!

var yyyy = today.getFullYear();

if(dd<10) {

    dd='0'+dd

} 
if(mm<10) {

    mm='0'+mm

} 
today = mm+'/'+dd+'/'+yyyy;
if(value!=''){
if(value>today){
alert("Date cannot be greater than current date");
}
}
}); 

JDK on OSX 10.7 Lion

For Mountain Lion, Apple's java is up to 1.6.0_35-b10-428.jdk as of today.
It is indeed located under /Library/Java/JavaVirtualMachines .

You just download
"Java for OS X 2012-005 Developer Package" (Sept 6, 2012)
from
http://connect.apple.com/

In my view, Apple's naming is at least a bit confusing; why "-005" - is this the fifth version, or the fifth of five installers one needs?

And then run the installer; then follow the above steps inside Eclipse.

Get the new record primary key ID from MySQL insert query?

You will receive these parameters on your query result:

    "fieldCount": 0,
    "affectedRows": 1,
    "insertId": 66,
    "serverStatus": 2,
    "warningCount": 1,
    "message": "",
    "protocol41": true,
    "changedRows": 0

The insertId is exactly what you need.

(NodeJS-mySql)

What exactly does the "u" do? "git push -u origin master" vs "git push origin master"

All necessary git bash commands to push and pull into Github:

git status 
git pull
git add filefullpath

git commit -m "comments for checkin file" 
git push origin branch/master
git remote -v 
git log -2 

If you want to edit a file then:

edit filename.* 

To see all branches and their commits:

git show-branch

Python foreach equivalent

Like this:

for pet in pets :
  print(pet)

In fact, Python only has foreach style for loops.

How do I get monitor resolution in Python?

If you are using the Qt toolkit specifically PySide, you can do the following:

from PySide import QtGui
import sys

app = QtGui.QApplication(sys.argv)
screen_rect = app.desktop().screenGeometry()
width, height = screen_rect.width(), screen_rect.height()

Editing hosts file to redirect url?

hosts file:

1.2.3.4 google.com

1.2.3.4 - ip of your server.

Run script on the server for redirecting users to url that you want.

How to use SharedPreferences in Android to store, fetch and edit values

To store values in shared preferences:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = sp.edit();
editor.putString("Name","Jayesh");
editor.commit();

To retrieve values from shared preferences:

SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
String name = sp.getString("Name", "");

Uncaught TypeError: Cannot set property 'value' of null

guys This error because of Element Id not Visible from js Try to inspect element from UI and paste it on javascript file:

before :

document.getElementById('form:salesoverviewform:ticketstatusid').value =topping;

After :

document.getElementById('form:salesoverviewform:j_idt190:ticketstatusid').value =topping;

Credits to Divya Akka .... :)

How can I change the color of AlertDialog title and the color of the line under it

    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.BLACK);

    String title = context.getString(R.string.agreement_popup_message);
    SpannableStringBuilder ssBuilder = new SpannableStringBuilder(title);
    ssBuilder.setSpan(
            foregroundColorSpan,
            0,
            title.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    );

AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(context);
alertDialogBuilderUserInput.setTitle(ssBuilder)

How to convert ISO8859-15 to UTF8?

I got the same problem, but i find the answer in this page! it works for me, you can try it.

iconv -f cp936 -t utf-8 

How can I see the entire HTTP request that's being sent by my Python application?

You can use HTTP Toolkit to do exactly this.

It's especially useful if you need to do this quickly, with no code changes: you can open a terminal from HTTP Toolkit, run any Python code from there as normal, and you'll be able to see the full content of every HTTP/HTTPS request immediately.

There's a free version that can do everything you need, and it's 100% open source.

I'm the creator of HTTP Toolkit; I actually built it myself to solve the exact same problem for me a while back! I too was trying to debug a payment integration, but their SDK didn't work, I couldn't tell why, and I needed to know what was actually going on to properly fix it. It's very frustrating, but being able to see the raw traffic really helps.

Declaring and using MySQL varchar variables

This works fine for me using MySQL 5.1.35:

DELIMITER $$

DROP PROCEDURE IF EXISTS `example`.`test` $$
CREATE PROCEDURE `example`.`test` ()
BEGIN

  DECLARE FOO varchar(7);
  DECLARE oldFOO varchar(7);
  SET FOO = '138';
  SET oldFOO = CONCAT('0', FOO);

  update mypermits
     set person = FOO
   where person = oldFOO;

END $$

DELIMITER ;

Table:

DROP TABLE IF EXISTS `example`.`mypermits`;
CREATE TABLE  `example`.`mypermits` (
  `person` varchar(7) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO mypermits VALUES ('0138');

CALL test()

Bootstrap modal: close current, open new

With BootStrap 3, you can try this:-

var visible_modal = jQuery('.modal.in').attr('id'); // modalID or undefined
if (visible_modal) { // modal is active
    jQuery('#' + visible_modal).modal('hide'); // close modal
}

Tested to work with: http://getbootstrap.com/javascript/#modals (click on "Launch Demo Modal" first).

Understanding checked vs unchecked exceptions in Java

  1. Is the above considered to be a checked exception? No The fact that you are handling an exception does not make it a Checked Exception if it is a RuntimeException.

  2. Is RuntimeException an unchecked exception? Yes

Checked Exceptions are subclasses of java.lang.Exception Unchecked Exceptions are subclasses of java.lang.RuntimeException

Calls throwing checked exceptions need to be enclosed in a try{} block or handled in a level above in the caller of the method. In that case the current method must declare that it throws said exceptions so that the callers can make appropriate arrangements to handle the exception.

Hope this helps.

Q: should I bubble up the exact exception or mask it using Exception?

A: Yes this is a very good question and important design consideration. The class Exception is a very general exception class and can be used to wrap internal low level exceptions. You would better create a custom exception and wrap inside it. But, and a big one - Never ever obscure in underlying original root cause. For ex, Don't ever do following -

try {
     attemptLogin(userCredentials);
} catch (SQLException sqle) {
     throw new LoginFailureException("Cannot login!!"); //<-- Eat away original root cause, thus obscuring underlying problem.
}

Instead do following:

try {
     attemptLogin(userCredentials);
} catch (SQLException sqle) {
     throw new LoginFailureException(sqle); //<-- Wrap original exception to pass on root cause upstairs!.
}

Eating away original root cause buries the actual cause beyond recovery is a nightmare for production support teams where all they are given access to is application logs and error messages. Although the latter is a better design but many people don't use it often because developers just fail to pass on the underlying message to caller. So make a firm note: Always pass on the actual exception back whether or not wrapped in any application specific exception.

On try-catching RuntimeExceptions

RuntimeExceptions as a general rule should not be try-catched. They generally signal a programming error and should be left alone. Instead the programmer should check the error condition before invoking some code which might result in a RuntimeException. For ex:

try {
    setStatusMessage("Hello Mr. " + userObject.getName() + ", Welcome to my site!);
} catch (NullPointerException npe) {
   sendError("Sorry, your userObject was null. Please contact customer care.");
}

This is a bad programming practice. Instead a null-check should have been done like -

if (userObject != null) {
    setStatusMessage("Hello Mr. " + userObject.getName() + ", Welome to my site!);
} else {
   sendError("Sorry, your userObject was null. Please contact customer care.");
}

But there are times when such error checking is expensive such as number formatting, consider this -

try {
    String userAge = (String)request.getParameter("age");
    userObject.setAge(Integer.parseInt(strUserAge));
} catch (NumberFormatException npe) {
   sendError("Sorry, Age is supposed to be an Integer. Please try again.");
}

Here pre-invocation error checking is not worth the effort because it essentially means to duplicate all the string-to-integer conversion code inside parseInt() method - and is error prone if implemented by a developer. So it is better to just do away with try-catch.

So NullPointerException and NumberFormatException are both RuntimeExceptions, catching a NullPointerException should replaced with a graceful null-check while I recommend catching a NumberFormatException explicitly to avoid possible introduction of error prone code.

How can I pass a Bitmap object from one activity to another

In my case, the way mentioned above didn't worked for me. Every time I put the bitmap in the intent, the 2nd activity didn't start. The same happened when I passed the bitmap as byte[].

I followed this link and it worked like a charme and very fast:

package your.packagename

import android.graphics.Bitmap;

public class CommonResources { 
      public static Bitmap photoFinishBitmap = null;
}

in my 1st acitiviy:

Constants.photoFinishBitmap = photoFinishBitmap;
Intent intent = new Intent(mContext, ImageViewerActivity.class);
startActivity(intent);

and here is the onCreate() of my 2nd Activity:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bitmap photo = Constants.photoFinishBitmap;
    if (photo != null) {
        mViewHolder.imageViewerImage.setImageDrawable(new BitmapDrawable(getResources(), photo));
    }
}

How to obtain the number of CPUs/cores in Linux from the command line?

You can also use Python! To get the number of physical cores:

$ python -c "import psutil; print(psutil.cpu_count(logical=False))"
4

To get the number of hyperthreaded cores:

$ python -c "import psutil; print(psutil.cpu_count(logical=True))"
8

SQL Server convert string to datetime

For instance you can use

update tablename set datetimefield='19980223 14:23:05'
update tablename set datetimefield='02/23/1998 14:23:05'
update tablename set datetimefield='1998-12-23 14:23:05'
update tablename set datetimefield='23 February 1998 14:23:05'
update tablename set datetimefield='1998-02-23T14:23:05'

You need to be careful of day/month order since this will be language dependent when the year is not specified first. If you specify the year first then there is no problem; date order will always be year-month-day.

How can I get column names from a table in Oracle?

SELECT COLUMN_NAME 'all_columns' 
FROM INFORMATION_SCHEMA.COLUMNS 
WHERE TABLE_NAME='user';

How do I make a JAR from a .java file?

Open a command prompt.

Go to the directory where you have your .java files

Create a directory build

Run java compilation from the command line

javac -d ./build *.java

if there are no errors, in the build directory you should have your class tree

move to the build directory and do a

jar cvf YourJar.jar *

For adding manifest check jar command line switches

How to empty a Heroku database

Assuming you want to reset your PostgreSQL database and set it back up, use:

heroku apps

to list your applications on Heroku. Find the name of your current application (application_name). Then run

heroku config | grep POSTGRESQL

to get the name of your databases. An example could be

HEROKU_POSTGRESQL_WHITE_URL

Finally, given application_name and database_url, you should run

heroku pg:reset `database_url` --confirm `application_name`
heroku run rake db:migrate
heroku restart

initializing strings as null vs. empty string

There's a function empty() ready for you in std::string:

std::string a;
if(a.empty())
{
    //do stuff. You will enter this block if the string is declared like this
}

or

std::string a;
if(!a.empty())
{
    //You will not enter this block now
}
a = "42";
if(!a.empty())
{
    //And now you will enter this block.
}

Find and kill a process in one line using bash and regex

killall -r regexp

-r, --regexp

Interpret process name pattern as an extended regular expression.

How to set thousands separator in Java?

DecimalFormatSymbols formatSymbols = new DecimalFormatSymbols();
formatSymbols.setDecimalSeparator('|');
formatSymbols.setGroupingSeparator(' ');

String strange = "#,##0.###";
DecimalFormat df = new DecimalFormat(strange, formatSymbols);
df.setGroupingSize(4);

String out = df.format(new BigDecimal(300000).doubleValue());

System.out.println(out);

How to stop java process gracefully?

Thanks for you answers. Shutdown hooks seams like something that would work in my case. But I also bumped into the thing called Monitoring and Management beans:
http://java.sun.com/j2se/1.5.0/docs/guide/management/overview.html
That gives some nice possibilities, for remote monitoring, and manipulation of the java process. (Was introduced in Java 5)

Is there an online application that automatically draws tree structures for phrases/sentences?

In short, yes. I assume you're looking to parse English: for that you can use the Link Parser from Carnegie Mellon.

It is important to remember that there are many theories of syntax, that can give completely different-looking phrase structure trees; further, the trees are different for each language, and tools may not exist for those languages.

As a note for the future: if you need a sentence parsed out and tag it as linguistics (and syntax or whatnot, if that's available), someone can probably parse it out for you and guide you through it.

How to format code in Xcode?

Key combination to format all text on open file:

Cmd ? A + Ctrl I

Parallel.ForEach vs Task.Factory.StartNew

In my view the most realistic scenario is when tasks have a heavy operation to complete. Shivprasad's approach focuses more on object creation/memory allocation than on computing itself. I made a research calling the following method:

public static double SumRootN(int root)
{
    double result = 0;
    for (int i = 1; i < 10000000; i++)
        {
            result += Math.Exp(Math.Log(i) / root);
        }
        return result; 
}

Execution of this method takes about 0.5sec.

I called it 200 times using Parallel:

Parallel.For(0, 200, (int i) =>
{
    SumRootN(10);
});

Then I called it 200 times using the old-fashioned way:

List<Task> tasks = new List<Task>() ;
for (int i = 0; i < loopCounter; i++)
{
    Task t = new Task(() => SumRootN(10));
    t.Start();
    tasks.Add(t);
}

Task.WaitAll(tasks.ToArray()); 

First case completed in 26656ms, the second in 24478ms. I repeated it many times. Everytime the second approach is marginaly faster.

How to remove whitespace from a string in typescript?

The trim() method removes whitespace from both sides of a string.

To remove all the spaces from the string use .replace(/\s/g, "")

 this.maintabinfo = this.inner_view_data.replace(/\s/g, "").toLowerCase();

Rails - How to use a Helper Inside a Controller

You can use

  • helpers.<helper> in Rails 5+ (or ActionController::Base.helpers.<helper>)
  • view_context.<helper> (Rails 4 & 3) (WARNING: this instantiates a new view instance per call)
  • @template.<helper> (Rails 2)
  • include helper in a singleton class and then singleton.helper
  • include the helper in the controller (WARNING: will make all helper methods into controller actions)

When using Trusted_Connection=true and SQL Server authentication, will this affect performance?

This will probably have some performance costs when creating the connection but as connections are pooled, they are created only once and then reused, so it won't make any difference to your application. But as always: measure it.


UPDATE:

There are two authentication modes:

  1. Windows Authentication mode (corresponding to a trusted connection). Clients need to be members of a domain.
  2. SQL Server Authentication mode. Clients are sending username/password at each connection

Filtering a list of strings based on contents

mylist = ['a', 'ab', 'abc']
assert 'ab' in mylist

Remove json element

I recommend splice method to remove an object from JSON objects array.

jQuery(json).each(function (index){
        if(json[index].FirstName == "Test1"){
            json.splice(index,1); // This will remove the object that first name equals to Test1
            return false; // This will stop the execution of jQuery each loop.
        }
});

I use this because when I use delete method, I get null object after I do JSON.stringify(json)