Programs & Examples On #Vectormath

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

A lot of correct answers been provided so far and I see lot of upvotes. However, the mentioned ways will work but not really optimized or not really readable. I recently came across the solution which every developer will like.

String nameWithProperSpacing = StringUtils.normalizeSpace( stringWithLotOfSpaces );

You are done. This is readable solution.

How to view the committed files you have not pushed yet?

The push command has a -n/--dry-run option which will compute what needs to be pushed but not actually do it. Does that work for you?

New lines inside paragraph in README.md

According to Github API two empty lines are a new paragraph (same as here in stackoverflow)

You can test it with http://prose.io

Cannot ignore .idea/workspace.xml - keeps popping up

If you have multiple projects in your git repo, .idea/workspace.xml will not match to any files.

Instead, do the following:

$ git rm -f **/.idea/workspace.xml

And make your .gitignore look something like this:

# User-specific stuff:
**/.idea/workspace.xml
**/.idea/tasks.xml
**/.idea/dictionaries
**/.idea/vcs.xml
**/.idea/jsLibraryMappings.xml

# Sensitive or high-churn files:
**/.idea/dataSources.ids
**/.idea/dataSources.xml
**/.idea/dataSources.local.xml
**/.idea/sqlDataSources.xml
**/.idea/dynamic.xml
**/.idea/uiDesigner.xml

## File-based project format:
*.iws

# IntelliJ
/out/

row-level trigger vs statement-level trigger

The main difference between statement level trigger is below :

statement level trigger : based on name it works if any statement is executed. Does not depends on how many rows or any rows effected.It executes only once. Exp : if you want to update salary of every employee from department HR and at the end you want to know how many rows get effected means how many got salary increased then use statement level trigger. please note that trigger will execute even if zero rows get updated because it is statement level trigger is called if any statement has been executed. No matters if it is affecting any rows or not.

Row level trigger : executes each time when an row is affected. if zero rows affected.no row level trigger will execute.suppose if u want to delete one employye from emp table whose department is HR and u want as soon as employee deleted from emp table the count in dept table from HR section should be reduce by 1.then you should opt for row level trigger.

PHP check if date between two dates

Simple solution:

function betweenDates($cmpDate,$startDate,$endDate){ 
   return (date($cmpDate) > date($startDate)) && (date($cmpDate) < date($endDate));
}

filtering a list using LINQ

var result = projects.Where(p => filtedTags.All(t => p.Tags.Contains(t)));

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

Just change your line of code to

<a href="~/Required/[email protected]">Edit</a>

from where you are calling this function that will pass corect id

Using braces with dynamic variable names in PHP

Overview

In PHP, you can just put an extra $ in front of a variable to make it a dynamic variable :

$$variableName = $value;

While I wouldn't recommend it, you could even chain this behavior :

$$$$$$$$DoNotTryThisAtHomeKids = $value;

You can but are not forced to put $variableName between {} :

${$variableName} = $value;

Using {} is only mandatory when the name of your variable is itself a composition of multiple values, like this :

${$variableNamePart1 . $variableNamePart2} = $value;

It is nevertheless recommended to always use {}, because it's more readable.

Differences between PHP5 and PHP7

Another reason to always use {}, is that PHP5 and PHP7 have a slightly different way of dealing with dynamic variables, which results in a different outcome in some cases.

In PHP7, dynamic variables, properties, and methods will now be evaluated strictly in left-to-right order, as opposed to the mix of special cases in PHP5. The examples below show how the order of evaluation has changed.

Case 1 : $$foo['bar']['baz']

  • PHP5 interpetation : ${$foo['bar']['baz']}
  • PHP7 interpetation : ${$foo}['bar']['baz']

Case 2 : $foo->$bar['baz']

  • PHP5 interpetation : $foo->{$bar['baz']}
  • PHP7 interpetation : $foo->{$bar}['baz']

Case 3 : $foo->$bar['baz']()

  • PHP5 interpetation : $foo->{$bar['baz']}()
  • PHP7 interpetation : $foo->{$bar}['baz']()

Case 4 : Foo::$bar['baz']()

  • PHP5 interpetation : Foo::{$bar['baz']}()
  • PHP7 interpetation : Foo::{$bar}['baz']()

How do I trim whitespace from a string?

As pointed out in answers above

my_string.strip()

will remove all the leading and trailing whitespace characters such as \n, \r, \t, \f, space .

For more flexibility use the following

  • Removes only leading whitespace chars: my_string.lstrip()
  • Removes only trailing whitespace chars: my_string.rstrip()
  • Removes specific whitespace chars: my_string.strip('\n') or my_string.lstrip('\n\r') or my_string.rstrip('\n\t') and so on.

More details are available in the docs.

PHP date() format when inserting into datetime in MySQL

Format MySQL datetime with PHP

$date = "'".date('Y-m-d H:i:s', strtotime(str_replace('-', '/', $_POST['date'])))."'";

Gson library in Android Studio

Use gradle dependencies to get the Gson in your project. Your application build.gradle should look like this-

dependencies {
  implementation 'com.google.code.gson:gson:2.8.2'
}

Javascript/Jquery to change class onclick?

      <div class="liveChatContainer online">
        <div class="actions" id="change">
         <span class="item title">Need help?</span>
              <a href="/test" onclick="demo()"><i class="fa fa-smile-o"></i>Chat</a>
              <a href="/test"><i class="fa fa-smile-o"></i>Call</a>
              <a href="/test"><i class="fa fa-smile-o"></i>Email</a>
        </div>
              <a href="#" class="liveChatLabel">Contact</a>
     </div>
             <style>
               .actions_one{
               background-color: red;
                      } 
              </style>



           <script>
          function demo(){
      document.getElementById("change").setAttribute("class","actions_one");}
            </script>      

Declaring a boolean in JavaScript using just var

As this very useful tutorial says:

var age = 0;

// bad
var hasAge = new Boolean(age);

// good
var hasAge = Boolean(age);

// good
var hasAge = !!age;

popup form using html/javascript/css

There are plenty available. Try using Modal windows of Jquery or DHTML would do good. Put the content in your div or Change your content in div dynamically and show it to the user. It won't be a popup but a modal window.
Jquery's Thickbox would clear your problem.

How to add title to seaborn boxplot

Seaborn box plot returns a matplotlib axes instance. Unlike pyplot itself, which has a method plt.title(), the corresponding argument for an axes is ax.set_title(). Therefore you need to call

sns.boxplot('Day', 'Count', data= gg).set_title('lalala')

A complete example would be:

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
sns.boxplot(x=tips["total_bill"]).set_title("LaLaLa")

plt.show()

Of course you could also use the returned axes instance to make it more readable:

ax = sns.boxplot('Day', 'Count', data= gg)
ax.set_title('lalala')
ax.set_ylabel('lololo')

UICollectionView - dynamic cell height?

Swift 4 answer based on helpful answer from @mbm29414.

Unfortunately, it requires the use of a XIB file. There doesn't appear to be an alternative.

The key parts are using a sizing cell (created only once) and registering the XIB when initializing the collection view.

Then you size each cell dynamically within the sizeForItemAt function.

// UICollectionView Vars and Constants
let CellXIBName = YouViewCell.XIBName
let CellReuseID = YouViewCell.ReuseID
var sizingCell = YouViewCell()


fileprivate func initCollectionView() {
    // Connect to view controller
    collectionView.dataSource = self
    collectionView.delegate = self

    // Register XIB
    collectionView.register(UINib(nibName: CellXIBName, bundle: nil), forCellWithReuseIdentifier: CellReuseID)

    // Create sizing cell for dynamically sizing cells
    sizingCell = Bundle.main.loadNibNamed(CellXIBName, owner: self, options: nil)?.first as! YourViewCell

    // Set scroll direction
    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .vertical
    collectionView.collectionViewLayout = layout

    // Set properties
    collectionView.alwaysBounceVertical = true
    collectionView.alwaysBounceHorizontal = false

    // Set top/bottom padding
    collectionView.contentInset = UIEdgeInsets(top: collectionViewTopPadding, left: collectionViewSidePadding, bottom: collectionViewBottomPadding, right: collectionViewSidePadding)

    // Hide scrollers
    collectionView.showsVerticalScrollIndicator = false
    collectionView.showsHorizontalScrollIndicator = false
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    // Get cell data and render post
    let data = YourData[indexPath.row]
    sizingCell.renderCell(data: data)

    // Get cell size
    sizingCell.setNeedsLayout()
    sizingCell.layoutIfNeeded()
    let cellSize = sizingCell.systemLayoutSizeFitting(UIView.layoutFittingCompressedSize)

    // Return cell size
    return cellSize
}

What is the best way to measure execution time of a function?

Use a Profiler

Your approach will work nevertheless, but if you are looking for more sophisticated approaches. I'd suggest using a C# Profiler.

The advantages they have is:

  • You can even get a statement level breakup
  • No changes required in your codebase
  • Instrumentions generally have very less overhead, hence very accurate results can be obtained.

There are many available open-source as well.

Error in Python IOError: [Errno 2] No such file or directory: 'data.csv'

open looks in the current working directory, which in your case is ~, since you are calling your script from the ~ directory.

You can fix the problem by either

  • cding to the directory containing data.csv before executing the script, or

  • by using the full path to data.csv in your script, or

  • by calling os.chdir(...) to change the current working directory from within your script. Note that all subsequent commands that use the current working directory (e.g. open and os.listdir) may be affected by this.

Rename a file using Java

Yes, you can use File.renameTo(). But remember to have the correct path while renaming it to a new file.

import java.util.Arrays;
import java.util.List;

public class FileRenameUtility {
public static void main(String[] a) {
    System.out.println("FileRenameUtility");
    FileRenameUtility renameUtility = new FileRenameUtility();
    renameUtility.fileRename("c:/Temp");
}

private void fileRename(String folder){
    File file = new File(folder);
    System.out.println("Reading this "+file.toString());
    if(file.isDirectory()){
        File[] files = file.listFiles();
        List<File> filelist = Arrays.asList(files);
        filelist.forEach(f->{
           if(!f.isDirectory() && f.getName().startsWith("Old")){
               System.out.println(f.getAbsolutePath());
               String newName = f.getAbsolutePath().replace("Old","New");
               boolean isRenamed = f.renameTo(new File(newName));
               if(isRenamed)
                   System.out.println(String.format("Renamed this file %s to  %s",f.getName(),newName));
               else
                   System.out.println(String.format("%s file is not renamed to %s",f.getName(),newName));
           }
        });

    }
}

}

Move an array element from one array position to another

let ar = ['a', 'b', 'c', 'd'];

function change( old_array, old_index , new_index ){

  return old_array.map(( item , index, array )=>{
    if( index === old_index ) return array[ new_index ];
    else if( index === new_index ) return array[ old_index ];
    else return item;
  });

}

let result = change( ar, 0, 1 );

console.log( result );

result:

["b", "a", "c", "d"]

Animate element to auto height with jQuery

I needed this functionality for multiple read more area's on one page implementing this into a Wordpress shortcode I ran into the same problem.

Design technically all of the read more span's on the page have a fixed height. And I wanted to be able to expand them separately to an auto height with a toggle. First click: 'expand to full height of text span', second click: 'collapse back to default height of 70px'

Html

 <span class="read-more" data-base="70" data-height="null">
     /* Lots of text determining the height of this span */
 </span>
 <button data-target='read-more'>Read more</button>

CSS

span.read-more {
    position:relative;
    display:block;
    overflow:hidden;
}

So above this looks very simple the data-base attribute I need to set the fixed height needed. The data-height attribute I used to store the actual (dynamic) height of the element.

The jQuery part

jQuery(document).ready(function($){

  $.fn.clickToggle = function(func1, func2) {
      var funcs = [func1, func2];
      this.data('toggleclicked', 0);
      this.click(function() {
          var data = $(this).data();
          var tc = data.toggleclicked;
          $.proxy(funcs[tc], this)();
          data.toggleclicked = (tc + 1) % 2;
      });
      return this;
  };

    function setAttr_height(key) {
        $(key).each(function(){
            var setNormalHeight = $(this).height();
            $(this).attr('data-height', setNormalHeight);
            $(this).css('height', $(this).attr('data-base') + 'px' );
        });
    }
    setAttr_height('.read-more');

    $('[data-target]').clickToggle(function(){
        $(this).prev().animate({height: $(this).prev().attr('data-height')}, 200);
    }, function(){
        $(this).prev().animate({height: $(this).prev().attr('data-base')}, 200);
    });

});

First I've used a clickToggle function for my first and second click. The second function is more important: setAttr_height() All of the .read-more elements have their actual heights set on page load in the base-height attribute. After that the base height is set through the jquery css function.

With both of our attributes set we now can toggle between them in a smooth way. Only chang the data-base to your desired (fixed)height and switch the .read-more class for your own ID

You can all see it working in a fiddle FIDDLE

No jQuery UI needed

How can I create a keystore?

I followed this guide to create the debug keystore.

The command is:

keytool -genkeypair -alias androiddebugkey -keypass android -keystore debug.keystore -storepass android -dname "CN=Android Debug,O=Android,C=US" -validity 9999

How to generate a random string in Ruby

This solution needs external dependency, but seems prettier than another.

  1. Install gem faker
  2. Faker::Lorem.characters(10) # => "ang9cbhoa8"

Integrating CSS star rating into an HTML form

Here is the solution.

The HTML:

<div class="rating">
<span>?</span><span>?</span><span>?</span><span>?</span><span>?</span>
</div>

The CSS:

.rating {
  unicode-bidi: bidi-override;
  direction: rtl;
}
.rating > span {
  display: inline-block;
  position: relative;
  width: 1.1em;
}
.rating > span:hover:before,
.rating > span:hover ~ span:before {
   content: "\2605";
   position: absolute;
}

Hope this helps.

Source

How can I color Python logging output?

This is an Enum containing the colour codes:

class TerminalColour:
    """
    Terminal colour formatting codes
    """
    # https://stackoverflow.com/questions/287871/print-in-terminal-with-colors
    MAGENTA = '\033[95m'
    BLUE = '\033[94m'
    GREEN = '\033[92m'
    YELLOW = '\033[93m'
    RED = '\033[91m'
    GREY = '\033[0m'  # normal
    WHITE = '\033[1m'  # bright white
    UNDERLINE = '\033[4m'

This may be applied to the names of each log level. Be aware that this is a monstrous hack.

logging.addLevelName(logging.INFO, "{}{}{}".format(TerminalColour.WHITE, logging.getLevelName(logging.INFO), TerminalColour.GREY))
logging.addLevelName(logging.WARNING, "{}{}{}".format(TerminalColour.YELLOW, logging.getLevelName(logging.WARNING), TerminalColour.GREY))
logging.addLevelName(logging.ERROR, "{}{}{}".format(TerminalColour.RED, logging.getLevelName(logging.ERROR), TerminalColour.GREY))
logging.addLevelName(logging.CRITICAL, "{}{}{}".format(TerminalColour.MAGENTA, logging.getLevelName(logging.CRITICAL), .GREY))

Note that your log formatter must include the name of the log level

%(levelname)

for example:

    LOGGING = {
...
        'verbose': {
            'format': '%(asctime)s %(levelname)s %(name)s:%(lineno)s %(module)s %(process)d %(thread)d %(message)s'
        },
        'simple': {
            'format': '[%(asctime)s] %(levelname)s %(name)s %(message)s'
        },

C#: Printing all properties of an object

Any other solution/library is in the end going to use reflection to introspect the type...

Manually install Gradle and use it in Android Studio

1.Download the Gradle form gradle distribution

2.Extract file to some location

3.Open Android Studio : File > Settings > Gradle > Use local gradle distribution navigate the path where you have extracted the gradle.

4.click apply and ok

Done

Check whether an array is empty

<?php
if(empty($myarray))
echo"true";
else
echo "false";
?>

How can I make a div not larger than its contents?

OK, in many cases you even don't need to do anything as by default div has height and width as auto, but if it's not your case, applying inline-block display gonna work for you... look at the code I create for you and it's do what you looking for:

_x000D_
_x000D_
div {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div>_x000D_
  <table>_x000D_
    <tr>_x000D_
      <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi ultrices feugiat massa sed laoreet. Maecenas et magna egestas, facilisis purus quis, vestibulum nibh.</td>_x000D_
      <td>Nunc auctor aliquam est ac viverra. Sed enim nisi, feugiat sed accumsan eu, convallis eget felis. Pellentesque consequat eu leo nec pharetra. Aenean interdum enim dapibus diam.</td>_x000D_
      <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi ultrices feugiat massa sed laoreet. Maecenas et magna egestas, facilisis purus quis, vestibulum nibh.</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Mod of negative number is melting my brain

For the more performance aware devs

uint wrap(int k, int n) ((uint)k)%n

A small performance comparison

Modulo: 00:00:07.2661827 ((n%x)+x)%x)
Cast:   00:00:03.2202334 ((uint)k)%n
If:     00:00:13.5378989 ((k %= n) < 0) ? k+n : k

As for performance cost of cast to uint have a look here

how to make twitter bootstrap submenu to open on the left side?

Only thing you have to do is

 <ul style='left:-100%'> 

of the menu which you want to display on RIGHT side.

App store link for "rate/review this app"

Update:

Swift 5.1, Xcode 11

Tested on Real Device iOS 13.0 (Guarantee to work)

import StoreKit

func rateApp() {

    if #available(iOS 10.3, *) {

        SKStoreReviewController.requestReview()
    
    } else {

        let appID = "Your App ID on App Store"
        let urlStr = "https://itunes.apple.com/app/id\(appID)" // (Option 1) Open App Page    
        let urlStr = "https://itunes.apple.com/app/id\(appID)?action=write-review" // (Option 2) Open App Review Page
        
        guard let url = URL(string: urlStr), UIApplication.shared.canOpenURL(url) else { return }
        
        if #available(iOS 10.0, *) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        } else {
            UIApplication.shared.openURL(url) // openURL(_:) is deprecated from iOS 10.
        }
    }
}

Exclude all transitive dependencies of a single dependency

If you develop under Eclipse, you can in the POM Editor (advanced tabs enabled) dependency graph look for the dependency you want to exclude of your project and then:

right click on it -> "Exclude Maven Artifact ..." and Eclipse will make the exclusion for you without the need to find out on which dependency the lib is linked.

How to set JVM parameters for Junit Unit Tests?

In Maven you can configure the surefire plugin

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.9</version>
    <configuration>
        <argLine>-Xmx256M</argLine>
    </configuration>
</plugin>

If you use Maven for builds then this configuration will be carried in the source tree and applied when tests are carried out. See the Maven Surefire Plugin documentation.

Two Divs on the same row and center align both of them

both floated divs need to have a width!

set 50% of width to both and it works.

BTW, the outer div, with its margin: 0 auto will only center itself not the ones inside.

MongoDB: How to query for records where field is null or not set?

If the sent_at field is not there when its not set then:

db.emails.count({sent_at: {$exists: false}})

If its there and null, or not there at all:

db.emails.count({sent_at: null})

Refer here for querying and null

CSS text-decoration underline color

You can do it if you wrap your text into a span like:

_x000D_
_x000D_
a {_x000D_
  color: red;_x000D_
  text-decoration: underline;_x000D_
}_x000D_
span {_x000D_
  color: blue;_x000D_
  text-decoration: none;_x000D_
}
_x000D_
<a href="#">_x000D_
  <span>Text</span>_x000D_
</a>
_x000D_
_x000D_
_x000D_

Woocommerce, get current product id

Since WooCommerce 2.2 you are able to simply use the wc_get_product Method. As an argument you can pass the ID or simply leave it empty if you're already in the loop.

wc_get_product()->get_id();

OR with 2 lines

$product = wc_get_product();
$id = $product->get_id();

Obtain form input fields using jQuery?

Same solution as given by nickf, but with array input names taken into account eg

<input type="text" name="array[]" />

values = {};
$("#something :input").each(function() {
  if (this.name.search(/\[\]/) > 0) //search for [] in name
  {
    if (typeof values[this.name] != "undefined") {
      values[this.name] = values[this.name].concat([$(this).val()])
    } else {
      values[this.name] = [$(this).val()];
    }
  } else {
    values[this.name] = $(this).val();
  }
});

matrix multiplication algorithm time complexity

The naive algorithm, which is what you've got once you correct it as noted in comments, is O(n^3).

There do exist algorithms that reduce this somewhat, but you're not likely to find an O(n^2) implementation. I believe the question of the most efficient implementation is still open.

See this wikipedia article on Matrix Multiplication for more information.

python dataframe pandas drop column using int

if you really want to do it with integers (but why?), then you could build a dictionary.

col_dict = {x: col for x, col in enumerate(df.columns)}

then df = df.drop(col_dict[0], 1) will work as desired

edit: you can put it in a function that does that for you, though this way it creates the dictionary every time you call it

def drop_col_n(df, col_n_to_drop):
    col_dict = {x: col for x, col in enumerate(df.columns)}
    return df.drop(col_dict[col_n_to_drop], 1)

df = drop_col_n(df, 2)

How to convert a string to a date in sybase

102 is the rule of thumb, convert (varchar, creat_tms, 102) > '2011'

Simple parse JSON from URL on Android and display in listview

You could use AsyncTask, you'll have to customize to fit your needs, but something like the following


Async task has three primary methods:

  1. onPreExecute() - most commonly used for setting up and starting a progress dialog

  2. doInBackground() - Makes connections and receives responses from the server (Do NOT try to assign response values to GUI elements, this is a common mistake, that cannot be done in a background thread).

  3. onPostExecute() - Here we are out of the background thread, so we can do user interface manipulation with the response data, or simply assign the response to specific variable types.

First we will start the class, initialize a String to hold the results outside of the methods but inside the class, then run the onPreExecute() method setting up a simple progress dialog.

class MyAsyncTask extends AsyncTask<String, String, Void> {

    private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
    InputStream inputStream = null;
    String result = ""; 

    protected void onPreExecute() {
        progressDialog.setMessage("Downloading your data...");
        progressDialog.show();
        progressDialog.setOnCancelListener(new OnCancelListener() {
            public void onCancel(DialogInterface arg0) {
                MyAsyncTask.this.cancel(true);
            }
        });
    }

Then we need to set up the connection and how we want to handle the response:

    @Override
    protected Void doInBackground(String... params) {

        String url_select = "http://yoururlhere.com";

        ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();

        try {
            // Set up HTTP post

            // HttpClient is more then less deprecated. Need to change to URLConnection
            HttpClient httpClient = new DefaultHttpClient();

            HttpPost httpPost = new HttpPost(url_select);
            httpPost.setEntity(new UrlEncodedFormEntity(param));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();

            // Read content & Log
            inputStream = httpEntity.getContent();
        } catch (UnsupportedEncodingException e1) {
            Log.e("UnsupportedEncodingException", e1.toString());
            e1.printStackTrace();
        } catch (ClientProtocolException e2) {
            Log.e("ClientProtocolException", e2.toString());
            e2.printStackTrace();
        } catch (IllegalStateException e3) {
            Log.e("IllegalStateException", e3.toString());
            e3.printStackTrace();
        } catch (IOException e4) {
            Log.e("IOException", e4.toString());
            e4.printStackTrace();
        }
        // Convert response to string using String Builder
        try {
            BufferedReader bReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"), 8);
            StringBuilder sBuilder = new StringBuilder();

            String line = null;
            while ((line = bReader.readLine()) != null) {
                sBuilder.append(line + "\n");
            }

            inputStream.close();
            result = sBuilder.toString();

        } catch (Exception e) {
            Log.e("StringBuilding & BufferedReader", "Error converting result " + e.toString());
        }
    } // protected Void doInBackground(String... params)

Lastly, here we will parse the return, in this example it was a JSON Array and then dismiss the dialog:

    protected void onPostExecute(Void v) {
        //parse JSON data
        try {
            JSONArray jArray = new JSONArray(result);    
            for(i=0; i < jArray.length(); i++) {

                JSONObject jObject = jArray.getJSONObject(i);

                String name = jObject.getString("name");
                String tab1_text = jObject.getString("tab1_text");
                int active = jObject.getInt("active");

            } // End Loop
            this.progressDialog.dismiss();
        } catch (JSONException e) {
            Log.e("JSONException", "Error: " + e.toString());
        } // catch (JSONException e)
    } // protected void onPostExecute(Void v)
} //class MyAsyncTask extends AsyncTask<String, String, Void>

Changing text of UIButton programmatically swift

//for normal state:

btnSecurite.setTitle("TextHear", for: .normal)

How to execute a .sql script from bash

You simply need to start mysql and feed it with the content of db.sql:

mysql -u user -p < db.sql

Connect to Oracle DB using sqlplus

Different ways to connect Oracle Database from Unix user are:

[oracle@OLE1 ~]$ sqlplus scott/tiger

[oracle@OLE1 ~]$ sqlplus scott/tiger@orcl

[oracle@OLE1 ~]$ sqlplus scott/[email protected]:1521/orcl

[oracle@OLE1 ~]$ sqlplus scott/tiger@//192.168.244.128:1521/orcl

[oracle@OLE1 ~]$ sqlplus "scott/tiger@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=ole1)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=orcl)))"

Please see the explanation at link: https://stackoverflow.com/a/45064809/6332029

Thanks!

Virtual member call in a constructor

The warning is a reminder that virtual members are likely to be overridden on derived class. In that case whatever the parent class did to a virtual member will be undone or changed by overriding child class. Look at the small example blow for clarity

The parent class below attempts to set value to a virtual member on its constructor. And this will trigger Re-sharper warning, let see on code:

public class Parent
{
    public virtual object Obj{get;set;}
    public Parent()
    {
        // Re-sharper warning: this is open to change from 
        // inheriting class overriding virtual member
        this.Obj = new Object();
    }
}

The child class here overrides the parent property. If this property was not marked virtual the compiler would warn that the property hides property on the parent class and suggest that you add 'new' keyword if it is intentional.

public class Child: Parent
{
    public Child():base()
    {
        this.Obj = "Something";
    }
    public override object Obj{get;set;}
}

Finally the impact on use, the output of the example below abandons the initial value set by parent class constructor. And this is what Re-sharper attempts to to warn you, values set on the Parent class constructor are open to be overwritten by the child class constructor which is called right after the parent class constructor.

public class Program
{
    public static void Main()
    {
        var child = new Child();
        // anything that is done on parent virtual member is destroyed
        Console.WriteLine(child.Obj);
        // Output: "Something"
    }
} 

How to read large text file on windows?

I just used less on top of Cygwin to read a 3GB file, though I ended up using grep to find what I needed in it.

(less is more, but better.)

See this answer for more details on less: https://stackoverflow.com/a/1343576/1005039

How do I POST a x-www-form-urlencoded request using Fetch?

According to the spec, using encodeURIComponent won't give you a conforming query string. It states:

  1. Control names and values are escaped. Space characters are replaced by +, and then reserved characters are escaped as described in [RFC1738], section 2.2: Non-alphanumeric characters are replaced by %HH, a percent sign and two hexadecimal digits representing the ASCII code of the character. Line breaks are represented as "CR LF" pairs (i.e., %0D%0A).
  2. The control names/values are listed in the order they appear in the document. The name is separated from the value by = and name/value pairs are separated from each other by &.

The problem is, encodeURIComponent encodes spaces to be %20, not +.

The form-body should be coded using a variation of the encodeURIComponent methods shown in the other answers.

const formUrlEncode = str => {
  return str.replace(/[^\d\w]/g, char => {
    return char === " " 
      ? "+" 
      : encodeURIComponent(char);
  })
}

const data = {foo: "bar߃©??  baz", boom: "pow"};

const dataPairs = Object.keys(data).map( key => {
  const val = data[key];
  return (formUrlEncode(key) + "=" + formUrlEncode(val));
}).join("&");

// dataPairs is "foo=bar%C3%9F%C6%92%C2%A9%CB%99%E2%88%91++baz&boom=pow"

Xcode 6: Keyboard does not show up in simulator

It would be difficult to say if there's any issue with your code without checking it out, however this happens to me quite a lot in (Version 6.0 (6A216f)). I usually have to reset the simulator's Content and Settings and/or restart xCode to get it working again. Try those and see if that solves the problem.

How to change TextField's height and width?

TextField( minLines: 1, maxLines: 5, maxLengthEnforced: true)

Is there an equivalent method to C's scanf in Java?

THERE'S an even simpler answer

import java.io.BufferedReader;
import java.util.Scanner;

public class Main {

    public static void main(String[] args)
    {
        String myBeautifulScanf = new Scanner(System.in).nextLine();
        System.out.println( myBeautifulScanf );

    }
}

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

I had the same error message. In my case, Jackson consisted of multiple JAR files. Sadly, they had different versions of jackson-core and jackson-annotations which resulted in the above exception.

Maybe you don't have the jackson-annotation JAR in your classpath, at least not in the correct version. You can analyze the used library versions with the command mvn dependency:tree.

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

I had the same problem. To fix it in Jboss 7 AS, I copy the oracle driver jar file to Jboss module folder. Example: ../jboss-as-7.1.1.Final/modules/org/hibernate/main.

You also need to change "module.xml"

<module xmlns="urn:jboss:module:1.1" name="org.hibernate">
<resources>
    <resource-root path="hibernate-core-4.0.1.Final.jar"/>
    <resource-root path="hibernate-commons-annotations-4.0.1.Final.jar"/>
    <resource-root path="hibernate-entitymanager-4.0.1.Final.jar"/>
    <resource-root path="hibernate-infinispan-4.0.1.Final.jar"/>
    <resource-root path="ojdbc6.jar"/>
</resources>

<dependencies>
    <module name="asm.asm"/>
    <module name="javax.api"/>
    <module name="javax.persistence.api"/>
    <module name="javax.transaction.api"/>
    <module name="javax.validation.api"/>
    <module name="org.antlr"/>
    <module name="org.apache.commons.collections"/>
    <module name="org.dom4j"/>
    <module name="org.infinispan" optional="true"/>
    <module name="org.javassist"/>
    <module name="org.jboss.as.jpa.hibernate" slot="4" optional="true"/>
    <module name="org.jboss.logging"/>
    <module name="org.hibernate.envers" services="import" optional="true"/>
</dependencies>

How to grant all privileges to root user in MySQL 8.0

For those who've been confused by CREATE USER 'root'@'localhost' when you already have a root account on the server machine, keep in mind that your 'root'@'localhost' and 'root'@'your_remote_ip' are two different users (same user name, yet different scope) in mysql server. Hence, creating a new user with your_remote_ip postfix will actually create a new valid root user that you can use to access the mysql server from a remote machine.

For example, if you're using root to connect to your mysql server from a remote machine whose IP is 10.154.10.241 and you want to set a password for the remote root account which is 'Abcdef123!@#', here are steps you would want to follow:

  1. On your mysql server machine, do mysql -u root -p, then enter your password for root to login.

  2. Once in mysql> session, do this to create root user for the remote scope:

    mysql> CREATE USER 'root'@'10.154.10.241' IDENTIFIED BY 'Abcdef123!@#';
    
  3. After the Query OK message, do this to grant the newly created root user all privileges:

    mysql> GRANT ALL ON *.* TO 'root'@'10.154.10.241';
    
  4. And then:

    FLUSH PRIVILEGES;
    
  5. Restart the mysqld service:

    sudo service mysqld restart
    
  6. Confirm that the server has successfully restarted:

    sudo service mysqld status
    

If the steps above were executed without any error, you can now access to the mysql server from a remote machine using root.

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

Instagram: Share photo from webpage

The short answer is: No. The only way to post images is through the mobile app.

From the Instagram API documentation: http://instagram.com/developer/endpoints/media/

At this time, uploading via the API is not possible. We made a conscious choice not to add this for the following reasons:

  • Instagram is about your life on the go – we hope to encourage photos from within the app. However, in the future we may give whitelist access to individual apps on a case by case basis.
  • We want to fight spam & low quality photos. Once we allow uploading from other sources, it's harder to control what comes into the Instagram ecosystem.

All this being said, we're working on ways to ensure users have a consistent and high-quality experience on our platform.

How do I concatenate two strings in C?

You should use strcat, or better, strncat. Google it (the keyword is "concatenating").

Set TextView text from html-formatted string resource in XML

Just in case anybody finds this, there's a nicer alternative that's not documented (I tripped over it after searching for hours, and finally found it in the bug list for the Android SDK itself). You CAN include raw HTML in strings.xml, as long as you wrap it in

<![CDATA[ ...raw html... ]]>

Example:

<string name="nice_html">
<![CDATA[
<p>This is a html-formatted string with <b>bold</b> and <i>italic</i> text</p>
<p>This is another paragraph of the same string.</p>
]]>
</string>

Then, in your code:

TextView foo = (TextView)findViewById(R.id.foo);
foo.setText(Html.fromHtml(getString(R.string.nice_html)));

IMHO, this is several orders of magnitude nicer to work with :-)

What does "atomic" mean in programming?

Just found a post Atomic vs. Non-Atomic Operations to be very helpful to me.

"An operation acting on shared memory is atomic if it completes in a single step relative to other threads.

When an atomic store is performed on a shared memory, no other thread can observe the modification half-complete.

When an atomic load is performed on a shared variable, it reads the entire value as it appeared at a single moment in time."

How to create RecyclerView with multiple view type?

Here is a complete sample to show RecyclerView with 2 types, the view type decide by the object

Class model

open class RecyclerViewItem
class SectionItem(val title: String) : RecyclerViewItem()
class ContentItem(val name: String, val number: Int) : RecyclerViewItem()

Adapter code

const val VIEW_TYPE_SECTION = 1
const val VIEW_TYPE_ITEM = 2

class UserAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

    var data = listOf<RecyclerViewItem>()

    override fun getItemViewType(position: Int): Int {
        if (data[position] is SectionItem) {
            return VIEW_TYPE_SECTION
        }
        return VIEW_TYPE_ITEM
    }

    override fun getItemCount(): Int {
        return data.size
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        if (viewType == VIEW_TYPE_SECTION) {
            return SectionViewHolder(
                LayoutInflater.from(parent.context).inflate(R.layout.item_user_section, parent, false)
            )
        }
        return ContentViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_user_content, parent, false)
        )
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        val item = data[position]
        if (holder is SectionViewHolder && item is SectionItem) {
            holder.bind(item)
        }
        if (holder is ContentViewHolder && item is ContentItem) {
            holder.bind(item)
        }
    }

    internal inner class SectionViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(item: SectionItem) {
            itemView.text_section.text = item.title
        }
    }

    internal inner class ContentViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        fun bind(item: ContentItem) {
            itemView.text_name.text = item.name
            itemView.text_number.text = item.number.toString()
        }
    }
}

item_user_section.xml

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/text_section"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#eee"
    android:padding="16dp" />

item_user_content.xml

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

    <TextView
        android:id="@+id/text_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        tools:text="Name" />

    <TextView
        android:id="@+id/text_number"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

Example using

val dataSet = arrayListOf<RecyclerViewItem>(
    SectionItem("A1"),
    ContentItem("11", 11),
    ContentItem("12", 12),
    ContentItem("13", 13),

    SectionItem("A2"),
    ContentItem("21", 21),
    ContentItem("22", 22),

    SectionItem("A3"),
    ContentItem("31", 31),
    ContentItem("32", 32),
    ContentItem("33", 33),
    ContentItem("33", 34),
)

recyclerAdapter.data = dataSet
recyclerAdapter.notifyDataSetChanged()

Sending HTTP POST with System.Net.WebClient

WebClient doesn't have a direct support for form data, but you can send a HTTP post by using the UploadString method:

Using client as new WebClient
    result = client.UploadString(someurl, "param1=somevalue&param2=othervalue")
End Using

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

I got this error as I used relative imports incorrectly. In the OP example, test_app.py should import functions using e.g.

from repo.app import *

However liberally __init__.py files are scattered around the file structure, this does not work and creates the kind of ImportError seen unless the files and test files are in the same directory.

from app import *

Here's an example of what I had to do with one of my projects:

Here’s my project structure:

microbit/
microbit/activity_indicator/activity_indicator.py
microbit/tests/test_activity_indicator.py

To be able to access activity_indicator.py from test_activity_indicator.py I needed to:

  • start test_activity_indicatory.py with the correct relative import:
    from microbit.activity_indicator.activity_indicator import *
  • put __init__.py files throughout the project structure:
    microbit/
    microbit/__init__.py
    microbit/activity_indicator/__init__.py
    microbit/activity_indicator/activity_indicator.py
    microbit/tests/__init__.py
    microbit/tests/test_activity_indicator.py

How do I send email with JavaScript without opening the mail client?

You can't do it with client side script only... you could make an AJAX call to some server side code that will send an email...

How to get item's position in a list?

Hmmm. There was an answer with a list comprehension here, but it's disappeared.

Here:

 [i for i,x in enumerate(testlist) if x == 1]

Example:

>>> testlist
[1, 2, 3, 5, 3, 1, 2, 1, 6]
>>> [i for i,x in enumerate(testlist) if x == 1]
[0, 5, 7]

Update:

Okay, you want a generator expression, we'll have a generator expression. Here's the list comprehension again, in a for loop:

>>> for i in [i for i,x in enumerate(testlist) if x == 1]:
...     print i
... 
0
5
7

Now we'll construct a generator...

>>> (i for i,x in enumerate(testlist) if x == 1)
<generator object at 0x6b508>
>>> for i in (i for i,x in enumerate(testlist) if x == 1):
...     print i
... 
0
5
7

and niftily enough, we can assign that to a variable, and use it from there...

>>> gen = (i for i,x in enumerate(testlist) if x == 1)
>>> for i in gen: print i
... 
0
5
7

And to think I used to write FORTRAN.

Update a local branch with the changes from a tracked remote branch

You don't use the : syntax - pull always modifies the currently checked-out branch. Thus:

git pull origin my_remote_branch

while you have my_local_branch checked out will do what you want.

Since you already have the tracking branch set, you don't even need to specify - you could just do...

git pull

while you have my_local_branch checked out, and it will update from the tracked branch.

How can I mock an ES6 module import using Jest?

The question is already answered, but you can resolve it like this:

File dependency.js

const doSomething = (x) => x
export default doSomething;

File myModule.js

import doSomething from "./dependency";

export default (x) => doSomething(x * 2);

File myModule.spec.js

jest.mock('../dependency');
import doSomething from "../dependency";
import myModule from "../myModule";

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    doSomething.mockImplementation((x) => x * 10)

    myModule(2);

    expect(doSomething).toHaveBeenCalledWith(4);
    console.log(myModule(2)) // 40
  });
});

Bootstrap Collapse not Collapsing

You need jQuery see bootstrap's basic template

How to place Text and an Image next to each other in HTML?

You want to use css float for this, you can put it directly in your code.

<body>
<img src="website_art.png" height= "75" width="235" style="float:left;"/>
<h3 style="float:right;">The Art of Gaming</h3>
</body>

But I would really suggest learning the basics of css and splitting all your styling out to a separate style sheet, and use classes. It will help you in the future. A good place to start is w3schools or, perhaps later down the path, Mozzila Dev. Network (MDN).

HTML:

<body>
  <img src="website_art.png" class="myImage"/>
  <h3 class="heading">The Art of Gaming</h3>
</body>

CSS:

.myImage {
  float: left;
  height: 75px;
  width: 235px;
  font-family: Veranda;
}
.heading {
  float:right;
}

How do I call an Angular 2 pipe with multiple arguments?

You're missing the actual pipe.

{{ myData | date:'fullDate' }}

Multiple parameters can be separated by a colon (:).

{{ myData | myPipe:'arg1':'arg2':'arg3' }}

Also you can chain pipes, like so:

{{ myData | date:'fullDate' | myPipe:'arg1':'arg2':'arg3' }}

How can I render a list select box (dropdown) with bootstrap?

Another way without using the .form-control is this:

  $(".dropdown-menu li a").click(function(){
        $(this).parents(".btn-group").find('.btn').html($(this).text() + ' <span class="caret"></span>');
        $(this).parents(".btn-group").find('.btn').val($(this).data('value'));
      });

_x000D_
_x000D_
$(".dropdown-menu li a").click(function(){_x000D_
  $(this).parents(".btn-group").find('.btn').html($(this).text() + ' <span class="caret"></span>');_x000D_
  $(this).parents(".btn-group").find('.btn').val($(this).data('value'));_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>_x000D_
_x000D_
_x000D_
<div class="btn-group">_x000D_
  <button  type="button" class="btn btn-info dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">_x000D_
                  Test <span class="caret"> </span>_x000D_
  </button>_x000D_
  <ul class="dropdown-menu">_x000D_
    <li><a href='#'>test 1</a></li>_x000D_
    <li><a href='#'>test 2</a></li>_x000D_
    <li><a href='#'>test 3</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is there an alternative sleep function in C to milliseconds?

You can use this cross-platform function:

#ifdef WIN32
#include <windows.h>
#elif _POSIX_C_SOURCE >= 199309L
#include <time.h>   // for nanosleep
#else
#include <unistd.h> // for usleep
#endif

void sleep_ms(int milliseconds){ // cross-platform sleep function
#ifdef WIN32
    Sleep(milliseconds);
#elif _POSIX_C_SOURCE >= 199309L
    struct timespec ts;
    ts.tv_sec = milliseconds / 1000;
    ts.tv_nsec = (milliseconds % 1000) * 1000000;
    nanosleep(&ts, NULL);
#else
    if (milliseconds >= 1000)
      sleep(milliseconds / 1000);
    usleep((milliseconds % 1000) * 1000);
#endif
}

how to set "camera position" for 3d plots using python/matplotlib?

Try the following code to find the optimal camera position

Move the viewing angle of the plot using the keyboard keys as mentioned in the if clause

Use print to get the camera positions

def move_view(event):
    ax.autoscale(enable=False, axis='both') 
    koef = 8
    zkoef = (ax.get_zbound()[0] - ax.get_zbound()[1]) / koef
    xkoef = (ax.get_xbound()[0] - ax.get_xbound()[1]) / koef
    ykoef = (ax.get_ybound()[0] - ax.get_ybound()[1]) / koef
    ## Map an motion to keyboard shortcuts
    if event.key == "ctrl+down":
        ax.set_ybound(ax.get_ybound()[0] + xkoef, ax.get_ybound()[1] + xkoef)
    if event.key == "ctrl+up":
        ax.set_ybound(ax.get_ybound()[0] - xkoef, ax.get_ybound()[1] - xkoef)
    if event.key == "ctrl+right":
        ax.set_xbound(ax.get_xbound()[0] + ykoef, ax.get_xbound()[1] + ykoef)
    if event.key == "ctrl+left":
        ax.set_xbound(ax.get_xbound()[0] - ykoef, ax.get_xbound()[1] - ykoef)
    if event.key == "down":
        ax.set_zbound(ax.get_zbound()[0] - zkoef, ax.get_zbound()[1] - zkoef)
    if event.key == "up":
        ax.set_zbound(ax.get_zbound()[0] + zkoef, ax.get_zbound()[1] + zkoef)
    # zoom option
    if event.key == "alt+up":
        ax.set_xbound(ax.get_xbound()[0]*0.90, ax.get_xbound()[1]*0.90)
        ax.set_ybound(ax.get_ybound()[0]*0.90, ax.get_ybound()[1]*0.90)
        ax.set_zbound(ax.get_zbound()[0]*0.90, ax.get_zbound()[1]*0.90)
    if event.key == "alt+down":
        ax.set_xbound(ax.get_xbound()[0]*1.10, ax.get_xbound()[1]*1.10)
        ax.set_ybound(ax.get_ybound()[0]*1.10, ax.get_ybound()[1]*1.10)
        ax.set_zbound(ax.get_zbound()[0]*1.10, ax.get_zbound()[1]*1.10)
    
    # Rotational movement
    elev=ax.elev
    azim=ax.azim
    if event.key == "shift+up":
        elev+=10
    if event.key == "shift+down":
        elev-=10
    if event.key == "shift+right":
        azim+=10
    if event.key == "shift+left":
        azim-=10

    ax.view_init(elev= elev, azim = azim)

    # print which ever variable you want 

    ax.figure.canvas.draw()

fig.canvas.mpl_connect("key_press_event", move_view)

plt.show()

Call JavaScript function from C#

.aspx file in header section

<head>
    <script type="text/javascript">
        <%=YourScript %>
        function functionname1(arg1,arg2){content}
    </script>
</head>

.cs file

public string YourScript = "";
public string functionname(arg)
{
    if (condition)
    {
        YourScript = "functionname1(arg1,arg2);";
    }
}

Assert that a WebElement is not present using Selenium WebDriver with java

Not Sure which version of selenium you are referring to, however some commands in selenium * can now do this: http://release.seleniumhq.org/selenium-core/0.8.0/reference.html

  • assertNotSomethingSelected
  • assertTextNotPresent

Etc..

Saving lists to txt file

Assuming your Generic List is of type String:

TextWriter tw = new StreamWriter("SavedList.txt");

foreach (String s in Lists.verbList)
   tw.WriteLine(s);

tw.Close();

Alternatively, with the using keyword:

using(TextWriter tw = new StreamWriter("SavedList.txt"))
{
   foreach (String s in Lists.verbList)
      tw.WriteLine(s);
}

Parse RSS with jQuery

jFeed is somewhat obsolete, working only with older versions of jQuery. It has been two years since it was updated.

zRSSFeed is perhaps a little less flexible, but it is easy to use, and it works with the current version of jQuery (currently 1.4). http://www.zazar.net/developers/zrssfeed/

Here's a quick example from the zRSSFeed docs:

<div id="test"><div>

<script type="text/javascript">
$(document).ready(function () {
  $('#test').rssfeed('http://feeds.reuters.com/reuters/oddlyEnoughNews', {
    limit: 5
  });
});
</script>

What is the documents directory (NSDocumentDirectory)?

Like others mentioned, your app runs in a sandboxed environment and you can use the documents directory to store images or other assets your app may use, eg. downloading offline-d files as user prefers - File System Basics - Apple Documentation - Which directory to use, for storing application specific files

Updated to swift 5, you can use one of these functions, as per requirement -

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}

func getCacheDirectory() -> URL {
        let paths = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)
        return paths[0]
    }

func getApplicationSupportDirectory() -> URL {
        let paths = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)
        return paths[0]
    }

Usage:

let urlPath = "https://jumpcloud.com/wp-content/uploads/2017/06/SSH-Keys.png" //Or string path to some URL of valid image, for eg.

if let url = URL(string: urlPath){
    let destination = getDocumentsDirectory().appendingPathComponent(url.lastPathComponent)
    do {
        let data = try Data(contentsOf: url) //Synchronous call, just as an example
        try data.write(to: destination)
    } catch _ {
        //Do something to handle the error
    }
}

How do I run a batch file from my Java Application?

To run batch files using java if that's you're talking about...

String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);`

This should do it.

Char Comparison in C

In C the char type has a numeric value so the > operator will work just fine for example

#include <stdio.h>
main() {

    char a='z';

    char b='h';

    if ( a > b ) {
        printf("%c greater than %c\n",a,b);
    }
}

I am not able launch JNLP applications using "Java Web Start"?

Same solution worked as suggested by hpereira The issue was due to JRE version was 32 bit and not 64 Bit Check with java -version to see if your Java is 64 bit

C:\>java -version
java version "1.8.0_192"
Java(TM) SE Runtime Environment (build 1.8.0_192-b12)
Java HotSpot(TM) **64-Bit Server** VM (build 25.192-b12, mixed mode)

Linux command line howto accept pairing for bluetooth device without pin

~ $ hciconfig noauth

It worked for me in "Linux mx 4.19"

The exact steps are:

1) open a terminal - run: "hciconfig noauth"
2) use the blueman-manager gui to pair the device (in my case it was a keyboard)
3) from the blueman-manager choose "connect to HID"

step(3) is normally asking for a password - the "hciconfig noauth" makes step(3) passwordless

How to print React component on click of a button?

There is kind of two solutions on the client. One is with frames like you posted. You can use an iframe though:

var content = document.getElementById("divcontents");
var pri = document.getElementById("ifmcontentstoprint").contentWindow;
pri.document.open();
pri.document.write(content.innerHTML);
pri.document.close();
pri.focus();
pri.print();

This expects this html to exist

<iframe id="ifmcontentstoprint" style="height: 0px; width: 0px; position: absolute"></iframe>

The other solution is to use the media selector and on the media="print" styles hide everything you don't want to print.

<style type="text/css" media="print">
   .no-print { display: none; }
</style>

Last way requires some work on the server. You can send all the HTML+CSS to the server and use one of many components to generate a printable document like PDF. I've tried setups doing this with PhantomJs.

What is simplest way to read a file into String?

Using Apache Commons IO.

import org.apache.commons.io.FileUtils;

//...

String contents = FileUtils.readFileToString(new File("/path/to/the/file"), "UTF-8")

You can see de javadoc for the method for details.

How to check size of a file using Bash?

Okay, if you're on a Mac, do this: stat -f %z "/Users/Example/config.log" That's it!

disable textbox using jquery?

Not really necessary, but a small improvement to o.k.w.'s code that would make the function call faster (since you're moving the conditional outside the function call).

$("#radiobutt input[type=radio]").each(function(i) {
    if (i == 2) { //3rd radiobutton
        $(this).click(function () {
            $("#textbox1").attr("disabled", "disabled");
            $("#checkbox1").attr("disabled", "disabled");
        });
    } else {
        $(this).click(function () {
            $("#textbox1").removeAttr("disabled");
            $("#checkbox1").removeAttr("disabled");
        });
    }
});

How to get integer values from a string in Python?

Here's your one-liner, without using any regular expressions, which can get expensive at times:

>>> ''.join(filter(str.isdigit, "1234GAgade5312djdl0"))

returns:

'123453120'

Windows 7 - Add Path

I founded the problem: Just insert the folder without the executable file.
so Instead of:

C:\Program Files (x86)\SumatraPDF\SumatraPDF.exe

you have to write this:

C:\Program Files (x86)\SumatraPDF\

How does the 'binding' attribute work in JSF? When and how should it be used?

How does it work?

When a JSF view (Facelets/JSP file) get built/restored, a JSF component tree will be produced. At that moment, the view build time, all binding attributes are evaluated (along with id attribtues and taghandlers like JSTL). When the JSF component needs to be created before being added to the component tree, JSF will check if the binding attribute returns a precreated component (i.e. non-null) and if so, then use it. If it's not precreated, then JSF will autocreate the component "the usual way" and invoke the setter behind binding attribute with the autocreated component instance as argument.

In effects, it binds a reference of the component instance in the component tree to a scoped variable. This information is in no way visible in the generated HTML representation of the component itself. This information is in no means relevant to the generated HTML output anyway. When the form is submitted and the view is restored, the JSF component tree is just rebuilt from scratch and all binding attributes will just be re-evaluated like described in above paragraph. After the component tree is recreated, JSF will restore the JSF view state into the component tree.

Component instances are request scoped!

Important to know and understand is that the concrete component instances are effectively request scoped. They're newly created on every request and their properties are filled with values from JSF view state during restore view phase. So, if you bind the component to a property of a backing bean, then the backing bean should absolutely not be in a broader scope than the request scope. See also JSF 2.0 specitication chapter 3.1.5:

3.1.5 Component Bindings

...

Component bindings are often used in conjunction with JavaBeans that are dynamically instantiated via the Managed Bean Creation facility (see Section 5.8.1 “VariableResolver and the Default VariableResolver”). It is strongly recommend that application developers place managed beans that are pointed at by component binding expressions in “request” scope. This is because placing it in session or application scope would require thread-safety, since UIComponent instances depends on running inside of a single thread. There are also potentially negative impacts on memory management when placing a component binding in “session” scope.

Otherwise, component instances are shared among multiple requests, possibly resulting in "duplicate component ID" errors and "weird" behaviors because validators, converters and listeners declared in the view are re-attached to the existing component instance from previous request(s). The symptoms are clear: they are executed multiple times, one time more with each request within the same scope as the component is been bound to.

And, under heavy load (i.e. when multiple different HTTP requests (threads) access and manipulate the very same component instance at the same time), you may face sooner or later an application crash with e.g. Stuck thread at UIComponent.popComponentFromEL, or Java Threads at 100% CPU utilization using richfaces UIDataAdaptorBase and its internal HashMap, or even some "strange" IndexOutOfBoundsException or ConcurrentModificationException coming straight from JSF implementation source code while JSF is busy saving or restoring the view state (i.e. the stack trace indicates saveState() or restoreState() methods and like).

Using binding on a bean property is bad practice

Regardless, using binding this way, binding a whole component instance to a bean property, even on a request scoped bean, is in JSF 2.x a rather rare use case and generally not the best practice. It indicates a design smell. You normally declare components in the view side and bind their runtime attributes like value, and perhaps others like styleClass, disabled, rendered, etc, to normal bean properties. Then, you just manipulate exactly that bean property you want instead of grabbing the whole component and calling the setter method associated with the attribute.

In cases when a component needs to be "dynamically built" based on a static model, better is to use view build time tags like JSTL, if necessary in a tag file, instead of createComponent(), new SomeComponent(), getChildren().add() and what not. See also How to refactor snippet of old JSP to some JSF equivalent?

Or, if a component needs to be "dynamically rendered" based on a dynamic model, then just use an iterator component (<ui:repeat>, <h:dataTable>, etc). See also How to dynamically add JSF components.

Composite components is a completely different story. It's completely legit to bind components inside a <cc:implementation> to the backing component (i.e. the component identified by <cc:interface componentType>. See also a.o. Split java.util.Date over two h:inputText fields representing hour and minute with f:convertDateTime and How to implement a dynamic list with a JSF 2.0 Composite Component?

Only use binding in local scope

However, sometimes you'd like to know about the state of a different component from inside a particular component, more than often in use cases related to action/value dependent validation. For that, the binding attribute can be used, but not in combination with a bean property. You can just specify an in the local EL scope unique variable name in the binding attribute like so binding="#{foo}" and the component is during render response elsewhere in the same view directly as UIComponent reference available by #{foo}. Here are several related questions where such a solution is been used in the answer:

See also:

Dynamic creation of table with DOM

when you say 'appendchild' you actually move your child from one parent to another. you have to create a node for each cell.

Location of the android sdk has not been setup in the preferences in mac os?

Simply create this folder:

C:\Users\xxxxx\android-sdk\tools

and then from Window -> Preferences -> Android, put this path:

 C:\Users\xxxxx\android-sdk

How to write a:hover in inline CSS?

There is no way to do this. Your options are to use a JavaScript or a CSS block.

Maybe there is some JavaScript library that will convert a proprietary style attribute to a style block. But then the code will not be standard-compliant.

fs.writeFile in a promise, asynchronous-synchronous stuff

What worked for me was fs.promises.

Example One:

const fs = require("fs")

fs.promises
  .writeFile(__dirname + '/test.json', "data", { encoding: 'utf8' })
  .then(() => {
    // Do whatever you want to do.
    console.log('Done');
  });

Example Two. Using Async-Await:

const fs = require("fs")

async function writeToFile() {
  await fs.promises.writeFile(__dirname + '/test-22.json', "data", {
    encoding: 'utf8'
  });

  console.log("done")
}

writeToFile()

Load an image from a url into a PictureBox

If you are trying to load the image at your form_load, it's a better idea to use the code

pictureBox1.LoadAsync(@"http://google.com/test.png");

not only loading from web but also no lag in your form loading.

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

The URI "file:///android_asset/" points to YourProject/app/src/main/assets/.

Note: android_asset/ uses the singular (asset) and src/main/assets uses the plural (assets).

Suppose you have a file YourProject/app/src/main/assets/web_thing.html that you would like to display in a WebView. You can refer to it like this:

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

The snippet above could be located in your Activity class, possibly in the onCreate method.

Here is a guide to the overall directory structure of an android project, that helped me figure out this answer.

jquery input select all on focus

This version works on ios and also fixes standard drag-to-select on windows chrome

var srcEvent = null;

$("input[type=text],input[type=number]")

    .mousedown(function (event) {
        srcEvent = event;
    })

    .mouseup(function (event) {
        var delta = Math.abs(event.clientX - srcEvent.clientX) 
                  + Math.abs(event.clientY - srcEvent.clientY);

        var threshold = 2;
        if (delta <= threshold) {
                   try {
                        // ios likes this but windows-chrome does not on number fields
                        $(this)[0].selectionStart = 0;
                        $(this)[0].selectionEnd = 1000;
                    } catch (e) {
                        // windows-chrome likes this
                        $(this).select();
                    }
        }
    });

http://jsfiddle.net/Zx2sc/2/

Can I escape html special chars in javascript?

DOM Elements support converting text to HTML by assigning to innerText. innerText is not a function but assigning to it works as if the text were escaped.

document.querySelectorAll('#id')[0].innerText = 'unsafe " String >><>';

Could not resolve Spring property placeholder

Your property file location is classpath:idm.properties

This is rather unusual, it means that idm.properties must be located either at the top level of WEB-INF/classes or at the top-level of one of the jars inside WEB-INF/lib. Usually it's good practice to either use a dedicated folder for properties or keep them close to the context files that use them.

So my suggestion is this: Is your properties file perhaps next to your context file? If so, it's not on the classpath (see this question: Is WEB-INF in the CLASSPATH?).

The classpath: prefix maps to a ClassPathResource, but you probably need a ServletContextResource, and you'll get that from a WebApplicationContext using the syntax without prefix:

<context:property-placeholder location="idm.properties" />

Reference:

Modifying a file inside a jar

Java jar files are the same format as zip files - so if you have a zip file utility that would let you modify an archive, you have your foot in the door. Second problem is, if you want to recompile a class or something, you probably will just have to re-build the jar; but a text file or something (xml, for instance) should be easily enough modified.

Java java.sql.SQLException: Invalid column index on preparing statement

In date '?', the '?' is a literal string with value ?, not a parameter placeholder, so your query does not have any parameters. The date is a shorthand cast from (literal) string to date. You need to replace date '?' with ? to actually have a parameter.

Also if you know it is a date, then use setDate(..) and not setString(..) to set the parameter.

UITableViewCell Selected Background Color on Multiple Selection

Swift 4.2

For multiple selections you need to set the UITableView property allowsMultipleSelection to true.

myTableView.allowsMultipleSelection = true

In case you subclassed the UITableViewCell, you override setSelected(_ selected: Bool, animated: Bool) method in your custom cell class.

 override func setSelected(_ selected: Bool, animated: Bool) {
     super.setSelected(selected, animated: animated)

     if selected {
         contentView.backgroundColor = UIColor.green
     } else {
         contentView.backgroundColor = UIColor.blue
     }
 }

Quick way to list all files in Amazon S3 bucket?

The below command will get all the file names from your AWS S3 bucket and write into text file in your current directory:

aws s3 ls s3://Bucketdirectory/Subdirectory/ | cat >> FileNames.txt

Parsing JSON objects for HTML table

This post is very much helpful to all of you

First Parse the json data by using jquery eval parser and then iterarate through jquery each function below is the code sniplet:

                var obj = eval("(" + data.d + ")");

                alert(obj);
                $.each(obj, function (index,Object) {

                    var Id = Object.Id;
                    var AptYear = Object.AptYear;
                    $("#ddlyear").append('<option value=' + Id + '>' + AptYear + '</option>').toString();
                });

How can I resolve the error "The security token included in the request is invalid" when running aws iam upload-server-certificate?

I had to specify the AWS profile to use --profile default explicitly to get rid of this error while running AWS CLI commands. I could not understand though that why it did not pick up this profile automatically as there was only [dafault] profile present in my aws config and credentials file.

I hope this helps.

Cheers, Kunal

Android offline documentation and sample codes

If you install the SDK, the offline documentation can be found in $ANDROID_SDK/docs/.

One line if-condition-assignment

I don't think this is possible in Python, since what you're actually trying to do probably gets expanded to something like this:

num1 = 20 if someBoolValue else num1

If you exclude else num1, you'll receive a syntax error since I'm quite sure that the assignment must actually return something.

As others have already mentioned, you could do this, but it's bad because you'll probably just end up confusing yourself when reading that piece of code the next time:

if someBoolValue: num1=20

I'm not a big fan of the num1 = someBoolValue and 20 or num1 for the exact same reason. I have to actually think twice on what that line is doing.

The best way to actually achieve what you want to do is the original version:

if someBoolValue:
    num1 = 20

The reason that's the best verison is because it's very obvious what you want to do, and you won't confuse yourself, or whoever else is going to come in contact with that code later.

Also, as a side note, num1 = 20 if someBoolValue is valid Ruby code, because Ruby works a bit differently.

How to allow users to check for the latest app version from inside the app?

There is no API for this, and you can't auto install it, you can just redirect them to it's Market page so they can upgrade. You can have your latest version in a file on a Web server, and have the app check it. Here's one implementation of this:

http://code.google.com/p/openintents/source/browse/#svn%2Ftrunk%2FUpdateCheckerApp

Sending data through POST request from a node.js server to a node.js server

Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?) as the request body.

This requires Content-Type and Content-Length headers, so the receiving server knows how to interpret the incoming data. (*)

var querystring = require('querystring');
var http = require('http');

var data = querystring.stringify({
      username: yourUsernameValue,
      password: yourPasswordValue
    });

var options = {
    host: 'my.url',
    port: 80,
    path: '/login',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': Buffer.byteLength(data)
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
req.end();

(*) Sending data requires the Content-Type header to be set correctly, i.e. application/x-www-form-urlencoded for the traditional format that a standard HTML form would use.

It's easy to send JSON (application/json) in exactly the same manner; just JSON.stringify() the data beforehand.

URL-encoded data supports one level of structure (i.e. key and value). JSON is useful when it comes to exchanging data that has a nested structure.

The bottom line is: The server must be able to interpret the content type in question. It could be text/plain or anything else; there is no need to convert data if the receiving server understands it as it is.

Add a charset parameter (e.g. application/json; charset=Windows-1252) if your data is in an unusual character set, i.e. not UTF-8. This can be necessary if you read it from a file, for example.

How can I solve a connection pool problem between ASP.NET and SQL Server?

I have encountered this problem too, when using some 3rd party data layer in one of my .NET applications. The problem was that the layer did not close the connections properly.

We threw out the layer and created one ourselves, which always closes and disposes the connections. Since then we don't get the error anymore.

Can you write virtual functions / methods in Java?

From wikipedia

In Java, all non-static methods are by default "virtual functions." Only methods marked with the keyword final, which cannot be overridden, along with private methods, which are not inherited, are non-virtual.

how to convert binary string to decimal?

parseInt() with radix is a best solution (as was told by many):

But if you want to implement it without parseInt, here is an implementation:

  function bin2dec(num){
    return num.split('').reverse().reduce(function(x, y, i){
      return (y === '1') ? x + Math.pow(2, i) : x;
    }, 0);
  }

Go build: "Cannot find package" (even though GOPATH is set)

TL;DR: Follow Go conventions! (lesson learned the hard way), check for old go versions and remove them. Install latest.

For me the solution was different. I worked on a shared Linux server and after verifying my GOPATH and other environment variables several times it still didn't work. I encountered several errors including 'Cannot find package' and 'unrecognized import path'. After trying to reinstall with this solution by the instructions on golang.org (including the uninstall part) still encountered problems.

Took me some time to realize that there's still an old version that hasn't been uninstalled (running go version then which go again... DAHH) which got me to this question and finally solved.

Google map V3 Set Center to specific Marker

may be this will help:

map.setCenter(window.markersArray[2].getPosition());

all the markers info are in markersArray array and it is global. So you can access it from anywhere using window.variablename. Each marker has a unique id and you can put that id in the key of array. so you create marker like this:

window.markersArray[2] = new google.maps.Marker({
            position: new google.maps.LatLng(23.81927, 90.362349),          
            map: map,
            title: 'your info '  
        });

Hope this will help.

convert nan value to zero

You could use np.where to find where you have NaN:

import numpy as np

a = np.array([[   0,   43,   67,    0,   38],
              [ 100,   86,   96,  100,   94],
              [  76,   79,   83,   89,   56],
              [  88,   np.nan,   67,   89,   81],
              [  94,   79,   67,   89,   69],
              [  88,   79,   58,   72,   63],
              [  76,   79,   71,   67,   56],
              [  71,   71,   np.nan,   56,  100]])

b = np.where(np.isnan(a), 0, a)

In [20]: b
Out[20]: 
array([[   0.,   43.,   67.,    0.,   38.],
       [ 100.,   86.,   96.,  100.,   94.],
       [  76.,   79.,   83.,   89.,   56.],
       [  88.,    0.,   67.,   89.,   81.],
       [  94.,   79.,   67.,   89.,   69.],
       [  88.,   79.,   58.,   72.,   63.],
       [  76.,   79.,   71.,   67.,   56.],
       [  71.,   71.,    0.,   56.,  100.]])

Adding Http Headers to HttpClient

To set custom headers ON A REQUEST, build a request with the custom header before passing it to httpclient to send to http server. eg:

HttpClient client = HttpClients.custom().build();
HttpUriRequest request = RequestBuilder.get()
  .setUri(someURL)
  .setHeader(HttpHeaders.CONTENT_TYPE, "application/json")
  .build();
client.execute(request);

Default header is SET ON HTTPCLIENT to send on every request to the server.

MySQL error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near

Delimiters, delimiters...

You really need them when there are multiple statements in your procedure. (in other words, do you have a ; in your code and then more statements/commands? Then, you need to use delimiters).

For such a simpler rpocedure as yours though, you could just do:

CREATE PROCEDURE ProG()
  SELECT * FROM `hs_hr_employee_leave_quota`;

How can I use jQuery to move a div across the screen

Just a quick little function I drummed up that moves DIVs from their current spot to a target spot, one pixel step at a time. I tried to comment as best as I could, but the part you're interested in, is in example 1 and example 2, right after [$(function() { // jquery document.ready]. Put your bounds checking code there, and then exit the interval if conditions are met. Requires jQuery.

First the Demo: http://jsfiddle.net/pnYWY/

First the DIVs...

<style>
  .moveDiv {
    position:absolute;
    left:20px;
    top:20px;
    width:10px;
    height:10px;
    background-color:#ccc;
  }

  .moveDivB {
    position:absolute;
    left:20px;
    top:20px;
    width:10px;
    height:10px;
    background-color:#ccc;
  }
</style>


<div class="moveDiv"></div>
<div class="moveDivB"></div>

example 1) Start

// first animation (fire right away)
var myVar = setInterval(function(){
    $(function() { // jquery document.ready

        // returns true if it just took a step
        // returns false if the div has arrived
        if( !move_div_step(55,25,'.moveDiv') )
        {
            // arrived...
            console.log('arrived'); 
            clearInterval(myVar);
        }

    });
},50); // set speed here in ms for your delay

example 2) Delayed Start

// pause and then fire an animation..
setTimeout(function(){
    var myVarB = setInterval(function(){
        $(function() { // jquery document.ready
            // returns true if it just took a step
            // returns false if the div has arrived
            if( !move_div_step(25,55,'.moveDivB') )
            {
                // arrived...
                console.log('arrived'); 
                clearInterval(myVarB);
            }
        });
    },50); // set speed here in ms for your delay
},5000);// set speed here for delay before firing

Now the Function:

function move_div_step(xx,yy,target) // takes one pixel step toward target
{
    // using a line algorithm to move a div one step toward a given coordinate.
    var div_target = $(target);

    // get current x and current y
    var x = div_target.position().left; // offset is relative to document; position() is relative to parent;
    var y = div_target.position().top;

    // if x and y are = to xx and yy (destination), then div has arrived at it's destination.
    if(x == xx && y == yy)
        return false;

    // find the distances travelled
    var dx = xx - x;
    var dy = yy - y;

    // preventing time travel
    if(dx < 0)          dx *= -1;
    if(dy < 0)          dy *= -1;

    // determine speed of pixel travel...
    var sx=1, sy=1;

    if(dx > dy)         sy = dy/dx;
    else if(dy > dx)    sx = dx/dy;

    // find our one...
    if(sx == sy) // both are one..
    {
        if(x <= xx) // are we going forwards?
        {
            x++; y++;
        }
        else  // .. we are going backwards.
        {
            x--; y--;
        }       
    }
    else if(sx > sy) // x is the 1
    {
        if(x <= xx) // are we going forwards..?
            x++;
        else  // or backwards?
            x--;

        y += sy;
    }
    else if(sy > sx) // y is the 1 (eg: for every 1 pixel step in the y dir, we take 0.xxx step in the x
    {
        if(y <= yy) // going forwards?
            y++;
        else  // .. or backwards?
            y--;

        x += sx;
    }

    // move the div
    div_target.css("left", x);
    div_target.css("top",  y);

    return true;
}  // END :: function move_div_step(xx,yy,target)

Node.js EACCES error when listening on most ports

#Windows

Another one reason - maybe your port has been excluded by some reasons.

So, try open CMD under admin rights and run :

  1. net stop winnat
  2. net start winnat

In my case it was enough.

Solution found here : https://medium.com/@Bartleby/ports-are-not-available-listen-tcp-0-0-0-0-3000-165892441b9d

How do I express "if value is not empty" in the VBA language?

Try this:

If Len(vValue & vbNullString) > 0 Then
  ' we have a non-Null and non-empty String value
  doSomething()
Else
  ' We have a Null or empty string value
  doSomethingElse()
End If

How to host a Node.Js application in shared hosting

You should look for a hosting company that provides such feature, but standard simple static+PHP+MySQL hosting won't let you use node.js.

You need either find a hosting designed for node.js or buy a Virtual Private Server and install it yourself.

HTML5 Canvas vs. SVG vs. div

While there is still some truth to most of the answers above, I think they deserve an update:

Over the years the performance of SVG has improved a lot and now there is hardware-accelerated CSS transitions and animations for SVG that do not depend on JavaScript performance at all. Of course JavaScript performance has improved, too and with it the performance of Canvas, but not as much as SVG got improved. Also there is a "new kid" on the block that is available in almost all browsers today and that is WebGL. To use the same words that Simon used above: It beats both Canvas and SVG hands down. This doesn't mean it should be the go-to technology, though, since it's a beast to work with and it is only faster in very specific use-cases.

IMHO for most use-cases today, SVG gives the best performance/usability ratio. Visualizations need to be really complex (with respect to number of elements) and really simple at the same time (per element) so that Canvas and even more so WebGL really shine.

In this answer to a similar question I am providing more details, why I think that the combination of all three technologies sometimes is the best option you have.

Fix GitLab error: "you are not allowed to push code to protected branches on this project"?

Simple solution for this problem to have quick chat with person who has owner role in gitlab. He can push one file READ.md or similar to just start with. Later, everything will be working as earlier.

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

Here's my take experience with E7 async/await:

In case you have an async helperFunction() called from your test... (one explicilty with the ES7 async keyword, I mean)

? make sure, you call that as await helperFunction(whateverParams) (well, yeah, naturally, once you know...)

And for that to work (to avoid ‘await is a reserved word’), your test-function must have an outer async marker:

it('my test', async () => { ...

Aligning label and textbox on same line (left and right)

You can do it with a table, like this:

<table width="100%">
  <tr>
    <td style="width: 50%">Left Text</td>
    <td style="width: 50%; text-align: right;">Right Text</td>
  </tr>
</table>

Or, you can do it with CSS like this:

<div style="float: left;">
    Left text
</div>
<div style="float: right;">
    Right text
</div>

GET and POST methods with the same Action name in the same Controller

Since you cannot have two methods with the same name and signature you have to use the ActionName attribute:

[HttpGet]
public ActionResult Index()
{
  // your code
  return View();
}

[HttpPost]
[ActionName("Index")]
public ActionResult IndexPost()
{
  // your code
  return View();
}

Also see "How a Method Becomes An Action"

How to pass the id of an element that triggers an `onclick` event to the event handling function

Here's a non-standard but cross-browser method that may be useful if you don't want to pass any arguments:-

Html:

<div onclick=myHandler() id="my element's id">&rarr; Click Here! &larr;</div>

Script:

function myHandler(){
    alert(myHandler.caller.arguments[0].target.id)
}

Demo: http://codepen.io/mrmoje/pen/ouJtk

Removing element from array in component state

As mentioned in a comment to ephrion's answer above, filter() can be slow, especially with large arrays, as it loops to look for an index that appears to have been determined already. This is a clean, but inefficient solution.

As an alternative one can simply 'slice' out the desired element and concatenate the fragments.

var dummyArray = [];    
this.setState({data: dummyArray.concat(this.state.data.slice(0, index), this.state.data.slice(index))})

Hope this helps!

Sending email with gmail smtp with codeigniter email library

send html email via codeiginater

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



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



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

Checking length of dictionary object

var c = {'a':'A', 'b':'B', 'c':'C'};
var count = 0;
for (var i in c) {
   if (c.hasOwnProperty(i)) count++;
}

alert(count);

Parse DateTime string in JavaScript

I'v been used following code in IE. (IE8 compatible)

var dString = "2013.2.4";
var myDate = new Date( dString.replace(/(\d+)\.(\d+)\.(\d+)/,"$2/$3/$1") );
alert( "my date:"+ myDate );

How do SETLOCAL and ENABLEDELAYEDEXPANSION work?

ENABLEDELAYEDEXPANSION is a parameter passed to the SETLOCAL command (look at setlocal /?)

Its effect lives for the duration of the script, or an ENDLOCAL:

When the end of a batch script is reached, an implied ENDLOCAL is executed for any outstanding SETLOCAL commands issued by that batch script.

In particular, this means that if you use SETLOCAL ENABLEDELAYEDEXPANSION in a script, any environment variable changes are lost at the end of it unless you take special measures.

Grant Select on all Tables Owned By Specific User

Well, it's not a single statement, but it's about as close as you can get with oracle:

BEGIN
   FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
      EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
   END LOOP;
END; 

LINQ to Entities does not recognize the method

As you've figured out, Entity Framework can't actually run your C# code as part of its query. It has to be able to convert the query to an actual SQL statement. In order for that to work, you will have to restructure your query expression into an expression that Entity Framework can handle.

public System.Linq.Expressions.Expression<Func<Charity, bool>> IsSatisfied()
{
    string name = this.charityName;
    string referenceNumber = this.referenceNumber;
    return p => 
        (string.IsNullOrEmpty(name) || 
            p.registeredName.ToLower().Contains(name.ToLower()) ||
            p.alias.ToLower().Contains(name.ToLower()) ||
            p.charityId.ToLower().Contains(name.ToLower())) &&
        (string.IsNullOrEmpty(referenceNumber) ||
            p.charityReference.ToLower().Contains(referenceNumber.ToLower()));
}

What's the valid way to include an image with no src?

I found that simply setting the src to an empty string and adding a rule to your CSS to hide the broken image icon works just fine.

[src=''] {
    visibility: hidden;
}

Check if specific input file is empty

 if( ($_POST) && (!empty($_POST['cover_image'])) )    //verifies  if post exists and cover_image is not empty
    {
    //execute whatever code you want
    }

How to parse freeform street/postal address out of text, and into components

UPDATE: Geocode.xyz now works worldwide. For examples see https://geocode.xyz

For USA, Mexico and Canada, see geocoder.ca.

For example:

Input: something going on near the intersection of main and arthur kill rd new york

Output:

<geodata>
  <latt>40.5123510000</latt>
  <longt>-74.2500500000</longt>
  <AreaCode>347,718</AreaCode>
  <TimeZone>America/New_York</TimeZone>
  <standard>
    <street1>main</street1>
    <street2>arthur kill</street2>
    <stnumber/>
    <staddress/>
    <city>STATEN ISLAND</city>
    <prov>NY</prov>
    <postal>11385</postal>
    <confidence>0.9</confidence>
  </standard>
</geodata>

You may also check the results in the web interface or get output as Json or Jsonp. eg. I'm looking for restaurants around 123 Main Street, New York

Close application and launch home screen on Android

I use this:

1) The parent activity call the secondary activity with the method "startActivityForResult"

2) In the secondary activity when is closing:

int exitCode = 1; // Select the number you want
setResult(exitCode);
finish();

3) And in the parent activity override the method "onActivityResult":

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    int exitCode = 1;
    if(resultCode == exitCode) {
        super.setResult(exitCode); // use this if you have more than 2 activities
        finish();
    }
}

This works fine for me.

What is the difference between instanceof and Class.isAssignableFrom(...)?

Apart from basic differences mentioned above, there is a core subtle difference between instanceof operator and isAssignableFrom method in Class.

Read instanceof as “is this (the left part) the instance of this or any subclass of this (the right part)” and read x.getClass().isAssignableFrom(Y.class) as “Can I write X x = new Y()”. In other words, instanceof operator checks if the left object is same or subclass of right class, while isAssignableFrom checks if we can assign object of the parameter class (from) to the reference of the class on which the method is called.
Note that both of these consider the actual instance not the reference type.

Consider an example of 3 classes A, B and C where C extends B and B extends A.

B b = new C();

System.out.println(b instanceof A); //is b (which is actually class C object) instance of A, yes. This will return true.  
System.out.println(b instanceof B); // is b (which is actually class C object) instance of B, yes. This will return true.  
System.out.println(b instanceof C); // is b (which is actually class C object) instance of C, yes. This will return true. If the first statement would be B b = new B(), this would have been false.
System.out.println(b.getClass().isAssignableFrom(A.class));//Can I write C c = new A(), no. So this is false.
System.out.println(b.getClass().isAssignableFrom(B.class)); //Can I write C c = new B(), no. So this is false.
System.out.println(b.getClass().isAssignableFrom(C.class)); //Can I write C c = new C(), Yes. So this is true.

Angularjs - ng-cloak/ng-show elements blink

I tried every solution posted here and still got flickering in Firefox.

If it helps anyone, I solved it by adding style="display: none;" to the main content div, then using jQuery (I was already using it on the page) $('#main-div-id').show(); once everything was loaded after getting data from the server;

How to print out the method name and line number and conditionally disable NSLog?

NSLog(@"%s %d %s %s", __FILE__, __LINE__, __PRETTY_FUNCTION__, __FUNCTION__);

Outputs file name, line number, and function name:

/proj/cocoa/cdcli/cdcli.m 121 managedObjectContext managedObjectContext

__FUNCTION__ in C++ shows mangled name __PRETTY_FUNCTION__ shows nice function name, in cocoa they look the same.

I'm not sure what is the proper way of disabling NSLog, I did:

#define NSLog

And no logging output showed up, however I don't know if this has any side effects.

FirstOrDefault returns NullReferenceException if no match is found

That is because FirstOrDefaultcan return null causing your following .Value to cause the exception. You need to change it to something like:

var myThing = things.FirstOrDefault(t => t.Id == idToFind);

if(myThing == null)
    return; // we failed to find what we wanted
var displayName = myThing.DisplayName;

Rails select helper - Default selected value, how?

<%= f.select :project_id, @project_select, :selected => params[:pid] %>

How to resolve "Input string was not in a correct format." error?

The problem is with line

imageWidth = 1 * Convert.ToInt32(Label1.Text);

Label1.Text may or may not be int. Check.

Use Int32.TryParse(value, out number) instead. That will solve your problem.

int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
{
    Image1.Width= imageWidth;
}

Best way to store time (hh:mm) in a database

Just store a regular datetime and ignore everything else. Why spend extra time writing code that loads an int, manipulates it, and converts it into a datetime, when you could just load a datetime?

ActionLink htmlAttributes

Replace the desired hyphen with an underscore; it will automatically be rendered as a hyphen:

@Html.ActionLink("Edit", "edit", "markets",
    new { id = 1 },
    new {@class="ui-btn-right", data_icon="gear"})

becomes:

<form action="markets/Edit/1" class="ui-btn-right" data-icon="gear" .../>

How to set value in @Html.TextBoxFor in Razor syntax?

It is going to write the value of your property model.Destination

This is by design. You'll want to populate your Destination property with the value you want in your controller before returning your view.

ng-change get new value and original value

Just keep a currentValue variable in your controller that you update on every change. You can then compare that to the new value every time before you update it.'

The idea of using a watch is good as well, but I think a simple variable is the simplest and most logical solution.

Matplotlib/pyplot: How to enforce axis range?

Calling p.plot after setting the limits is why it is rescaling. You are correct in that turning autoscaling off will get the right answer, but so will calling xlim() or ylim() after your plot command.

I use this quite a lot to invert the x axis, I work in astronomy and we use a magnitude system which is backwards (ie. brighter stars have a smaller magnitude) so I usually swap the limits with

lims = xlim()
xlim([lims[1], lims[0]]) 

Rounding up to next power of 2

If you want an one-line-template. Here it is

int nxt_po2(int n) { return 1 + (n|=(n|=(n|=(n|=(n|=(n-=1)>>1)>>2)>>4)>>8)>>16); }

or

int nxt_po2(int n) { return 1 + (n|=(n|=(n|=(n|=(n|=(n-=1)>>(1<<0))>>(1<<1))>>(1<<2))>>(1<<3))>>(1<<4)); }

css 100% width div not taking up full width of parent

Remove the width:100%; declarations.

Block elements should take up the whole available width by default.

How to fix "The ConnectionString property has not been initialized"

You get this error when a datasource attempts to bind to data but cannot because it cannot find the connection string. In my experience, this is not usually due to an error in the web.config (though I am not 100% sure of this).

If you are programmatically assigning a datasource (such as a SqlDataSource) or creating a query (i.e. using a SqlConnection/SqlCommand combination), make sure you assigned it a ConnectionString.

var connection = new SqlConnection(ConfigurationManager.ConnectionStrings[nameOfString].ConnectionString);

If you are hooking up a databound element to a datasource (i.e. a GridView or ComboBox to a SqlDataSource), make sure the datasource is assigned to one of your connection strings.

Post your code (for the databound element and the web.config to be safe) and we can take a look at it.

EDIT: I think the problem is that you are trying to get the Connection String from the AppSettings area, and programmatically that is not where it exists. Try replacing that with ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString (if ConnectionString is the name of your connection string.)

Use Mockito to mock some methods but not others

Partial mocking of a class is also supported via Spy in mockito

List list = new LinkedList();
List spy = spy(list);

//optionally, you can stub out some methods:
when(spy.size()).thenReturn(100);

//using the spy calls real methods
spy.add("one");
spy.add("two");

//size() method was stubbed - 100 is printed
System.out.println(spy.size());

Check the 1.10.19 and 2.7.22 docs for detailed explanation.

How to create a zip file in Java

This is how you create a zip file from a source file:

String srcFilename = "C:/myfile.txt";
String zipFile = "C:/myfile.zip";

try {
    byte[] buffer = new byte[1024];
    FileOutputStream fos = new FileOutputStream(zipFile);
    ZipOutputStream zos = new ZipOutputStream(fos);         
    File srcFile = new File(srcFilename);
    FileInputStream fis = new FileInputStream(srcFile);
    zos.putNextEntry(new ZipEntry(srcFile.getName()));          
    int length;
    while ((length = fis.read(buffer)) > 0) {
        zos.write(buffer, 0, length);
    }
    zos.closeEntry();
    fis.close();
    zos.close();            
}
catch (IOException ioe) {
    System.out.println("Error creating zip file" + ioe);
}

socket.error: [Errno 48] Address already in use

You already have a process bound to the default port (8000). If you already ran the same module before, it is most likely that process still bound to the port. Try and locate the other process first:

$ ps -fA | grep python
  501 81651 12648   0  9:53PM ttys000    0:00.16 python -m SimpleHTTPServer

The command arguments are included, so you can spot the one running SimpleHTTPServer if more than one python process is active. You may want to test if http://localhost:8000/ still shows a directory listing for local files.

The second number is the process number; stop the server by sending it a signal:

kill 81651

This sends a standard SIGTERM signal; if the process is unresponsive you may have to resort to tougher methods like sending a SIGKILL (kill -s KILL <pid> or kill -9 <pid>) signal instead. See Wikipedia for more details.

Alternatively, run the server on a different port, by specifying the alternative port on the command line:

$ python -m SimpleHTTPServer 8910
Serving HTTP on 0.0.0.0 port 8910 ...

then access the server as http://localhost:8910; where 8910 can be any number from 1024 and up, provided the port is not already taken.

Determining image file size + dimensions via Javascript?

var img = new Image();
img.src = sYourFilePath;
var iSize = img.fileSize;

How to resolve ORA 00936 Missing Expression Error?

This happens every time you insert/ update and you don't use single quotes. When the variable is empty it will result in that error. Fix it by using ''

Assuming the first parameter is an empty variable here is a simple example:

Wrong

nvl( ,0)

Fix

nvl('' ,0)

Put your query into your database software and check it for that error. Generally this is an easy fix

Adding Lombok plugin to IntelliJ project

To install the plugin manually, try:

  1. Download Lombok zip file (ensure Lombok matches the IDE version).
  2. Select Preferences Plugins Install Plugins from Disk.

IntelliJ Plugin Preferences Dialog

How to apply slide animation between two activities in Android?

Slide up/down with alpha animation with a few note

enter image description here

slide_up.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@integer/activity_transition_time"
    >
    <translate
        android:fromYDelta="100%p"
        android:toYDelta="0"/>
    <alpha
        android:fromAlpha="0.5"
        android:toAlpha="1"/>
</set>

slide_down.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@integer/activity_transition_time"
    >
    <translate
        android:fromYDelta="0"
        android:toYDelta="100%p"/>
    <alpha
        android:fromAlpha="1"
        android:toAlpha="0.5"/>
</set>

no_animation.xml

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@integer/activity_transition_time"
    android:fromYDelta="0"
    android:toYDelta="0"/>

First Activity

startActivity(new Intent(this, SecondActivity.class));
overridePendingTransition(R.anim.slide_up,  R.anim.no_animation); // remember to put it after startActivity, if you put it to above, animation will not working
// document say if we don't want animation we can put 0. However, if we put 0 instead of R.anim.no_animation, the exist activity will become black when animate

Second Activity

finish();
overridePendingTransition(R.anim.no_animation, R.anim.slide_down);

Done

MORE
I try to make the slide animation like iOS animation when present a View Model (like this https://www.youtube.com/watch?v=deZobvh2064) but failed.

Looking at iOS present animation you will see: The animation from bottom with alpha (about 50%) then it go very fast then slower, the animation time is about > 500ms (I use trim video tools for count the animation time https://www.kapwing.com/trim-video so it can not exactly 100%)

Then I try to apply to android.
To make alpha I use <alpha> and success.
To make animation start faster than slower I use android:interpolator="a decelerate interpolator" but it almost failed.

There are 3 default decelerate interpolator in Android
@android:interpolator/decelerate_quad -> factor = 1
@android:interpolator/decelerate_cubic -> factor = 1.5
@android:interpolator/decelerate_quint _> factor = 2.5
(higher factor <=> animation start more faster from start and more slower at end)
Here is a good tutorial http://cogitolearning.co.uk/2013/10/android-animations-tutorial-5-more-on-interpolators/ for understand it

I tried 3 above I can not achieve like iOS, the animation can not start faster like iOS. Then I create a custom decelerateInterpolator wiht factor = 3 like

<?xml version="1.0" encoding="utf-8"?>
<decelerateInterpolator xmlns:android="http://schemas.android.com/apk/res/android"
    android:factor="3" />

and I increase the duration time from 500 -> 750. It working well (very similar to iOS). However, it only working well in some device, in some device the animation is quite slow. Later on, I know that animation may different on different device (eg: some device will faster and some device will slower) so I can not make it the animation similar in all Android device. Therefore I don't use interpolator. I don't know if my testing is exactly 100% or not but I hope this experience help

how to loop through json array in jquery?

Try this:

var data = jQuery.parseJSON(response);
$.each(data, function(key, item) 
{
   console.log(item.com);
});

or

var data = $.parseJSON(response);

$(data).each(function(i,val)
 {
    $.each(val,function(key,val)
  {
          console.log(key + " : " + val);     
  });
});

Sorted array list in Java

Have a look at SortedList

This class implements a sorted list. It is constructed with a comparator that can compare two objects and sort objects accordingly. When you add an object to the list, it is inserted in the correct place. Object that are equal according to the comparator, will be in the list in the order that they were added to this list. Add only objects that the comparator can compare.


When the list already contains objects that are equal according to the comparator, the new object will be inserted immediately after these other objects.

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

@paul burke's answer works fine for both camera and gallery pictures for API level 19 and above, but it doesn't work if your Android project's minimum SDK is set to below 19, and some answers referring above doesn't work for both gallery and camera. Well, I have modified @paul burke's code which works for API level below 19. Below is the code.

public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >=
                             Build.VERSION_CODES.KITKAT;
    Log.i("URI",uri+"");
    String result = uri+"";

    // DocumentProvider
    // if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
    if (isKitKat && (result.contains("media.documents"))) {

        String[] ary = result.split("/");
        int length = ary.length;
        String imgary = ary[length-1];
        final String[] dat = imgary.split("%3A");

        final String docId = dat[1];
        final String type = dat[0];

        Uri contentUri = null;
        if ("image".equals(type)) {
            contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
        }
        else if ("video".equals(type)) {
        }
        else if ("audio".equals(type)) {
        }

        final String selection = "_id=?";
        final String[] selectionArgs = new String[] {
            dat[1]
        };

        return getDataColumn(context, contentUri, selection, selectionArgs);
    }
    else
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

public static String getDataColumn(Context context, Uri uri, String selection,
                                   String[] selectionArgs) {
    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    }
    finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}

How to correctly get image from 'Resources' folder in NetBeans

For me it worked like I had images in icons folder under src and I wrote below code.

new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));

Is it possible to send a variable number of arguments to a JavaScript function?

For those who were redirected here from Passing variable number of arguments from one function to another (which should not be marked as a duplicate of this question):

If you're trying to pass a variable number of arguments from one function to another, since JavaScript 1.8.5 you can simply call apply() on the second function and pass in the arguments parameter:

var caller = function()
{
    callee.apply( null, arguments );
}

var callee = function()
{
    alert( arguments.length );
}

caller( "Hello", "World!", 88 ); // Shows "3".

Note: The first argument is the this parameter to use. Passing null will call the function from the global context, i.e. as a global function instead of the method of some object.

According to this document, the ECMAScript 5 specification redefined the apply() method to take any "generic array-like object", instead of strictly an Array. Thus, you can directly pass the arguments list into the second function.

Tested in Chrome 28.0, Safari 6.0.5, and IE 10. Try it out with this JSFiddle.

What is the default root pasword for MySQL 5.7

After a lot of try, I could reset the default password with the following commands (Ubuntu and derivatives):

sudo -i
mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld
/etc/init.d/mysql stop
mysqld_safe --skip-grant-tables &
mysql -uroot
use mysql;
update user set authentication_string=password('YOURPASSWORD') where user='root';
update user set plugin="mysql_native_password" where User='root';  
flush privileges;
quit;
sudo /etc/init.d/mysql stop
sudo /etc/init.d/mysql start

Sometimes, even after typed in the terminal

mkdir -p /var/run/mysqld
chown mysql:mysql /var/run/mysqld
/etc/init.d/mysql stop
mysqld_safe --skip-grant-tables &

I got the error that the mysqld don't exists. So, quit, and type the same commands again.

And the final command

sudo /etc/init.d/mysql start

Sometimes doesn't work. Only after restart the computer.

Use CSS3 transitions with gradient backgrounds

As stated. Gradients aren't currently supported with CSS Transitions. But you could work around it in some cases by setting one of the colors to transparent, so that the background-color of some other wrapping element shines through, and transition that instead.

Adding Multiple Values in ArrayList at a single index

create simple method to do that for you:

public void addMulti(String[] strings,List list){
    for (int i = 0; i < strings.length; i++) {
        list.add(strings[i]);
    }
}

Then you can create

String[] wrong ={"1","2","3","4","5","6"};

and add it with this method to your list.

What's the best way to convert a number to a string in JavaScript?

like this:

var foo = 45;
var bar = '' + foo;

Actually, even though I typically do it like this for simple convenience, over 1,000s of iterations it appears for raw speed there is an advantage for .toString()

See Performance tests here (not by me, but found when I went to write my own): http://jsben.ch/#/ghQYR

Fastest based on the JSPerf test above: str = num.toString();

It should be noted that the difference in speed is not overly significant when you consider that it can do the conversion any way 1 Million times in 0.1 seconds.

Update: The speed seems to differ greatly by browser. In Chrome num + '' seems to be fastest based on this test http://jsben.ch/#/ghQYR

Update 2: Again based on my test above it should be noted that Firefox 20.0.1 executes the .toString() about 100 times slower than the '' + num sample.

What do all of Scala's symbolic operators mean?

<= is just like you would "read" it: 'less than or equals'. So it's a mathematical operator, in the list of < (is less than?), > (is greater than?), == (equals?), != (is not equal?), <= (is less than or equal?), and >= (is greater than or equal?).

This must not be confused with => which is kind of a double right-hand arrow, used to separate the argument list from the body of a function and to separate the testing condition in pattern matching (a case block) from the body executed when a match occurs. You can see example of this in my previous two answers. First, the function use:

coll.map(tup => tup._2.reverse)

which is already abbreviated as the types are omitted. The follow function would be

// function arguments         function body
(tup: Tuple2[Int, String]) => tup._2.reverse

and the pattern matching use:

def extract2(l: List[Int]) = l match {
   // if l matches Nil    return "empty"
   case Nil            => "empty"
   // etc.
   case ::(head, Nil)  => "exactly one element (" + head + ")"
   // etc.
   case ::(head, tail) => "more than one element"
}

jquery simple image slideshow tutorial

Here is my adaptation of Michael Soriano's tutorial. See below or in JSBin.

_x000D_
_x000D_
$(function() {_x000D_
  var theImage = $('ul#ss li img');_x000D_
  var theWidth = theImage.width();_x000D_
  //wrap into mother div_x000D_
  $('ul#ss').wrap('<div id="mother" />');_x000D_
  //assign height width and overflow hidden to mother_x000D_
  $('#mother').css({_x000D_
    width: function() {_x000D_
      return theWidth;_x000D_
    },_x000D_
    height: function() {_x000D_
      return theImage.height();_x000D_
    },_x000D_
    position: 'relative',_x000D_
    overflow: 'hidden'_x000D_
  });_x000D_
  //get total of image sizes and set as width for ul _x000D_
  var totalWidth = theImage.length * theWidth;_x000D_
  $('ul').css({_x000D_
    width: function() {_x000D_
      return totalWidth;_x000D_
    }_x000D_
  });_x000D_
_x000D_
  var ss_timer = setInterval(function() {_x000D_
    ss_next();_x000D_
  }, 3000);_x000D_
_x000D_
  function ss_next() {_x000D_
    var a = $(".active");_x000D_
    a.removeClass('active');_x000D_
_x000D_
    if (a.hasClass('last')) {_x000D_
      //last element -- loop_x000D_
      a.parent('ul').animate({_x000D_
        "margin-left": (0)_x000D_
      }, 1000);_x000D_
      a.siblings(":first").addClass('active');_x000D_
    } else {_x000D_
      a.parent('ul').animate({_x000D_
        "margin-left": (-(a.index() + 1) * theWidth)_x000D_
      }, 1000);_x000D_
      a.next().addClass('active');_x000D_
    }_x000D_
  }_x000D_
_x000D_
  // Cancel slideshow and move next manually on click_x000D_
  $('ul#ss li img').on('click', function() {_x000D_
    clearInterval(ss_timer);_x000D_
    ss_next();_x000D_
  });_x000D_
_x000D_
});
_x000D_
* {_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
#ss {_x000D_
  list-style: none;_x000D_
}_x000D_
#ss li {_x000D_
  float: left;_x000D_
}_x000D_
#ss img {_x000D_
  width: 200px;_x000D_
  height: 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<ul id="ss">_x000D_
  <li class="active">_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/colorado-colors.jpg">_x000D_
  </li>_x000D_
  <li>_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/monte-vista.jpg">_x000D_
  </li>_x000D_
  <li class="last">_x000D_
    <img src="http://leemark.github.io/better-simple-slideshow/demo/img/colorado.jpg">_x000D_
  </li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Error:Unable to locate adb within SDK in Android Studio

I deleted and re-installed the Android SDK Platform-Tools 23 23.0.0. This solved the problem. Yesterday i had done a complete update of the SDK using SDK Manager, deleting some parts that i believed i no longer needed and downloading updates. Perhaps this was the source of the problem.

The opposite of Intersect()

array1.NonIntersect(array2);

Nonintersect such operator is not present in Linq you should do

except -> union -> except

a.except(b).union(b.Except(a));

android listview get selected item

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

      }                 
});

I hope this fixes your problem.

How to right-align and justify-align in Markdown?

In a generic Markdown document, use:

<style>body {text-align: right}</style>

or

<style>body {text-align: justify}</style>

Does not seem to work with Jupyter though.

sqlite copy data from one table to another

If you have data already present in both the tables and you want to update a table column values based on some condition then use this

UPDATE Table1 set Name=(select t2.Name from Table2 t2 where t2.id=Table1.id)

Regex - Should hyphens be escaped?

Correct on all fronts. Outside of a character class (that's what the "square brackets" are called) the hyphen has no special meaning, and within a character class, you can place a hyphen as the first or last character in the range (e.g. [-a-z] or [0-9-]), OR escape it (e.g. [a-z\-0-9]) in order to add "hyphen" to your class.

It's more common to find a hyphen placed first or last within a character class, but by no means will you be lynched by hordes of furious neckbeards for choosing to escape it instead.

(Actually... my experience has been that a lot of regex is employed by folks who don't fully grok the syntax. In these cases, you'll typically see everything escaped (e.g. [a-z\%\$\#\@\!\-\_]) simply because the engineer doesn't know what's "special" and what's not... so they "play it safe" and obfuscate the expression with loads of excessive backslashes. You'll be doing yourself, your contemporaries, and your posterity a huge favor by taking the time to really understand regex syntax before using it.)

Great question!

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

What is the difference between iterator and iterable and how to use them?

I will answer the question especially about ArrayList as an example in order to help you understand better..

  1. Iterable interface forces its subclasses to implement abstract method 'iterator()'.
public interface Iterable {
  ...
  abstract Iterator<T> iterator(); //Returns an 'Iterator'(not iterator) over elements of type T.
  ...
}
  1. Iterator interface forces its subclasses to implement abstract method 'hasNext()' and 'next()'.
public interface Iterator {
  ...
  abstract boolean hasNext(); //Returns true if the iteration has more elements.
  abstract E next();          //Returns the next element in the iteration.
  ...
}
  1. ArrayList implements List, List extends Collection and Collection extends Iterable.. That is, you could see the relationship like

    'Iterable <- Collection <- List <- ArrayList'

. And Iterable, Collection and List just declare abstract method 'iterator()' and ArrayList alone implements it.

  1. I am going to show ArrayList source code with 'iterator()' method as follows for more detailed information.

'iterator()' method returns an object of class 'Itr' which implements 'Iterator'.

public class ArrayList<E> ... implements List<E>, ...
{
  ...
  public Iterator<E> iterator() {
              return new Itr();
  }


  private class Itr implements Iterator<E> {
          ...

          public boolean hasNext() {
              return cursor != size;
          }
          @SuppressWarnings("unchecked")
          public E next() {
              checkForComodification();
              int i = cursor;
              if (i >= size)
                  throw new NoSuchElementException();
              Object[] elementData = ArrayList.this.elementData;
              if (i >= elementData.length)
                  throw new ConcurrentModificationException();
              cursor = i + 1;
              return (E) elementData[lastRet = i];
          }
          ...
  }
}
  1. Some other methods or classes will iterate elements of collections like ArrayList through making use of Iterator (Itr).

Here is a simple example.

public static void main(String[] args) {

    List<String> list = new ArrayList<>();
    list.add("a");
    list.add("b");
    list.add("c");
    list.add("d");
    list.add("e");
    list.add("f");

    Iterator<String> iterator = list.iterator();
    while (iterator.hasNext()) {
        String string = iterator.next();
        System.out.println(string);
    }
}

Now, is it clear? :)

What is the use of join() in Python threading?

A somewhat clumsy ascii-art to demonstrate the mechanism: The join() is presumably called by the main-thread. It could also be called by another thread, but would needlessly complicate the diagram.

join-calling should be placed in the track of the main-thread, but to express thread-relation and keep it as simple as possible, I choose to place it in the child-thread instead.

without join:
+---+---+------------------                     main-thread
    |   |
    |   +...........                            child-thread(short)
    +..................................         child-thread(long)

with join
+---+---+------------------***********+###      main-thread
    |   |                             |
    |   +...........join()            |         child-thread(short)
    +......................join()......         child-thread(long)

with join and daemon thread
+-+--+---+------------------***********+###     parent-thread
  |  |   |                             |
  |  |   +...........join()            |        child-thread(short)
  |  +......................join()......        child-thread(long)
  +,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,     child-thread(long + daemonized)

'-' main-thread/parent-thread/main-program execution
'.' child-thread execution
'#' optional parent-thread execution after join()-blocked parent-thread could 
    continue
'*' main-thread 'sleeping' in join-method, waiting for child-thread to finish
',' daemonized thread - 'ignores' lifetime of other threads;
    terminates when main-programs exits; is normally meant for 
    join-independent tasks

So the reason you don't see any changes is because your main-thread does nothing after your join. You could say join is (only) relevant for the execution-flow of the main-thread.

If, for example, you want to concurrently download a bunch of pages to concatenate them into a single large page, you may start concurrent downloads using threads, but need to wait until the last page/thread is finished before you start assembling a single page out of many. That's when you use join().

How to make PopUp window in java

Check out Swing Dialogs (mainly focused on JOptionPane, as mentioned by @mcfinnigan).

git repo says it's up-to-date after pull but files are not updated

For me my forked branch was not in sync with the master branch. So I went to bitbucket and synced and merged my forked branch and then tried to take the pull. Then it worked fine.

Insert content into iFrame

Wait, are you really needing to render it using javascript?

Be aware that in HTML5 there is srcdoc, which can do that for you! (The drawback is that IE/EDGE does not support it yet https://caniuse.com/#feat=iframe-srcdoc)

See here [srcdoc]: https://www.w3schools.com/tags/att_iframe_srcdoc.asp

Another thing to note is that if you want to avoid the interference of the js code inside and outside you should consider using the sandbox mode.

See here [sandbox]: https://www.w3schools.com/tags/att_iframe_sandbox.asp

Run chrome in fullscreen mode on Windows

It's very easy.

"your chrome path" -kiosk -fullscreen "your URL"

Example:

"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" -kiosk -fullscreen http://google.com

Close all Chrome sessions first !

To exit: Press ALT-TAB > hold ALT and press X in the windows task. (win10)

SQL LIKE condition to check for integer?

Assuming that you're looking for "numbers that start with 7" rather than "strings that start with 7," maybe something like

select * from books where convert(char(32), book_id) like '7%'

Or whatever the Postgres equivalent of convert is.

What exactly does += do in python?

+= adds another value with the variable's value and assigns the new value to the variable.

>>> x = 3
>>> x += 2
>>> print x
5

-=, *=, /= does similar for subtraction, multiplication and division.

Get age from Birthdate

Try this function...

function calculate_age(birth_month,birth_day,birth_year)
{
    today_date = new Date();
    today_year = today_date.getFullYear();
    today_month = today_date.getMonth();
    today_day = today_date.getDate();
    age = today_year - birth_year;

    if ( today_month < (birth_month - 1))
    {
        age--;
    }
    if (((birth_month - 1) == today_month) && (today_day < birth_day))
    {
        age--;
    }
    return age;
}

OR

function getAge(dateString) 
{
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) 
    {
        age--;
    }
    return age;
}

See Demo.

OS X cp command in Terminal - No such file or directory

Summary of solution:

directory is neither an existing file nor directory. As it turns out, the real name is directory.1 as revealed by ls -la $HOME/Desktop/.

The complete working command is

cp -R $HOME/directory.1/file.bundle /library/application\ support/directory/

with the -R parameter for recursive copy (compulsory for copying directories).

Math operations from string

The easiest way is to use eval as in:

 >>> eval("2   +    2")
 4

Pay attention to the fact I included spaces in the string. eval will execute a string as if it was a Python code, so if you want the input to be in a syntax other than Python, you should parse the string yourself and calculate, for example eval("2x7") would not give you 14 because Python uses * for multiplication operator rather than x.

How can I create an object and add attributes to it?

The mock module is basically made for that.

import mock
obj = mock.Mock()
obj.a = 5

The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I ran into this problem today and wanted to share my solution. In my case, the solution was to delete the Child items before getting the Parent from the database.

Previously I was doing it like in the code below. I will then get the same error listed in this question.

var Parent = GetParent(parentId);
var children = Parent.Children;
foreach (var c in children )
{
     Context.Children.Remove(c);
}
Context.SaveChanges();

What worked for me, is to get the children items first, using the parentId (foreign key) and then delete those items. Then I can get the Parent from the database and at that point, it should not have any children items anymore and I can add new children items.

var children = GetChildren(parentId);
foreach (var c in children )
{
     Context.Children.Remove(c);
}
Context.SaveChanges();

var Parent = GetParent(parentId);
Parent.Children = //assign new entities/items here

Loop Through All Subfolders Using VBA

And to complement Rich's recursive answer, a non-recursive method.

Public Sub NonRecursiveMethod()
    Dim fso, oFolder, oSubfolder, oFile, queue As Collection

    Set fso = CreateObject("Scripting.FileSystemObject")
    Set queue = New Collection
    queue.Add fso.GetFolder("your folder path variable") 'obviously replace

    Do While queue.Count > 0
        Set oFolder = queue(1)
        queue.Remove 1 'dequeue
        '...insert any folder processing code here...
        For Each oSubfolder In oFolder.SubFolders
            queue.Add oSubfolder 'enqueue
        Next oSubfolder
        For Each oFile In oFolder.Files
            '...insert any file processing code here...
        Next oFile
    Loop

End Sub

You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1) with Set oFolder = queue(queue.Count) and replace queue.Remove(1) with queue.Remove(queue.Count), and probably rename the variable...)

Constants in Kotlin -- what's a recommended way to create them?

First of all, the naming convention in Kotlin for constants is the same than in java (e.g : MY_CONST_IN_UPPERCASE).

How should I create it ?

1. As a top level value (recommended)

You just have to put your const outside your class declaration.

Two possibilities : Declare your const in your class file (your const have a clear relation with your class)

private const val CONST_USED_BY_MY_CLASS = 1

class MyClass { 
    // I can use my const in my class body 
}

Create a dedicated constants.kt file where to store those global const (Here you want to use your const widely across your project) :

package com.project.constants
const val URL_PATH = "https:/"

Then you just have to import it where you need it :

import com.project.constants

MyClass {
    private fun foo() {
        val url = URL_PATH
        System.out.print(url) // https://
    }
}

2. Declare it in a companion object (or an object declaration)

This is much less cleaner because under the hood, when bytecode is generated, a useless object is created :

MyClass {
    companion object {
        private const val URL_PATH = "https://"
        const val PUBLIC_URL_PATH = "https://public" // Accessible in other project files via MyClass.PUBLIC_URL_PATH
    }
}

Even worse if you declare it as a val instead of a const (compiler will generate a useless object + a useless function) :

MyClass {
    companion object {
        val URL_PATH = "https://"
    }
}

Note :

In kotlin, const can just hold primitive types. If you want to pass a function to it, you need add the @JvmField annotation. At compile time, it will be transform as a public static final variable. But it's slower than with a primitive type. Try to avoid it.

@JvmField val foo = Foo()

Line break in HTML with '\n'

Simple and linear:

 <p> my phrase is this..<br>
 the other line is this<br>
 the end is this other phrase..
 </p>

The mysqli extension is missing. Please check your PHP configuration

  1. Find out which php.ini is used.
  2. In file php.ini this line:

    extension=mysqli
    
  3. Replace by:

    extension="C:\php\ext\php_mysqli.dll"
    
  4. Restart apache

Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.

How do you upload a file to a document library in sharepoint?

I used this article to allow to c# to access to a sharepoint site.

http://www.thesharepointguide.com/access-office-365-using-a-console-application/

Basically you create a ClientId and ClientSecret keys to access to the site with c#

Hope this can help you!

How does the Python's range function work?

When I'm teaching someone programming (just about any language) I introduce for loops with terminology similar to this code example:

for eachItem in someList:
    doSomething(eachItem)

... which, conveniently enough, is syntactically valid Python code.

The Python range() function simply returns or generates a list of integers from some lower bound (zero, by default) up to (but not including) some upper bound, possibly in increments (steps) of some other number (one, by default).

So range(5) returns (or possibly generates) a sequence: 0, 1, 2, 3, 4 (up to but not including the upper bound).

A call to range(2,10) would return: 2, 3, 4, 5, 6, 7, 8, 9

A call to range(2,12,3) would return: 2, 5, 8, 11

Notice that I said, a couple times, that Python's range() function returns or generates a sequence. This is a relatively advanced distinction which usually won't be an issue for a novice. In older versions of Python range() built a list (allocated memory for it and populated with with values) and returned a reference to that list. This could be inefficient for large ranges which might consume quite a bit of memory and for some situations where you might want to iterate over some potentially large range of numbers but were likely to "break" out of the loop early (after finding some particular item in which you were interested, for example).

Python supports more efficient ways of implementing the same semantics (of doing the same thing) through a programming construct called a generator. Instead of allocating and populating the entire list and return it as a static data structure, Python can instantiate an object with the requisite information (upper and lower bounds and step/increment value) ... and return a reference to that.

The (code) object then keeps track of which number it returned most recently and computes the new values until it hits the upper bound (and which point it signals the end of the sequence to the caller using an exception called "StopIteration"). This technique (computing values dynamically rather than all at once, up-front) is referred to as "lazy evaluation."

Other constructs in the language (such as those underlying the for loop) can then work with that object (iterate through it) as though it were a list.

For most cases you don't have to know whether your version of Python is using the old implementation of range() or the newer one based on generators. You can just use it and be happy.

If you're working with ranges of millions of items, or creating thousands of different ranges of thousands each, then you might notice a performance penalty for using range() on an old version of Python. In such cases you could re-think your design and use while loops, or create objects which implement the "lazy evaluation" semantics of a generator, or use the xrange() version of range() if your version of Python includes it, or the range() function from a version of Python that uses the generators implicitly.

Concepts such as generators, and more general forms of lazy evaluation, permeate Python programming as you go beyond the basics. They are usually things you don't have to know for simple programming tasks but which become significant as you try to work with larger data sets or within tighter constraints (time/performance or memory bounds, for example).

[Update: for Python3 (the currently maintained versions of Python) the range() function always returns the dynamic, "lazy evaluation" iterator; the older versions of Python (2.x) which returned a statically allocated list of integers are now officially obsolete (after years of having been deprecated)].

Algorithm for Determining Tic Tac Toe Game Over

you can use a magic square http://mathworld.wolfram.com/MagicSquare.html if any row, column, or diag adds up to 15 then a player has won.

Tips for using Vim as a Java IDE?

I found the following summary very useful: http://www.techrepublic.com/article/configure-vi-for-java-application-development/5054618. The description of :make was for ant not maven, but otherwise a nice summary.