Programs & Examples On #Xhprof

XHProf is a profiling extension for PHP light weight enough to be run in production

How to stop process from .BAT file?

Why don't you use PowerShell?

Stop-Process -Name notepad

And if you are in a batch file:

powershell -Command "Stop-Process -Name notepad"
powershell -Command "Stop-Process -Id 4232"

Passing an array by reference

Arrays are default passed by pointers. You can try modifying an array inside a function call for better understanding.

Overwriting txt file in java

The easiest way to overwrite a text file is to use a public static field.

this will overwrite the file every time because your only using false the first time through.`

public static boolean appendFile;

Use it to allow only one time through the write sequence for the append field of the write code to be false.

// use your field before processing the write code

appendFile = False;

File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;

try {
     //change this line to read this

    // f2 = new FileWriter(fnew,false);

    // to read this
    f2 = new FileWriter(fnew,appendFile); // important part
    f2.write(source);

    // change field back to true so the rest of the new data will
    // append to the new file.

    appendFile = true;

    f2.close();
 } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
 }           

How does data binding work in AngularJS?

It happened that I needed to link a data model of a person with a form, what I did was a direct mapping of the data with the form.

For example if the model had something like:

$scope.model.people.name

The control input of the form:

<input type="text" name="namePeople" model="model.people.name">

That way if you modify the value of the object controller, this will be reflected automatically in the view.

An example where I passed the model is updated from server data is when you ask for a zip code and zip code based on written loads a list of colonies and cities associated with that view, and by default set the first value with the user. And this I worked very well, what does happen, is that angularJS sometimes takes a few seconds to refresh the model, to do this you can put a spinner while displaying the data.

How to check if a string contains a specific text

you can use this code

$a = '';

if(!empty($a))
  echo 'text';

Get characters after last / in url

Very simply:

$id = substr($url, strrpos($url, '/') + 1);

strrpos gets the position of the last occurrence of the slash; substr returns everything after that position.


As mentioned by redanimalwar if there is no slash this doesn't work correctly since strrpos returns false. Here's a more robust version:

$pos = strrpos($url, '/');
$id = $pos === false ? $url : substr($url, $pos + 1);

warning: assignment makes integer from pointer without a cast

The expression *src refers to the first character in the string, not the whole string. To reassign src to point to a different string tgt, use src = tgt;.

JavaScript - populate drop down list with array

You'll first get the dropdown element from the DOM, then loop through the array, and add each element as a new option in the dropdown like this:

// Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");

// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
    // Append the element to the end of Array list
    dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}?

See JSFiddle for a live demo: http://jsfiddle.net/nExgJ/

This assumes that you're not using JQuery, and you only have the basic DOM API to work with.

JavaScript Form Submit - Confirm or Cancel Submission Dialog Box

A simple inline JavaScript confirm would suffice:

<form onsubmit="return confirm('Do you really want to submit the form?');">

No need for an external function unless you are doing validation, which you can do something like this:

<script>
function validate(form) {

    // validation code here ...


    if(!valid) {
        alert('Please correct the errors in the form!');
        return false;
    }
    else {
        return confirm('Do you really want to submit the form?');
    }
}
</script>
<form onsubmit="return validate(this);">

How to select the comparison of two columns as one column in Oracle

I stopped using DECODE several years ago because it is non-portable. Also, it is less flexible and less readable than a CASE/WHEN.

However, there is one neat "trick" you can do with decode because of how it deals with NULL. In decode, NULL is equal to NULL. That can be exploited to tell whether two columns are different as below.

select a, b, decode(a, b, 'true', 'false') as same
  from t;

     A       B  SAME
------  ------  -----
     1       1  true
     1       0  false
     1          false
  null    null  true  

How to export data to CSV in PowerShell?

This solution creates a psobject and adds each object to an array, it then creates the csv by piping the contents of the array through Export-CSV.

$results = @()
foreach ($computer in $computerlist) {
    if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
    {
        foreach ($file in $REMOVE) {
            Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
            Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"            
        }
    } else {

        $details = @{            
                Date             = get-date              
                ComputerName     = $Computer                 
                Destination      = $Destination 
        }                           
        $results += New-Object PSObject -Property $details  
    }
}
$results | export-csv -Path c:\temp\so.csv -NoTypeInformation

If you pipe a string object to a csv you will get its length written to the csv, this is because these are properties of the string, See here for more information.

This is why I create a new object first.

Try the following:

write-output "test" | convertto-csv -NoTypeInformation

This will give you:

"Length"
"4"

If you use the Get-Member on Write-Output as follows:

write-output "test" | Get-Member -MemberType Property

You will see that it has one property - 'length':

   TypeName: System.String

Name   MemberType Definition
----   ---------- ----------
Length Property   System.Int32 Length {get;}

This is why Length will be written to the csv file.


Update: Appending a CSV Not the most efficient way if the file gets large...

$csvFileName = "c:\temp\so.csv"
$results = @()
if (Test-Path $csvFileName)
{
    $results += Import-Csv -Path $csvFileName
}
foreach ($computer in $computerlist) {
    if((Test-Connection -Cn $computer -BufferSize 16 -Count 1 -ea 0 -quiet))
    {
        foreach ($file in $REMOVE) {
            Remove-Item "\\$computer\$DESTINATION\$file" -Recurse
            Copy-Item E:\Code\powershell\shortcuts\* "\\$computer\$DESTINATION\"            
        }
    } else {

        $details = @{            
                Date             = get-date              
                ComputerName     = $Computer                 
                Destination      = $Destination 
        }                           
        $results += New-Object PSObject -Property $details  
    }
}
$results | export-csv -Path $csvFileName -NoTypeInformation

Trouble setting up git with my GitHub Account error: could not lock config file

I am old to the party but may be this will help some one. Thanks to @paperclip

In Windows 10:

Step 1: Go to This PC > Right click Properties

step 2: Click Advanced System Settings and click Environment Variables

Step 3: Under System Variables create new variable called HOME and input the value as %USERPROFILE% like below

enter image description here

Step 4: Important You must restart your PC to take effect

Step 5: Install Git for Windows now and optional Tortoise Git for windows if you prefer.

Make a git clone request or try pushing something in to your repo. Magic it will work. All should work fine now.

How to make div background color transparent in CSS

    /*Fully Opaque*/
    .class-name {
      opacity:1.0;
    }

    /*Translucent*/
    .class-name {
      opacity:0.5;
    }

    /*Transparent*/
    .class-name {
      opacity:0;
    }

    /*or you can use a transparent rgba value like this*/
    .class-name{
      background-color: rgba(255, 242, 0, 0.7);
      }

    /*Note - Opacity value can be anything between 0 to 1;
    Eg(0.1,0.8)etc */

Oracle PL/SQL string compare issue

To the first question:

Probably the message wasn't print out because you have the output turned off. Use these commands to turn it back on:

set serveroutput on
exec dbms_output.enable(1000000);

On the second question:

My PLSQL is quite rusty so I can't give you a full snippet, but you'll need to loop over the result set of the SQL query and CONCAT all the strings together.

What is a simple C or C++ TCP server and client example?

If the code should be simple, then you probably asking for C example based on traditional BSD sockets. Solutions like boost::asio are imho quite complicated when it comes to short and simple "hello world" example.

To compile examples you mentioned you must make simple fixes, because you are compiling under C++ compiler. I'm referring to following files:
http://www.linuxhowtos.org/data/6/server.c
http://www.linuxhowtos.org/data/6/client.c
from: http://www.linuxhowtos.org/C_C++/socket.htm

  1. Add following includes to both files:

    #include <cstdlib>
    #include <cstring>
    #include <unistd.h>
    
  2. In client.c, change the line:

    if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
    { ... }
    

    to:

    if (connect(sockfd,(const sockaddr*)&serv_addr,sizeof(serv_addr)) < 0)
    { ... }
    

As you can see in C++ an explicit cast is needed.

Python: tf-idf-cosine: to find document similarity

This should help you.

from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity  

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(train_set)
print tfidf_matrix
cosine = cosine_similarity(tfidf_matrix[length-1], tfidf_matrix)
print cosine

and output will be:

[[ 0.34949812  0.81649658  1.        ]]

How to add new line in Markdown presentation?

If none of the solutions mentions here work for you, which is what happened with me, then you can do the following: Add an empty header (A hack that ruins semantics)

text
####
text

Just make sure that when the header is added it has no border in bottom of it in the markdown css, so you can try different variations of the headers.

How to parse a text file with C#

Like it's already mentioned, I would highly recommend using regular expression (in System.Text) to get this kind of job done.

In combo with a solid tool like RegexBuddy, you are looking at handling any complex text record parsing situations, as well as getting results quickly. The tool makes it real easy.

Hope that helps.

Passing parameters to a JDBC PreparedStatement

The problem was that you needed to add " ' ;" at the end.

(XML) The markup in the document following the root element must be well-formed. Start location: 6:2

After insuring that the string "strOutput" has a correct XML structure, you can do this:

Matcher junkMatcher = (Pattern.compile("^([\\W]+)<")).matcher(strOutput);
strOutput = junkMatcher.replaceFirst("<");

Nested attributes unpermitted parameters

Seems there is a change in handling of attribute protection and now you must whitelist params in the controller (instead of attr_accessible in the model) because the former optional gem strong_parameters became part of the Rails Core.

This should look something like this:

class PeopleController < ActionController::Base
  def create
    Person.create(person_params)
  end

private
  def person_params
    params.require(:person).permit(:name, :age)
  end
end

So params.require(:model).permit(:fields) would be used

and for nested attributes something like

params.require(:person).permit(:name, :age, pets_attributes: [:id, :name, :category])

Some more details can be found in the Ruby edge API docs and strong_parameters on github or here

How can I show data using a modal when clicking a table row (using bootstrap)?

The best practice is to ajax load the order information when click tr tag, and render the information html in $('#orderDetails') like this:

  $.get('the_get_order_info_url', { order_id: the_id_var }, function(data){
    $('#orderDetails').html(data);
  }, 'script')

Alternatively, you can add class for each td that contains the order info, and use jQuery method $('.class').html(html_string) to insert specific order info into your #orderDetails BEFORE you show the modal, like:

  <% @restaurant.orders.each do |order| %>
  <!-- you should add more class and id attr to help control the DOM -->
  <tr id="order_<%= order.id %>" onclick="orderModal(<%= order.id  %>);">
    <td class="order_id"><%= order.id %></td>
    <td class="customer_id"><%= order.customer_id %></td>
    <td class="status"><%= order.status %></td>
  </tr>
  <% end %>

js:

function orderModal(order_id){
  var tr = $('#order_' + order_id);
  // get the current info in html table 
  var customer_id = tr.find('.customer_id');
  var status = tr.find('.status');

  // U should work on lines here:
  var info_to_insert = "order: " + order_id + ", customer: " + customer_id + " and status : " + status + ".";
  $('#orderDetails').html(info_to_insert);

  $('#orderModal').modal({
    keyboard: true,
    backdrop: "static"
  });
};

That's it. But I strongly recommend you to learn sth about ajax on Rails. It's pretty cool and efficient.

Maintain the aspect ratio of a div with CSS

You can achieve that by using SVG.

It depends on a case, but in some it is really usefull. As an example - you can set background-image without setting fixed height or use it to embed youtube <iframe> with ratio 16:9 and position:absolute etc.

For 3:2 ratio set viewBox="0 0 3 2" and so on.

Example:

_x000D_
_x000D_
div{_x000D_
    background-color:red_x000D_
}_x000D_
svg{_x000D_
    width:100%;_x000D_
    display:block;_x000D_
    visibility:hidden_x000D_
}_x000D_
_x000D_
.demo-1{width:35%}_x000D_
.demo-2{width:20%}
_x000D_
<div class="demo-1">_x000D_
  <svg viewBox="0 0 3 2"></svg>_x000D_
</div>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<div class="demo-2">_x000D_
  <svg viewBox="0 0 3 2"></svg>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I make a checkbox readonly? not disabled?

You can easily do this by css. HTML :

<form id="aform" name="aform" method="POST">
    <input name="chkBox_1" type="checkbox" checked value="1" readonly />
    <br/>
    <input name="chkBox_2" type="checkbox" value="1" readonly />
    <br/>
    <input id="submitBttn" type="button" value="Submit">
</form>

CSS :

input[type="checkbox"][readonly] {
  pointer-events: none;
}

Demo

How to use Object.values with typescript?

Object.values() is part of ES2017, and the compile error you are getting is because you need to configure TS to use the ES2017 library. You are probably using ES6 or ES5 library in your current TS configuration.

Solution: use es2017 or es2017.object in your --lib compiler option.

For example, using tsconfig.json:

"compilerOptions": {
    "lib": ["es2017", "dom"]
}

Note that targeting ES2017 with TypeScript does not emit polyfills in the browser for ES2017 (meaning the above solves your compile error, but you can still encounter a runtime error because the browser doesn't implement ES2017 Object.values), it's up to you to polyfill your project code yourself if you want. And since Object.values is not yet well supported by all browsers (at the time of this writing) you definitely want a polyfill: core-js will do the job.

How do you rebase the current branch's changes on top of changes being merged in?

You've got what rebase does backwards. git rebase master does what you're asking for — takes the changes on the current branch (since its divergence from master) and replays them on top of master, then sets the head of the current branch to be the head of that new history. It doesn't replay the changes from master on top of the current branch.

sys.argv[1], IndexError: list index out of range

sys.argv is the list of command line arguments passed to a Python script, where sys.argv[0] is the script name itself.

It is erroring out because you are not passing any commandline argument, and thus sys.argv has length 1 and so sys.argv[1] is out of bounds.

To "fix", just make sure to pass a commandline argument when you run the script, e.g.

python ConcatenateFiles.py /the/path/to/the/directory

However, you likely wanted to use some default directory so it will still work when you don't pass in a directory:

cur_dir = sys.argv[1] if len(sys.argv) > 1 else '.'

with open(cur_dir + '/Concatenated.csv', 'w+') as outfile:

    try:
        with open(cur_dir + '/MatrixHeader.csv') as headerfile:
            for line in headerfile:
                outfile.write(line + '\n')
    except:
        print 'No Header File'

How to start debug mode from command prompt for apache tomcat server?

There are two ways to run tomcat in debug mode

  1. Using jdpa run

  2. Using JAVA_OPTS

First setup the environment. Then start the server using following commands.

_x000D_
_x000D_
export JPDA_ADDRESS=8000_x000D_
_x000D_
export JPDA_TRANSPORT=dt_socket_x000D_
_x000D_
%TOMCAT_HOME%/bin/catalina.sh jpda start_x000D_
_x000D_
sudo catalina.sh jpda start
_x000D_
_x000D_
_x000D_

refer this article for more information this is clearly define it

Deck of cards JAVA

There is something wrong with your design. Try to make your classes represent real world things. For example:

  • The class Card should represent one card, that is the nature of a "Card". The Card class does not need to know about Decks.
  • The Deck class should contain 52 Card objects (plus jokers?).

Can we call the function written in one JavaScript in another JS file?

Here's a more descriptive example with a CodePen snippet attached:

1.js

function fn1() {
  document.getElementById("result").innerHTML += "fn1 gets called";
}

2.js

function clickedTheButton() {
  fn1();
} 

index.html

<html>
  <head>
  </head>
  <body>
    <button onclick="clickedTheButton()">Click me</button>
    <script type="text/javascript" src="1.js"></script>
    <script type="text/javascript" src="2.js"></script>
  </body>
 </html>

output

Output. Button + Result

Try this CodePen snippet: link .

What to do about Eclipse's "No repository found containing: ..." error messages?

As Mauro said: "you have to remove and re-add the Eclipse Project Update site, so that its metadata are re-calculated." - works as workaround

bundle install fails with SSL certificate verification error

I get a slightly different error, though perhaps related, on Ubuntu 12.04:

Gem::RemoteFetcher::FetchError: SSL_connect returned=1 errno=0 state=unknown state: sslv3 alert handshake failure (https://d2chzxaqi4y7f8.cloudfront.net/gems/activesupport-3.2.3.gem)
An error occured while installing activesupport (3.2.3), and Bundler cannot continue.
Make sure that `gem install activesupport -v '3.2.3'` succeeds before bundling.

It happens when I run bundle install with source 'https://rubygems.org' in a Gemfile.

This is an issue with OpenSSL on Ubuntu 12.04. See Rubygems issue #319.

To fix this, run apt-get update && apt-get upgrade on Ubuntu 12.04 to upgrade your OpenSSL.

Prevent the keyboard from displaying on activity start

You can also write these lines of code in the direct parent layout of the .xml layout file in which you have the "problem":

android:focusable="true"
android:focusableInTouchMode="true"

For example:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    ...
    android:focusable="true"
    android:focusableInTouchMode="true" >

    <EditText
        android:id="@+id/myEditText"
        ...
        android:hint="@string/write_here" />

    <Button
        android:id="@+id/button_ok"
        ...
        android:text="@string/ok" />
</LinearLayout>


EDIT :

Example if the EditText is contained in another layout:

<?xml version="1.0" encoding="utf-8"?>
<ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    ... >                                            <!--not here-->

    ...    <!--other elements-->

    <LinearLayout
        android:id="@+id/theDirectParent"
        ...
        android:focusable="true"
        android:focusableInTouchMode="true" >        <!--here-->

        <EditText
            android:id="@+id/myEditText"
            ...
            android:hint="@string/write_here" />

        <Button
            android:id="@+id/button_ok"
            ...
            android:text="@string/ok" />
    </LinearLayout>

</ConstraintLayout>

The key is to make sure that the EditText is not directly focusable.
Bye! ;-)

Can't accept license agreement Android SDK Platform 24

you need to manually re-install sdk this help me: https://forum.ionicframework.com/t/you-have-not-accepted-the-license-agreements-of-the-following-sdk-component/69570/6

"android update sdk --no-ui --filter build-tools-24.0.0,android-24,extra-android-m2repository"

Correctly Parsing JSON in Swift 3

First of all never load data synchronously from a remote URL, use always asynchronous methods like URLSession.

'Any' has no subscript members

occurs because the compiler has no idea of what type the intermediate objects are (for example currently in ["currently"]!["temperature"]) and since you are using Foundation collection types like NSDictionary the compiler has no idea at all about the type.

Additionally in Swift 3 it's required to inform the compiler about the type of all subscripted objects.

You have to cast the result of the JSON serialization to the actual type.

This code uses URLSession and exclusively Swift native types

let urlString = "https://api.forecast.io/forecast/apiKey/37.5673776,122.048951"

let url = URL(string: urlString)
URLSession.shared.dataTask(with:url!) { (data, response, error) in
  if error != nil {
    print(error)
  } else {
    do {

      let parsedData = try JSONSerialization.jsonObject(with: data!) as! [String:Any]
      let currentConditions = parsedData["currently"] as! [String:Any]

      print(currentConditions)

      let currentTemperatureF = currentConditions["temperature"] as! Double
      print(currentTemperatureF)
    } catch let error as NSError {
      print(error)
    }
  }

}.resume()

To print all key / value pairs of currentConditions you could write

 let currentConditions = parsedData["currently"] as! [String:Any]

  for (key, value) in currentConditions {
    print("\(key) - \(value) ")
  }

A note regarding jsonObject(with data:

Many (it seems all) tutorials suggest .mutableContainers or .mutableLeaves options which is completely nonsense in Swift. The two options are legacy Objective-C options to assign the result to NSMutable... objects. In Swift any variable is mutable by default and passing any of those options and assigning the result to a let constant has no effect at all. Further most of the implementations are never mutating the deserialized JSON anyway.

The only (rare) option which is useful in Swift is .allowFragments which is required if if the JSON root object could be a value type(String, Number, Bool or null) rather than one of the collection types (array or dictionary). But normally omit the options parameter which means No options.

===========================================================================

Some general considerations to parse JSON

JSON is a well-arranged text format. It's very easy to read a JSON string. Read the string carefully. There are only six different types – two collection types and four value types.


The collection types are

  • Array - JSON: objects in square brackets [] - Swift: [Any] but in most cases [[String:Any]]
  • Dictionary - JSON: objects in curly braces {} - Swift: [String:Any]

The value types are

  • String - JSON: any value in double quotes "Foo", even "123"or "false" – Swift: String
  • Number - JSON: numeric values not in double quotes 123 or 123.0 – Swift: Int or Double
  • Bool - JSON: true or false not in double quotes – Swift: true or false
  • null - JSON: null – Swift: NSNull

According to the JSON specification all keys in dictionaries are required to be String.


Basically it's always recommeded to use optional bindings to unwrap optionals safely

If the root object is a dictionary ({}) cast the type to [String:Any]

if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [String:Any] { ...

and retrieve values by keys with (OneOfSupportedJSONTypes is either JSON collection or value type as described above.)

if let foo = parsedData["foo"] as? OneOfSupportedJSONTypes {
    print(foo)
} 

If the root object is an array ([]) cast the type to [[String:Any]]

if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]] { ...

and iterate through the array with

for item in parsedData {
    print(item)
}

If you need an item at specific index check also if the index exists

if let parsedData = try JSONSerialization.jsonObject(with: data!) as? [[String:Any]], parsedData.count > 2,
   let item = parsedData[2] as? OneOfSupportedJSONTypes {
      print(item)
    }
}

In the rare case that the JSON is simply one of the value types – rather than a collection type – you have to pass the .allowFragments option and cast the result to the appropriate value type for example

if let parsedData = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? String { ...

Apple has published a comprehensive article in the Swift Blog: Working with JSON in Swift


===========================================================================

In Swift 4+ the Codable protocol provides a more convenient way to parse JSON directly into structs / classes.

For example the given JSON sample in the question (slightly modified)

let jsonString = """
{"icon": "partly-cloudy-night", "precipProbability": 0, "pressure": 1015.39, "humidity": 0.75, "precip_intensity": 0, "wind_speed": 6.04, "summary": "Partly Cloudy", "ozone": 321.13, "temperature": 49.45, "dew_point": 41.75, "apparent_temperature": 47, "wind_bearing": 332, "cloud_cover": 0.28, "time": 1480846460}
"""

can be decoded into the struct Weather. The Swift types are the same as described above. There are a few additional options:

  • Strings representing an URL can be decoded directly as URL.
  • The time integer can be decoded as Date with the dateDecodingStrategy .secondsSince1970.
  • snaked_cased JSON keys can be converted to camelCase with the keyDecodingStrategy .convertFromSnakeCase

struct Weather: Decodable {
    let icon, summary: String
    let pressure: Double, humidity, windSpeed : Double
    let ozone, temperature, dewPoint, cloudCover: Double
    let precipProbability, precipIntensity, apparentTemperature, windBearing : Int
    let time: Date
}

let data = Data(jsonString.utf8)
do {
    let decoder = JSONDecoder()
    decoder.dateDecodingStrategy = .secondsSince1970
    decoder.keyDecodingStrategy = .convertFromSnakeCase
    let result = try decoder.decode(Weather.self, from: data)
    print(result)
} catch {
    print(error)
}

Other Codable sources:

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

Paying tribute to IgorBeaz, you need to stop running the current container. For that you are going to know current CONTAINER ID:

$ docker container ls

You get something like:

CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS                  NAMES
12a32e8928ef        friendlyhello       "python app.py"     51 seconds ago      Up 50 seconds       0.0.0.0:4000->80/tcp   romantic_tesla   

Then you stop the container by:

$ docker stop 12a32e8928ef

Finally you try to do what you wanted to do, for example:

$ docker run -p 4000:80 friendlyhello

How can the error 'Client found response content type of 'text/html'.. be interpreted

The webserver is returning an http 500 error code. These errors generally happen when an exception in thrown on the webserver and there's no logic to catch it so it spits out an http 500 error. You can usually resolve the problem by placing try-catch blocks in your code.

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

Close PHP Storm in terminal go to the project folder type

git rm -rf .idea; git commit -m "delete .idea"; git push;

Then go to project folder and delete the folder .idea

sudo rm -r .idea/

Start PhpStorm and you are done

If list index exists, do X

Do not let any space in front of your brackets.

Example:

n = input ()
         ^

Tip: You should add comments over and/or under your code. Not behind your code.


Have a nice day.

Section vs Article HTML5

Article and Section are both semantic elements of HTML5. Section is block level generic section of a webpage, but relevant to our webpage content. Article is also block level, but article refers to an individual blog post, a comment, of a webpage.

Both Article and Section should include an heading elements h2-h6.

For a blog post, use following syntax for article and section.

<article role="main">
         <h1>Heading 1</h1>
         <p>Article Description</p>
         <section id="sec1">
                <h2>Section Heading</h2>
                <p>Section Description</p>
         </section>
         <section id="sec2">
                <h2>Section Heading</h2>
                <p>Section Description</p>
         </section>
</article>

Removing fields from struct or hiding them in JSON Response

I also faced this problem, at first I just wanted to specialize the responses in my http handler. My first approach was creating a package that copies the information of a struct to another struct and then marshal that second struct. I did that package using reflection, so, never liked that approach and also I wasn't dynamically.

So I decided to modify the encoding/json package to do this. The functions Marshal, MarshalIndent and (Encoder) Encode additionally receives a

type F map[string]F

I wanted to simulate a JSON of the fields that are needed to marshal, so it only marshals the fields that are in the map.

https://github.com/JuanTorr/jsont

package main

import (
    "fmt"
    "log"
    "net/http"

    "github.com/JuanTorr/jsont"
)

type SearchResult struct {
    Date        string      `json:"date"`
    IdCompany   int         `json:"idCompany"`
    Company     string      `json:"company"`
    IdIndustry  interface{} `json:"idIndustry"`
    Industry    string      `json:"industry"`
    IdContinent interface{} `json:"idContinent"`
    Continent   string      `json:"continent"`
    IdCountry   interface{} `json:"idCountry"`
    Country     string      `json:"country"`
    IdState     interface{} `json:"idState"`
    State       string      `json:"state"`
    IdCity      interface{} `json:"idCity"`
    City        string      `json:"city"`
} //SearchResult

type SearchResults struct {
    NumberResults int            `json:"numberResults"`
    Results       []SearchResult `json:"results"`
} //type SearchResults
func main() {
    msg := SearchResults{
        NumberResults: 2,
        Results: []SearchResult{
            {
                Date:        "12-12-12",
                IdCompany:   1,
                Company:     "alfa",
                IdIndustry:  1,
                Industry:    "IT",
                IdContinent: 1,
                Continent:   "america",
                IdCountry:   1,
                Country:     "México",
                IdState:     1,
                State:       "CDMX",
                IdCity:      1,
                City:        "Atz",
            },
            {
                Date:        "12-12-12",
                IdCompany:   2,
                Company:     "beta",
                IdIndustry:  1,
                Industry:    "IT",
                IdContinent: 1,
                Continent:   "america",
                IdCountry:   2,
                Country:     "USA",
                IdState:     2,
                State:       "TX",
                IdCity:      2,
                City:        "XYZ",
            },
        },
    }
    fmt.Println(msg)
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {

        //{"numberResults":2,"results":[{"date":"12-12-12","idCompany":1,"idIndustry":1,"country":"México"},{"date":"12-12-12","idCompany":2,"idIndustry":1,"country":"USA"}]}
        err := jsont.NewEncoder(w).Encode(msg, jsont.F{
            "numberResults": nil,
            "results": jsont.F{
                "date":       nil,
                "idCompany":  nil,
                "idIndustry": nil,
                "country":    nil,
            },
        })
        if err != nil {
            log.Fatal(err)
        }
    })

    http.ListenAndServe(":3009", nil)
}

Visual Studio Code cannot detect installed git

Now you can configure Visual Studio Code (version 0.10.2, check for older versions) to use existing git installation.

Just add the path to the git executable in your Visual Studio Code settings (File -> Preferences -> Settings) like this:

{
    // Is git enabled
    "git.enabled": true,

    // Path to the git executable
    "git.path": "C:\\path\\to\\git.exe"

    // other settings
}

How to get a complete list of ticker symbols from Yahoo Finance?

Complete list of yahoo symbols/tickers/stocks is available for download(excel format) at below website. http://www.myinvestorshub.com/yahoo_stock_list.php

List updated to january 2016: http://investexcel.net/all-yahoo-finance-stock-tickers/

javascript code to check special characters

If you don't want to include any special character, then try this much simple way for checking special characters using RegExp \W Metacharacter.

var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
if(!(iChars.match(/\W/g)) == "") {
    alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
    return false;
}

Python WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect:

I had a similar issue while working with Jupyter. I was trying to copy files from one directory to another using copy function of shutil. The problem was that I had forgotten to import the package.(Silly) But instead of python giving import error, it gave this error.

Solved by adding:

from shutil import copy

Want to make Font Awesome icons clickable

I found this worked best for my usecase:

<i class="btn btn-light fa fa-dribbble fa-4x" href="#"></i>
<i class="btn btn-light fa fa-behance-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-linkedin-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-twitter-square fa-4x" href="#"></i>
<i class="btn btn-light fa fa-facebook-square fa-4x" href="#"></i>

What do hjust and vjust do when making a plot using ggplot?

The value of hjust and vjust are only defined between 0 and 1:

  • 0 means left-justified
  • 1 means right-justified

Source: ggplot2, Hadley Wickham, page 196

(Yes, I know that in most cases you can use it beyond this range, but don't expect it to behave in any specific way. This is outside spec.)

hjust controls horizontal justification and vjust controls vertical justification.

An example should make this clear:

td <- expand.grid(
    hjust=c(0, 0.5, 1),
    vjust=c(0, 0.5, 1),
    angle=c(0, 45, 90),
    text="text"
)

ggplot(td, aes(x=hjust, y=vjust)) + 
    geom_point() +
    geom_text(aes(label=text, angle=angle, hjust=hjust, vjust=vjust)) + 
    facet_grid(~angle) +
    scale_x_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2)) +
    scale_y_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2))

enter image description here


To understand what happens when you change the hjust in axis text, you need to understand that the horizontal alignment for axis text is defined in relation not to the x-axis, but to the entire plot (where this includes the y-axis text). (This is, in my view, unfortunate. It would be much more useful to have the alignment relative to the axis.)

DF <- data.frame(x=LETTERS[1:3],y=1:3)
p <- ggplot(DF, aes(x,y)) + geom_point() + 
    ylab("Very long label for y") +
    theme(axis.title.y=element_text(angle=0))


p1 <- p + theme(axis.title.x=element_text(hjust=0)) + xlab("X-axis at hjust=0")
p2 <- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab("X-axis at hjust=0.5")
p3 <- p + theme(axis.title.x=element_text(hjust=1)) + xlab("X-axis at hjust=1")

library(ggExtra)
align.plots(p1, p2, p3)

enter image description here


To explore what happens with vjust aligment of axis labels:

DF <- data.frame(x=c("a\na","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p1 <- p + theme(axis.text.x=element_text(vjust=0, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0")
p2 <- p + theme(axis.text.x=element_text(vjust=0.5, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0.5")
p3 <- p + theme(axis.text.x=element_text(vjust=1, colour="red")) + 
        xlab("X-axis labels aligned with vjust=1")


library(ggExtra)
align.plots(p1, p2, p3)

enter image description here

Read large files in Java

You can consider using memory-mapped files, via FileChannels .

Generally a lot faster for large files. There are performance trade-offs that could make it slower, so YMMV.

Related answer: Java NIO FileChannel versus FileOutputstream performance / usefulness

What is Ruby's double-colon `::`?

What good is scope (private, protected) if you can just use :: to expose anything?

In Ruby, everything is exposed and everything can be modified from anywhere else.

If you're worried about the fact that classes can be changed from outside the "class definition", then Ruby probably isn't for you.

On the other hand, if you're frustrated by Java's classes being locked down, then Ruby is probably what you're looking for.

Constructing pandas DataFrame from values in variables gives "ValueError: If using all scalar values, you must pass an index"

If you intend to convert a dictionary of scalars, you have to include an index:

import pandas as pd

alphabets = {'A': 'a', 'B': 'b'}
index = [0]
alphabets_df = pd.DataFrame(alphabets, index=index)
print(alphabets_df)

Although index is not required for a dictionary of lists, the same idea can be expanded to a dictionary of lists:

planets = {'planet': ['earth', 'mars', 'jupiter'], 'length_of_day': ['1', '1.03', '0.414']}
index = [0, 1, 2]
planets_df = pd.DataFrame(planets, index=index)
print(planets_df)

Of course, for the dictionary of lists, you can build the dataframe without an index:

planets_df = pd.DataFrame(planets)
print(planets_df)

What is the attribute property="og:title" inside meta tag?

A degree of control is possible over how information travels from a third-party website to Facebook when a page is shared (or liked, etc.). In order to make this possible, information is sent via Open Graph meta tags in the <head> part of the website’s code.

How can I add an item to a SelectList in ASP.net MVC

private SelectList AddFirstItem(SelectList list)
        {
            List<SelectListItem> _list = list.ToList();
            _list.Insert(0, new SelectListItem() { Value = "-1", Text = "This Is First Item" });
            return new SelectList((IEnumerable<SelectListItem>)_list, "Value", "Text");
        }

This Should do what you need ,just send your selectlist and it will return a select list with an item in index 0

You can custome the text,value or even the index of the item you need to insert

How to set an image's width and height without stretching it?

Load the image as a background for a div.

Instead of:

<img id='logo' src='picture.jpg'>

do

<div id='logo' style='background:url(picture.jpg)'></div>

All browsers will crop the part of the image that doesn't fit.
This has several advantages over wrapping it an element whose overflow is hidden:

  1. No extra markup. The div simply replaces the img.
  2. Easily center or set the image to another offset. eg. url(pic) center top;
  3. Repeat the image when small enough. (Ok, I don't know, why you would want that)
  4. Set a bg color in the same statement, easily apply the same image to multiple elements, and everything that applies to bg images.

Update: This answer is from before object-fit; you should now probably use object-fit/object-position.

It is still useful for older browsers, for extra properties (such as background-repeat), and for edge cases (For example, workaround Chrome bugs with flexbox and object-position and FF's (former?) issues with grid + autoheight + object-fit. Wrapper divs in grid / flexbox often give... unintuitive results.)

SET NAMES utf8 in MySQL?

It is needed whenever you want to send data to the server having characters that cannot be represented in pure ASCII, like 'ñ' or 'ö'.

That if the MySQL instance is not configured to expect UTF-8 encoding by default from client connections (many are, depending on your location and platform.)

Read http://www.joelonsoftware.com/articles/Unicode.html in case you aren't aware how Unicode works.

Read Whether to use "SET NAMES" to see SET NAMES alternatives and what exactly is it about.

Convert datetime to valid JavaScript date

This works everywhere including Safari 5 and Firefox 5 on OS X.

UPDATE: Fx Quantum (54) has no need for the replace, but Safari 11 is still not happy unless you convert as below

_x000D_
_x000D_
var date_test = new Date("2011-07-14 11:23:00".replace(/-/g,"/"));_x000D_
console.log(date_test);
_x000D_
_x000D_
_x000D_


FIDDLE

System.Runtime.InteropServices.COMException (0x800A03EC)

Some googling reveals that potentially you've got a corrupt file:

http://bitterolives.blogspot.com/2009/03/excel-interop-comexception-hresult.html

and that you can tell excel to open it anyway with the CorruptLoad parameter, with something like...

Workbook workbook = excelApplicationObject.Workbooks.Open(path, CorruptLoad: true);

Sql Server trigger insert values from new row into another table

You use an insert trigger - inside the trigger, inserted row items will be exposed as a logical table INSERTED, which has the same column layout as the table the trigger is defined on.

Delete triggers have access to a similar logical table called DELETED.

Update triggers have access to both an INSERTED table that contains the updated values and a DELETED table that contains the values to be updated.

How to git commit a single file/directory

Try:

git commit -m 'my notes' path/to/my/file.ext 

Merge two Excel tables Based on matching data in Columns

Put the table in the second image on Sheet2, columns D to F.

In Sheet1, cell D2 use the formula

=iferror(vlookup($A2,Sheet2!$D$1:$F$100,column(A1),false),"")

copy across and down.

Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.

enter image description here

How to remove all null elements from a ArrayList or String Array?

Pre-Java 8 you should use:

tourists.removeAll(Collections.singleton(null));

Post-Java 8 use:

tourists.removeIf(Objects::isNull);

The reason here is time complexity. The problem with arrays is that a remove operation can take O(n) time to complete. Really in Java this is an array copy of the remaining elements being moved to replace the empty spot. Many other solutions offered here will trigger this issue. The former is technically O(n*m) where m is 1 because it's a singleton null: so O(n)

You should removeAll of the singleton, internally it does a batchRemove() which has a read position and a write position. And iterates the list. When it hits a null, it simply iterates the read position by 1. When they are the same it passes, when they are different it keeps moving along copying the values. Then at the end it trims to size.

It effectively does this internally:

public static <E> void removeNulls(ArrayList<E> list) {
    int size = list.size();
    int read = 0;
    int write = 0;
    for (; read < size; read++) {
        E element = list.get(read);
        if (element == null) continue;
        if (read != write) list.set(write, element);
        write++;
    }
    if (write != size) {
        list.subList(write, size).clear();
    }
}

Which you can explicitly see is an O(n) operation.

The only thing that could ever be faster is if you iterated the list from both ends, and when you found a null, you set its value equal to the value you found at the end, and decremented that value. And iterated until the two values matched. You'd mess up the order, but would vastly reduce the number of values you set vs. ones you left alone. Which is a good method to know but won't help much here as .set() is basically free, but that form of delete is a useful tool for your belt.


for (Iterator<Tourist> itr = tourists.iterator(); itr.hasNext();) {
      if (itr.next() == null) { itr.remove(); }
 }

While this seems reasonable enough, the .remove() on the iterator internally calls:

ArrayList.this.remove(lastRet);

Which is again the O(n) operation within the remove. It does an System.arraycopy() which is again not what you want, if you care about speed. This makes it n^2.

There's also:

while(tourists.remove(null));

Which is O(m*n^2). Here we not only iterate the list. We reiterate the entire list, each time we match the null. Then we do n/2 (average) operations to do the System.arraycopy() to perform the remove. You could quite literally, sort the entire collection between items with values and items with null values and trim the ending in less time. In fact, that's true for all the broken ones. At least in theory, the actual system.arraycopy isn't actually an N operation in practice. In theory, theory and practice are the same thing; in practice they aren't.

New line character in VB.Net?

you can solve that problem in visual basic .net without concatenating your text, you can use this as a return type of your overloaded Tostring:

System.Text.RegularExpressions.Regex.Unescape(String.format("FirstName:{0} \r\n LastName: {1}", "Nordanne", "Isahac"))

How to get text and a variable in a messagebox

Why not use:

Dim msg as String = String.Format("Variable = {0}", variable)

More info on String.Format

HashMap: One Key, multiple Values

A standard Java HashMap cannot store multiple values per key, any new entry you add will overwrite the previous one.

How to write one new line in Bitbucket markdown?

On Github, <p> and <br/>solves the problem.

<p>I want to this to appear in a new line. Introduces extra line above

or

<br/> another way

how to do file upload using jquery serialization

HTML5 introduces FormData class that can be used to file upload with ajax.

FormData support starts from following desktop browsers versions. IE 10+, Firefox 4.0+, Chrome 7+, Safari 5+, Opera 12+

FormData - Mozilla.org

Does an HTTP Status code of 0 have any meaning?

Short Answer

It's not a HTTP response code, but it is documented by WhatWG as a valid value for the status attribute of an XMLHttpRequest or a Fetch response.

Broadly speaking, it is a default value used when there is no real HTTP status code to report and/or an error occurred sending the request or receiving the response. Possible scenarios where this is the case include, but are not limited to:

  • The request hasn't yet been sent, or was aborted.
  • The browser is still waiting to receive the response status and headers.
  • The connection dropped during the request.
  • The request timed out.
  • The request encountered an infinite redirect loop.
  • The browser knows the response status, but you're not allowed to access it due to security restrictions related to the Same-origin Policy.

Long Answer

First, to reiterate: 0 is not a HTTP status code. There's a complete list of them in RFC 7231 Section 6.1, that doesn't include 0, and the intro to section 6 states clearly that

The status-code element is a three-digit integer code

which 0 is not.

However, 0 as a value of the .status attribute of an XMLHttpRequest object is documented, although it's a little tricky to track down all the relevant details. We begin at https://xhr.spec.whatwg.org/#the-status-attribute, documenting the .status attribute, which simply states:

The status attribute must return the response’s status.

That may sound vacuous and tautological, but in reality there is information here! Remember that this documentation is talking here about the .response attribute of an XMLHttpRequest, not a response, so this tells us that the definition of the status on an XHR object is deferred to the definition of a response's status in the Fetch spec.

But what response object? What if we haven't actually received a response yet? The inline link on the word "response" takes us to https://xhr.spec.whatwg.org/#response, which explains:

An XMLHttpRequest has an associated response. Unless stated otherwise it is a network error.

So the response whose status we're getting is by default a network error. And by searching for everywhere the phrase "set response to" is used in the XHR spec, we can see that it's set in five places:

Looking in the Fetch standard, we can see that:

A network error is a response whose status is always 0

so we can immediately tell that we'll see a status of 0 on an XHR object in any of the cases where the XHR spec says the response should be set to a network error. (Interestingly, this includes the case where the body's stream gets "errored", which the Fetch spec tells us can happen during parsing the body after having received the status - so in theory I suppose it is possible for an XHR object to have its status set to 200, then encounter an out-of-memory error or something while receiving the body and so change its status back to 0.)

We also note in the Fetch standard that a couple of other response types exist whose status is defined to be 0, whose existence relates to cross-origin requests and the same-origin policy:

An opaque filtered response is a filtered response whose ... status is 0...

An opaque-redirect filtered response is a filtered response whose ... status is 0...

(various other details about these two response types omitted).

But beyond these, there are also many cases where the Fetch algorithm (rather than the XHR spec, which we've already looked at) calls for the browser to return a network error! Indeed, the phrase "return a network error" appears 40 times in the Fetch standard. I will not try to list all 40 here, but I note that they include:

  • The case where the request's scheme is unrecognised (e.g. trying to send a request to madeupscheme://foobar.com)
  • The wonderfully vague instruction "When in doubt, return a network error." in the algorithms for handling ftp:// and file:// URLs
  • Infinite redirects: "If request’s redirect count is twenty, return a network error."
  • A bunch of CORS-related issues, such as "If httpRequest’s response tainting is not "cors" and the cross-origin resource policy check with request and response returns blocked, then return a network error."
  • Connection failures: "If connection is failure, return a network error."

In other words: whenever something goes wrong other than getting a real HTTP error status code like a 500 or 400 from the server, you end up with a status attribute of 0 on your XHR object or Fetch response object in the browser. The number of possible specific causes enumerated in spec is vast.

Finally: if you're interested in the history of the spec for some reason, note that this answer was completely rewritten in 2020, and that you may be interested in the previous revision of this answer, which parsed essentially the same conclusions out of the older (and much simpler) W3 spec for XHR, before these were replaced by the more modern and more complicated WhatWG specs this answers refers to.

AngularJS check if form is valid in controller

Here is another solution

Set a hidden scope variable in your html then you can use it from your controller:

<span style="display:none" >{{ formValid = myForm.$valid}}</span>

Here is the full working example:

_x000D_
_x000D_
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
  $scope.userType = 'guest';_x000D_
  $scope.formValid = false;_x000D_
  console.info('Ctrl init, no form.');_x000D_
  _x000D_
  $scope.$watch('myForm', function() {_x000D_
    console.info('myForm watch');_x000D_
    console.log($scope.formValid);_x000D_
  });_x000D_
  _x000D_
  $scope.isFormValid = function() {_x000D_
    //test the new scope variable_x000D_
    console.log('form valid?: ', $scope.formValid);_x000D_
  };_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
  userType: <input name="input" ng-model="userType" required>_x000D_
  <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
  <tt>userType = {{userType}}</tt><br>_x000D_
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
  _x000D_
  _x000D_
  /*-- Hidden Variable formValid to use in your controller --*/_x000D_
  <span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
  _x000D_
  _x000D_
  <br/>_x000D_
  <button ng-click="isFormValid()">Check Valid</button>_x000D_
 </form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Serialize object to query string in JavaScript/jQuery

You want $.param(): http://api.jquery.com/jQuery.param/

Specifically, you want this:

var data = { one: 'first', two: 'second' };
var result = $.param(data);

When given something like this:

{a: 1, b : 23, c : "te!@#st"}

$.param will return this:

a=1&b=23&c=te!%40%23st

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

You can't, as far as I know, make the entire OS understand an http:+domain URL. You can only register new schemes (I use x-darkslide: in my app). If the app is installed, Mobile Safari will launch the app correctly.

However, you would have to handle the case where the app isn't installed with a "Still here? Click this link to download the app from iTunes." in your web page.

How to use a FolderBrowserDialog from a WPF application

//add a reference to System.Windows.Forms.dll

public partial class MainWindow : Window, System.Windows.Forms.IWin32Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void button_Click(object sender, RoutedEventArgs e)
    {
        var fbd = new FolderBrowserDialog();
        fbd.ShowDialog(this);
    }

    IntPtr System.Windows.Forms.IWin32Window.Handle
    {
        get
        {
            return ((HwndSource)PresentationSource.FromVisual(this)).Handle;
        }
    }
}

How to avoid page refresh after button click event in asp.net

I had the same problem with a button doing a page refresh before doing the actual button_click event (so the button had to be clicked twice). This behavior happened after a server.transfer-command (server.transfer("testpage.aspx").

In this case, the solution was to replace the server.transfer-command with response-redirect (response.redirect("testpage.aspx").

For details on the differences between the two commands, see Server.Transfer Vs. Response.Redirect

How to display special characters in PHP

You can have a mix of PHP and HTML in your PHP files... just do something like this...

<?php
$string = htmlentities("Résumé");
?>

<html>
<head></head>
<body>
<p><?= $string ?></p>
</body>
</html>

That should output Résumé just how you want it to.

If you don't have short tags enabled, replace the <?= $string ?> with <?php echo $string; ?>

How to update a record using sequelize for node?

I have used sequelize.js, node.js and transaction in below code and added proper error handling if it doesn't find data it will throw error that no data found with that id

editLocale: async (req, res) => {

    sequelize.sequelize.transaction(async (t1) => {

        if (!req.body.id) {
            logger.warn(error.MANDATORY_FIELDS);
            return res.status(500).send(error.MANDATORY_FIELDS);
        }

        let id = req.body.id;

        let checkLocale= await sequelize.Locale.findOne({
            where: {
                id : req.body.id
            }
        });

        checkLocale = checkLocale.get();
        if (checkLocale ) {
            let Locale= await sequelize.Locale.update(req.body, {
                where: {
                    id: id
                }
            });

            let result = error.OK;
            result.data = Locale;

            logger.info(result);
            return res.status(200).send(result);
        }
        else {
            logger.warn(error.DATA_NOT_FOUND);
            return res.status(404).send(error.DATA_NOT_FOUND);
        }
    }).catch(function (err) {
        logger.error(err);
        return res.status(500).send(error.SERVER_ERROR);
    });
},

Cloning an array in Javascript/Typescript

Cloning Arrays and Objects in javascript have a different syntax. Sooner or later everyone learns the difference the hard way and end up here.

In Typescript and ES6 you can use the spread operator for array and object:

const myClonedArray  = [...myArray];  // This is ok for [1,2,'test','bla']
                                      // But wont work for [{a:1}, {b:2}]. 
                                      // A bug will occur when you 
                                      // modify the clone and you expect the 
                                      // original not to be modified.
                                      // The solution is to do a deep copy
                                      // when you are cloning an array of objects.

To do a deep copy of an object you need an external library:

import {cloneDeep} from 'lodash';
const myClonedArray = cloneDeep(myArray);     // This works for [{a:1}, {b:2}]

The spread operator works on object as well but it will only do a shallow copy (first layer of children)

const myShallowClonedObject = {...myObject};   // Will do a shallow copy
                                               // and cause you an un expected bug.

To do a deep copy of an object you need an external library:

 import {cloneDeep} from 'lodash';
 const deeplyClonedObject = cloneDeep(myObject);   // This works for [{a:{b:2}}]

What is the difference between Task.Run() and Task.Factory.StartNew()

People already mentioned that

Task.Run(A);

Is equivalent to

Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);

But no one mentioned that

Task.Factory.StartNew(A);

Is equivalent to:

Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Current);

As you can see two parameters are different for Task.Run and Task.Factory.StartNew:

  1. TaskCreationOptions - Task.Run uses TaskCreationOptions.DenyChildAttach which means that children tasks can not be attached to the parent, consider this:

    var parentTask = Task.Run(() =>
    {
        var childTask = new Task(() =>
        {
            Thread.Sleep(10000);
            Console.WriteLine("Child task finished.");
        }, TaskCreationOptions.AttachedToParent);
        childTask.Start();
    
        Console.WriteLine("Parent task finished.");
    });
    
    parentTask.Wait();
    Console.WriteLine("Main thread finished.");
    

    When we invoke parentTask.Wait(), childTask will not be awaited, even though we specified TaskCreationOptions.AttachedToParent for it, this is because TaskCreationOptions.DenyChildAttach forbids children to attach to it. If you run the same code with Task.Factory.StartNew instead of Task.Run, parentTask.Wait() will wait for childTask because Task.Factory.StartNew uses TaskCreationOptions.None

  2. TaskScheduler - Task.Run uses TaskScheduler.Default which means that the default task scheduler (the one that runs tasks on Thread Pool) will always be used to run tasks. Task.Factory.StartNew on the other hand uses TaskScheduler.Current which means scheduler of the current thread, it might be TaskScheduler.Default but not always. In fact when developing Winforms or WPF applications it is required to update UI from the current thread, to do this people use TaskScheduler.FromCurrentSynchronizationContext() task scheduler, if you unintentionally create another long running task inside task that used TaskScheduler.FromCurrentSynchronizationContext() scheduler the UI will be frozen. A more detailed explanation of this can be found here

So generally if you are not using nested children task and always want your tasks to be executed on Thread Pool it is better to use Task.Run, unless you have some more complex scenarios.

Setting the number of map tasks and reduce tasks

Folks from this theory it seems we cannot run map reduce jobs in parallel.

Lets say I configured total 5 mapper jobs to run on particular node.Also I want to use this in such a way that JOB1 can use 3 mappers and JOB2 can use 2 mappers so that job can run in parallel. But above properties are ignored then how can execute jobs in parallel.

Capture the Screen into a Bitmap

// Use this version to capture the full extended desktop (i.e. multiple screens)

Bitmap screenshot = new Bitmap(SystemInformation.VirtualScreen.Width, 
                               SystemInformation.VirtualScreen.Height, 
                               PixelFormat.Format32bppArgb);
Graphics screenGraph = Graphics.FromImage(screenshot);
screenGraph.CopyFromScreen(SystemInformation.VirtualScreen.X, 
                           SystemInformation.VirtualScreen.Y, 
                           0, 
                           0, 
                           SystemInformation.VirtualScreen.Size, 
                           CopyPixelOperation.SourceCopy);

screenshot.Save("Screenshot.png", System.Drawing.Imaging.ImageFormat.Png);

Laravel migration table field's type change

For me the solution was just replace unsigned with index

This is the full code:

    Schema::create('champions_overview',function (Blueprint $table){
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('cid')->index();
        $table->longText('name');
    });


    Schema::create('champions_stats',function (Blueprint $table){
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->integer('championd_id')->index();
        $table->foreign('championd_id', 'ch_id')->references('cid')->on('champions_overview');
    });

How to create a popup window (PopupWindow) in Android

are you done with the layout inflating? maybe you can try this!!

View myPoppyView = pw.getContentView();
Button myBelovedButton = (Button)myPoppyView.findViewById(R.id.my_beloved_button);
//do something with my beloved button? :p

What's the difference between an argument and a parameter?

Simple Explanations without code

A "parameter" is a very general, broad thing, but an "argument: is a very specific, concrete thing. This is best illustrated via everyday examples:

Example 1: Vending Machines - Money is the parameter, $2.00 is the argument

Most machines take an input and return an output. For example a vending machine takes as an input: money, and returns: fizzy drinks as the output. In that particular case, it accepts as a parameter: money.

What then is the argument? Well if I put $2.00 into the machine, then the argument is: $2.00 - it is the very specific input used.

Example 2: Cars - Petrol is the parameter

Let's consider a car: they accept petrol (unleaded gasoline) as an input. It can be said that these machines accept parameters of type: petrol. The argument would be the exact and concrete input I put into my car. e.g. In my case, the argument would be: 40 litres of unleaded petrol/gasoline.

Example 3 - Elaboration on Arguments

An argument is a particular and specific example of an input. Suppose my machine takes a person as an input and turns them into someone who isn't a liar.

What then is an argument? The argument will be the particular person who is actually put into the machine. e.g. if Colin Powell is put into the machine then the argument would be Colin Powell.

So the parameter would be a person as an abstract concept, but the argument would always be a particular person with a particular name who is put into the machine. The argument is specific and concrete.

That's the difference. Simple.

Confused?

Post a comment and I'll fix up the explanation.

What is POCO in Entity Framework?

POCOs(Plain old CLR objects) are simply entities of your Domain. Normally when we use entity framework the entities are generated automatically for you. This is great but unfortunately these entities are interspersed with database access functionality which is clearly against the SOC (Separation of concern). POCOs are simple entities without any data access functionality but still gives the capabilities all EntityObject functionalities like

  • Lazy loading
  • Change tracking

Here is a good start for this

POCO Entity framework

You can also generate POCOs so easily from your existing Entity framework project using Code generators.

EF 5.X DbContext code generator

File Upload to HTTP server in iphone programming

ASIHTTPRequest is a great wrapper around the network APIs and makes it very easy to upload a file. Here's their example (but you can do this on the iPhone too - we save images to "disk" and later upload them.

ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[request setPostValue:@"Ben" forKey:@"first_name"];
[request setPostValue:@"Copsey" forKey:@"last_name"];
[request setFile:@"/Users/ben/Desktop/ben.jpg" forKey:@"photo"];

Converting JSON data to Java object

HashMap keyArrayList = new HashMap();
Iterator itr = yourJson.keys();
while (itr.hasNext())
{
    String key = (String) itr.next();
    keyArrayList.put(key, yourJson.get(key).toString());
}

How to concat two ArrayLists?

add one ArrayList to second ArrayList as:

Arraylist1.addAll(Arraylist2);

EDIT : if you want to Create new ArrayList from two existing ArrayList then do as:

ArrayList<String> arraylist3=new ArrayList<String>();

arraylist3.addAll(Arraylist1); // add first arraylist

arraylist3.addAll(Arraylist2); // add Second arraylist

Regular Expressions: Is there an AND operator?

The order is always implied in the structure of the regular expression. To accomplish what you want, you'll have to match the input string multiple times against different expressions.

What you want to do is not possible with a single regexp.

What is the most efficient way to store a list in the Django models?

"Premature optimization is the root of all evil."

With that firmly in mind, let's do this! Once your apps hit a certain point, denormalizing data is very common. Done correctly, it can save numerous expensive database lookups at the cost of a little more housekeeping.

To return a list of friend names we'll need to create a custom Django Field class that will return a list when accessed.

David Cramer posted a guide to creating a SeperatedValueField on his blog. Here is the code:

from django.db import models

class SeparatedValuesField(models.TextField):
    __metaclass__ = models.SubfieldBase

    def __init__(self, *args, **kwargs):
        self.token = kwargs.pop('token', ',')
        super(SeparatedValuesField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if not value: return
        if isinstance(value, list):
            return value
        return value.split(self.token)

    def get_db_prep_value(self, value):
        if not value: return
        assert(isinstance(value, list) or isinstance(value, tuple))
        return self.token.join([unicode(s) for s in value])

    def value_to_string(self, obj):
        value = self._get_val_from_obj(obj)
        return self.get_db_prep_value(value)

The logic of this code deals with serializing and deserializing values from the database to Python and vice versa. Now you can easily import and use our custom field in the model class:

from django.db import models
from custom.fields import SeparatedValuesField 

class Person(models.Model):
    name = models.CharField(max_length=64)
    friends = SeparatedValuesField()

Set Windows process (or user) memory limit

Use Windows Job Objects. Jobs are like process groups and can limit memory usage and process priority.

Pass Multiple Parameters to jQuery ajax call

Its all about data which you pass; has to properly formatted string. If you are passing empty data then data: {} will work. However with multiple parameters it has to be properly formatted e.g.

var dataParam = '{' + '"data1Variable": "' + data1Value+ '", "data2Variable": "' + data2Value+ '"' +  '}';

....

data : dataParam

...

Best way to understand is have error handler with proper message parameter, so as to know the detailed errors.

using "if" and "else" Stored Procedures MySQL

you can use CASE WHEN as follow as achieve the as IF ELSE.

SELECT FROM A a 
LEFT JOIN B b 
ON a.col1 = b.col1 
AND (CASE 
        WHEN a.col2 like '0%' then TRIM(LEADING '0' FROM a.col2)
        ELSE substring(a.col2,1,2)
    END
)=b.col2; 

p.s:just in case somebody needs this way.

What does localhost:8080 mean?

http: //localhost:8080/web

Where

  • localhost ( hostname ) is the machine name or IP address of the host server e.g Glassfish, Tomcat.
  • 8080 ( port ) is the address of the port on which the host server is listening for requests.

http ://localhost/web

Where

  • localhost ( hostname ) is the machine name or IP address of the host server e.g Glassfish, Tomcat.
  • host server listening to default port 80.

Creating a chart in Excel that ignores #N/A or blank cells

Please note that when plotting a line chart, using =NA() (output #N/A) to avoid plotting non existing values will only work for the ends of each series, first and last values. Any #N/A in between two other values will be ignored and bridged.

Example Plot Here

VIM Disable Automatic Newline At End Of File

Add the following command to your .vimrc to turn of the end-of-line option:

autocmd FileType php setlocal noeol binary fileformat=dos

However, PHP itself will ignore that last end-of-line - it shouldn't be an issue. I am almost certain that in your case there is something else which is adding the last newline character, or possibly there is a mixup with windows/unix line ending types (\n or \r\n, etc).

Update:

An alternative solution might be to just add this line to your .vimrc:

set fileformats+=dos

Open a URL in a new tab (and not a new window)

JQuery

$('<a />',{'href': url, 'target': '_blank'}).get(0).click();

JS

Object.assign(document.createElement('a'), { target: '_blank', href: 'URL_HERE'}).click();

How to get Spinner value?

The Spinner should fire an "OnItemSelected" event when something is selected:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
        Object item = parent.getItemAtPosition(pos);
    }
    public void onNothingSelected(AdapterView<?> parent) {
    }
});

AngularJS - Building a dynamic table based on a json

TGrid is another option that people don't usually find in a google search. If the other grids you find don't suit your needs, you can give it a try, its free

Append to string variable

var str1 = 'abc';
var str2 = str1+' def'; // str2 is now 'abc def'

Groovy write to file (newline)

As @Steven points out, a better way would be:

public void writeToFile(def directory, def fileName, def extension, def infoList) {
  new File("$directory/$fileName$extension").withWriter { out ->
    infoList.each {
      out.println it
    }
  }
}

As this handles the line separator for you, and handles closing the writer as well

(and doesn't open and close the file each time you write a line, which could be slow in your original version)

Trigger to fire only if a condition is met in SQL Server

How about this?

CREATE TRIGGER 
[dbo].[SystemParameterInsertUpdate]
ON 
[dbo].[SystemParameter]
FOR INSERT, UPDATE 
AS
BEGIN
SET NOCOUNT ON
  IF (LEFT((SELECT Attribute FROM INSERTED), 7) <> 'NoHist_') 
  BEGIN
      INSERT INTO SystemParameterHistory 
      (
        Attribute,
        ParameterValue,
        ParameterDescription,
        ChangeDate
      )
    SELECT
      Attribute,
      ParameterValue,
      ParameterDescription,
      ChangeDate
   FROM Inserted AS I
END
END

How do I check if a PowerShell module is installed?

When I use a non-default modules in my scripts I call the function below. Beside the module name you can provide a minimum version.

# See https://www.powershellgallery.com/ for module and version info
Function Install-ModuleIfNotInstalled(
    [string] [Parameter(Mandatory = $true)] $moduleName,
    [string] $minimalVersion
) {
    $module = Get-Module -Name $moduleName -ListAvailable |`
        Where-Object { $null -eq $minimalVersion -or $minimalVersion -ge $_.Version } |`
        Select-Object -Last 1
    if ($null -ne $module) {
         Write-Verbose ('Module {0} (v{1}) is available.' -f $moduleName, $module.Version)
    }
    else {
        Import-Module -Name 'PowershellGet'
        $installedModule = Get-InstalledModule -Name $moduleName -ErrorAction SilentlyContinue
        if ($null -ne $installedModule) {
            Write-Verbose ('Module [{0}] (v {1}) is installed.' -f $moduleName, $installedModule.Version)
        }
        if ($null -eq $installedModule -or ($null -ne $minimalVersion -and $installedModule.Version -lt $minimalVersion)) {
            Write-Verbose ('Module {0} min.vers {1}: not installed; check if nuget v2.8.5.201 or later is installed.' -f $moduleName, $minimalVersion)
            #First check if package provider NuGet is installed. Incase an older version is installed the required version is installed explicitly
            if ((Get-PackageProvider -Name NuGet -Force).Version -lt '2.8.5.201') {
                Write-Warning ('Module {0} min.vers {1}: Install nuget!' -f $moduleName, $minimalVersion)
                Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Scope CurrentUser -Force
            }        
            $optionalArgs = New-Object -TypeName Hashtable
            if ($null -ne $minimalVersion) {
                $optionalArgs['RequiredVersion'] = $minimalVersion
            }  
            Write-Warning ('Install module {0} (version [{1}]) within scope of the current user.' -f $moduleName, $minimalVersion)
            Install-Module -Name $moduleName @optionalArgs -Scope CurrentUser -Force -Verbose
        } 
    }
}

usage example:

Install-ModuleIfNotInstalled 'CosmosDB' '2.1.3.528'

Please let me known if it's usefull (or not)

Java creating .jar file

In order to create a .jar file, you need to use jar instead of java:

jar cf myJar.jar myClass.class

Additionally, if you want to make it executable, you need to indicate an entry point (i.e., a class with public static void main(String[] args)) for your application. This is usually accomplished by creating a manifest file that contains the Main-Class header (e.g., Main-Class: myClass).

However, as Mark Peters pointed out, with JDK 6, you can use the e option to define the entry point:

jar cfe myJar.jar myClass myClass.class 

Finally, you can execute it:

java -jar myJar.jar

See also

Concat strings by & and + in VB.Net

As your question confirms, they are different: & is ONLY string concatenation, + is overloaded with both normal addition and concatenation.

In your example:

  • because one of the operands to + is an integer VB attempts to convert the string to a integer, and as your string is not numeric it throws; and

  • & only works with strings so the integer is converted to a string.

npm install gives error "can't find a package.json file"

node comes with npm installed so you should have a version of npm, however npm gets updated more frequently than node does, so you'll want to make sure it's the latest version.

sudo npm install npm -g

Test: Run npm -v. The version should be higher than 2.1.8.

npm install

THAT'S IT!

https://www.youtube.com/watch?v=wREima9e6vk

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65

Should always start with the simplest first, after wasting hours and days on this error.

And after an extensive amount of research,

Simply

RESTART YOUR MACHINE

This resolved this error.

I'm on

react-native-cli: 2.0.1
react-native: 0.63.3

Difference between $.ajax() and $.get() and $.load()

Important note : jQuery.load() method can do not only GET but also POST requests, if data parameter is supplied (see: http://api.jquery.com/load/)

data Type: PlainObject or String A plain object or string that is sent to the server with the request.

Request Method The POST method is used if data is provided as an object; otherwise, GET is assumed.

Example: pass arrays of data to the server (POST request)
$( "#objectID" ).load( "test.php", { "choices[]": [ "Jon", "Susan" ] } );

Rails - How to use a Helper Inside a Controller

You can use

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

Load More Posts Ajax Button in WordPress

UPDATE 24.04.2016.

I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)

EDIT

I've tested this on Twenty Fifteen and it's working, so it should be working for you.

In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:

    <div id="ajax-posts" class="row">
        <?php
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
                    'cat' => 8
            );

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();
        ?>

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with

$cat_id = get_query_var('cat');

This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like

<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>

And pull the category with

var cat = $('#more_posts').data('category');

But for now, you can leave this out.

Next in functions.php I added

wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),
));

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the functions.php file I added the function that will load your posts:

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 8,
        'paged'    => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">
                <h1>'.get_the_title().'</h1>
                <p>'.get_the_content().'</p>
         </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.

If you've added your category in the loader, you'd add:

$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';

And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.

Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment

var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
});

Saved it, tested it, and it works :)

Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD

enter image description here

enter image description here

enter image description here

UPDATE

For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with

$(window).on('scroll', function () {
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer

$(window).on('scroll', function(){
    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
                load_posts();
        }
    }
});

Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.

You can easily check it by putting console.logs in your code and see in the inspector what they throw out

$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

And just adjust accordingly ;)

Hope this helps :) If you have any questions just ask.

Return a `struct` from a function in C

You can return a structure from a function (or use the = operator) without any problems. It's a well-defined part of the language. The only problem with struct b = a is that you didn't provide a complete type. struct MyObj b = a will work just fine. You can pass structures to functions as well - a structure is exactly the same as any built-in type for purposes of parameter passing, return values, and assignment.

Here's a simple demonstration program that does all three - passes a structure as a parameter, returns a structure from a function, and uses structures in assignment statements:

#include <stdio.h>

struct a {
   int i;
};

struct a f(struct a x)
{
   struct a r = x;
   return r;
}

int main(void)
{
   struct a x = { 12 };
   struct a y = f(x);
   printf("%d\n", y.i);
   return 0;
}

The next example is pretty much exactly the same, but uses the built-in int type for demonstration purposes. The two programs have the same behaviour with respect to pass-by-value for parameter passing, assignment, etc.:

#include <stdio.h>

int f(int x) 
{
  int r = x;
  return r;
}

int main(void)
{
  int x = 12;
  int y = f(x);
  printf("%d\n", y);
  return 0;
}

How do I simulate a hover with a touch in touch enabled browsers?

Without device (or rather browser) specific JS I'm pretty sure you're out of luck.

Edit: thought you wanted to avoid that until i reread your question. In case of Mobile Safari you can register to get all touch events similar to what you can do with native UIView-s. Can't find the documentation right now, will try to though.

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

Best TCP port number range for internal applications

Short answer: use an unassigned user port

Over achiever's answer - Select and deploy a resource discovery solution. Have the server select a private port dynamically. Have the clients use resource discovery.

The risk that that a server will fail because the port it wants to listen on is not available is real; at least it's happened to me. Another service or a client might get there first.

You can almost totally reduce the risk from a client by avoiding the private ports, which are dynamically handed out to clients.

The risk that from another service is minimal if you use a user port. An unassigned port's risk is only that another service happens to be configured (or dyamically) uses that port. But at least that's probably under your control.

The huge doc with all the port assignments, including User Ports, is here: http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.txt look for the token Unassigned.

Timer for Python game

For a StopWatch helper class, here is my solution which gives you precision on output and also access to the raw start time:

class StopWatch:
    def __init__(self):
        self.start()
    def start(self):
        self._startTime = time.time()
    def getStartTime(self):
        return self._startTime
    def elapsed(self, prec=3):
        prec = 3 if prec is None or not isinstance(prec, (int, long)) else prec
        diff= time.time() - self._startTime
        return round(diff, prec)
def round(n, p=0):
    m = 10 ** p
    return math.floor(n * m + 0.5) / m

Difference between id and name attributes in HTML

The name attribute is used when sending data in a form submission. Different controls respond differently. For example, you may have several radio buttons with different id attributes, but the same name. When submitted, there is just the one value in the response - the radio button you selected.

Of course, there's more to it than that, but it will definitely get you thinking in the right direction.

MySQLDump one INSERT statement for each data row

In newer versions change was made to the flags: from the documentation:

--extended-insert, -e

Write INSERT statements using multiple-row syntax that includes several VALUES lists. This results in a smaller dump file and speeds up inserts when the file is reloaded.

--opt

This option, enabled by default, is shorthand for the combination of --add-drop-table --add-locks --create-options --disable-keys --extended-insert --lock-tables --quick --set-charset. It gives a fast dump operation and produces a dump file that can be reloaded into a MySQL server quickly.

Because the --opt option is enabled by default, you only specify its converse, the --skip-opt to turn off several default settings. See the discussion of mysqldump option groups for information about selectively enabling or disabling a subset of the options affected by --opt.

--skip-extended-insert

Turn off extended-insert

Convert double to string

a = 0.000006;
b = 6;
c = a/b;

textbox.Text = c.ToString("0.000000");

As you requested:

textbox.Text = c.ToString("0.######");

This will only display out to the 6th decimal place if there are 6 decimals to display.

How do I tell what type of value is in a Perl variable?

At some point I read a reasonably convincing argument on Perlmonks that testing the type of a scalar with ref or reftype is a bad idea. I don't recall who put the idea forward, or the link. Sorry.

The point was that in Perl there are many mechanisms that make it possible to make a given scalar act like just about anything you want. If you tie a filehandle so that it acts like a hash, the testing with reftype will tell you that you have a filehanle. It won't tell you that you need to use it like a hash.

So, the argument went, it is better to use duck typing to find out what a variable is.

Instead of:

sub foo {
    my $var = shift;
    my $type = reftype $var;

    my $result;
    if( $type eq 'HASH' ) {
        $result = $var->{foo};
    }
    elsif( $type eq 'ARRAY' ) {
        $result = $var->[3];
    }
    else {
        $result = 'foo';
    }

    return $result;
}

You should do something like this:

sub foo {
    my $var = shift;
    my $type = reftype $var;

    my $result;

    eval {
        $result = $var->{foo};
        1; # guarantee a true result if code works.
    }
    or eval { 
        $result = $var->[3];
        1;
    }
    or do {
        $result = 'foo';
    }

    return $result;
}

For the most part I don't actually do this, but in some cases I have. I'm still making my mind up as to when this approach is appropriate. I thought I'd throw the concept out for further discussion. I'd love to see comments.

Update

I realized I should put forward my thoughts on this approach.

This method has the advantage of handling anything you throw at it.

It has the disadvantage of being cumbersome, and somewhat strange. Stumbling upon this in some code would make me issue a big fat 'WTF'.

I like the idea of testing whether a scalar acts like a hash-ref, rather that whether it is a hash ref.

I don't like this implementation.

How can I have two fixed width columns with one flexible column in the center?

Compatibility with older browsers can be a drag, so be adviced.

If that is not a problem then go ahead. Run the snippet. Go to full page view and resize. Center will resize itself with no changes to the left or right divs.

Change left and right values to meet your requirement.

Thank you.

Hope this helps.

_x000D_
_x000D_
#container {_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
.column.left {_x000D_
  width: 100px;_x000D_
  flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.right {_x000D_
  width: 100px;_x000D_
  flex: 0 0 100px;_x000D_
}_x000D_
_x000D_
.column.center {_x000D_
  flex: 1;_x000D_
  text-align: center;_x000D_
}_x000D_
_x000D_
.column.left,_x000D_
.column.right {_x000D_
  background: orange;_x000D_
  text-align: center;_x000D_
}
_x000D_
<div id="container">_x000D_
  <div class="column left">this is left</div>_x000D_
  <div class="column center">this is center</div>_x000D_
  <div class="column right">this is right</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Is there a way to avoid null check before the for-each loop iteration starts?

How much shorter do you want it to be? It is only an extra 2 lines AND it is clear and concise logic.

I think the more important thing you need to decide is if null is a valid value or not. If they are not valid, you should write you code to prevent it from happening. Then you would not need this kind of check. If you go get an exception while doing a foreach loop, that is a sign that there is a bug somewhere else in your code.

Get elements by attribute when querySelectorAll is not available without using libraries?

Don't use in Browser

In the browser, use document.querySelect('[attribute-name]').

But if you're unit testing and your mocked dom has a flakey querySelector implementation, this will do the trick.

This is @kevinfahy's answer, just trimmed down to be a bit with ES6 fat arrow functions and by converting the HtmlCollection into an array at the cost of readability perhaps.

So it'll only work with an ES6 transpiler. Also, I'm not sure how performant it'll be with a lot of elements.

function getElementsWithAttribute(attribute) {
  return [].slice.call(document.getElementsByTagName('*'))
    .filter(elem => elem.getAttribute(attribute) !== null);
}

And here's a variant that will get an attribute with a specific value

function getElementsWithAttributeValue(attribute, value) {
  return [].slice.call(document.getElementsByTagName('*'))
    .filter(elem => elem.getAttribute(attribute) === value);
}

tmux status bar configuration

I have been playing about with tmux today, trying to customised a little here and there, managed to get battery info displaying on the status right with a ruby script.

Copy the ruby script from http://natedickson.com/blog/2013/04/30/battery-status-in-tmux/ and save it as:

 battinfo.rb in ~/bin

To make it executable make sure to run:

chmod +x ~/bin/battinfo.rb

edit your ~/.tmux.config and include this line

set -g status-right "#[fg=colour155]#(pmset -g batt | ~/bin/battinfo.rb) | #[fg=colour45]%d %b %R"

Percentage Height HTML 5/CSS

bobince's answer will let you know in which cases "height: XX%;" will or won't work.

If you want to create an element with a set ratio (height: % of it's own width), the best way to do that is by effectively setting the height using padding-bottom. Example for square:

<div class="square-container">
  <div class="square-content">
    <!-- put your content in here -->
  </div>
</div>

.square-container {  /* any display: block; element */
  position: relative;
  height: 0;
  padding-bottom: 100%; /* of parent width */
}
.square-content {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
}

The square container will just be made of padding, and the content will expand to fill the container. Long article from 2009 on this subject: http://alistapart.com/article/creating-intrinsic-ratios-for-video

Difference Between Cohesion and Coupling

Cohesion is an indication of the relative functional strength of a module.

  • A cohesive module performs a single task, requiring little interaction with other components in other parts of a program. Stated simply, a cohesive module should (ideally) do just one thing.
  • ?Conventional view:

    the “single-mindedness” of a module

  • ?OO view:

    ?cohesion implies that a component or class encapsulates only attributes and operations that are closely related to one another and to the class or component itself

  • ?Levels of cohesion

    ?Functional

    ?Layer

    ?Communicational

    ?Sequential

    ?Procedural

    ?Temporal

    ?utility

Coupling is an indication of the relative interdependence among modules.

  • Coupling depends on the interface complexity between modules, the point at which entry or reference is made to a module, and what data pass across the interface.

  • Conventional View : The degree to which a component is connected to other components and to the external world

  • OO view: a qualitative measure of the degree to which classes are connected to one another

  • Level of coupling

    ?Content

    ?Common

    ?Control

    ?Stamp

    ?Data

    ?Routine call

    ?Type use

    ?Inclusion or import

    ?External #

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

RunAs A different user when debugging in Visual Studio

I'm using Visual Studio 2015 and attempting to debug a website with different credentials.

(I'm currently testing a website on a development network that has a copy of the live active directory; I can "hijack" user accounts to test permissions in a safe way)

  1. Begin debugging with your normal user, ensure you can get to http://localhost:8080 as normal etc
  2. Give the other user "Full Control" access to your normal user's home directory, ie, C:\Users\Colin
  3. Make the other user an administrator on your machine. Right click Computer > Manage > Add other user to Administrator group
  4. Run Internet Explorer as the other user (Shift + Right Click Internet Explorer, Run as different user)
  5. Go to your localhost URL in that IE window

Really convenient to do some quick testing. The Full Control access is probably overkill but I develop on an isolated network. If anyone adds notes about more specific settings I'll gladly edit this post in future.

finding multiples of a number in Python

You can do:

def mul_table(n,i=1):
    print(n*i)
    if i !=10:
        mul_table(n,i+1)
mul_table(7)

How do I set Tomcat Manager Application User Name and Password for NetBeans?

I case of tomcat 7 the role has changed from manager to manager-gui so set it as below in the tomcat-user.xml file.

enter image description here

Read file data without saving it in Flask

I was trying to do the exact same thing, open a text file (a CSV for Pandas actually). Don't want to make a copy of it, just want to open it. The form-WTF has a nice file browser, but then it opens the file and makes a temporary file, which it presents as a memory stream. With a little work under the hood,

form = UploadForm() 
 if form.validate_on_submit(): 
      filename = secure_filename(form.fileContents.data.filename)  
      filestream =  form.fileContents.data 
      filestream.seek(0)
      ef = pd.read_csv( filestream  )
      sr = pd.DataFrame(ef)  
      return render_template('dataframe.html',tables=[sr.to_html(justify='center, classes='table table-bordered table-hover')],titles = [filename], form=form) 

Spark - repartition() vs coalesce()

For someone who had issues generating a single csv file from PySpark (AWS EMR) as an output and saving it on s3, using repartition helped. The reason being, coalesce cannot do a full shuffle, but repartition can. Essentially, you can increase or decrease the number of partitions using repartition, but can only decrease the number of partitions (but not 1) using coalesce. Here is the code for anyone who is trying to write a csv from AWS EMR to s3:

df.repartition(1).write.format('csv')\
.option("path", "s3a://my.bucket.name/location")\
.save(header = 'true')

Required request body content is missing: org.springframework.web.method.HandlerMethod$HandlerMethodParameter

If it's working from Postman, try new Spring version, becouse the 'org.springframework.boot' 2.2.2.RELEASE version can throw "Required request body content is missing" exception.
Try 2.2.6.RELEASE version.

Google server putty connect 'Disconnected: No supported authentication methods available (server sent: publickey)

PasswordAuthentication and ChallengeResponseAuthentication default set to NO in rhel7.

Change them to NO and restart sshd.

Find all packages installed with easy_install/pip?

If you use the Anaconda python distribution, you can use the conda list command to see what was installed by what method:

user@pc:~ $ conda list
# packages in environment at /anaconda3:
#
# Name                    Version                   Build  Channel
_ipyw_jlab_nb_ext_conf    0.1.0            py36h2fc01ae_0
alabaster                 0.7.10           py36h174008c_0
amqp                      2.2.2                     <pip>
anaconda                  5.1.0                    py36_2
anaconda-client           1.6.9                    py36_0

To grab the entries installed by pip (including possibly pip itself):

user@pc:~ $ conda list | grep \<pip
amqp                      2.2.2                     <pip>
astroid                   1.6.2                     <pip>
billiard                  3.5.0.3                   <pip>
blinker                   1.4                       <pip>
ez-setup                  0.9                       <pip>
feedgenerator             1.9                       <pip>

Of course you probably want to just select the first column, which you can do with (excluding pip if needed):

user@pc:~ $ conda list | awk '$3 ~ /pip/ {if ($1 != "pip") print $1}'
amqp        
astroid
billiard
blinker
ez-setup
feedgenerator 

Finally you can grab these values and pip uninstall all of them using the following:

user@pc:~ $ conda list | awk '$3 ~ /pip/ {if ($1 != "pip") print $1}' | xargs pip uninstall -y

Note the use of the -y flag for the pip uninstall to avoid having to give confirmation to delete.

How to set the JDK Netbeans runs on?

Go to Tools -> Java Platforms. There, click on Add Platform, point it to C:\Program Files (x86)\Java\jdk1.6.0_25. You can either set the another JDK version or remove existing versions.

Another solution suggested in the oracle (sun) site is,

netbeans.exe --jdkhome "C:\Program Files\jdk1.6.0_20"

I tried this on 6.9.1. You may change the JDK per project as well. You need to set the available JDKs via Java Platforms dialog. Then, go to Run -> Set Project Configuration -> Customize. After that, in the opened Dialog box go to Build -> Compile. Set the version.

Get array of object's keys

You can use jQuery's $.map.

var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' },
keys = $.map(foo, function(v, i){
  return i;
});

How to use pip with Python 3.x alongside Python 2.x

Please note that on msys2 I've found these commands to be helpful:

$ pacman -S python3-pip
$ pip3 install --upgrade pip
$ pip3 install --user package_name

Fixed header, footer with scrollable content

Here's what worked for me. I had to add a margin-bottom so the footer wouldn't eat up my content:

header {
  height: 20px;
  background-color: #1d0d0a;
  position: fixed;
  top: 0;
  width: 100%;
  overflow: hide;
}

content {
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 100px;
  margin-top: 20px;
  overflow: auto;
  width: 80%;
}

footer {
  position: fixed;
  bottom: 0px;
  overflow: hide;
  width: 100%;
}

I want to execute shell commands from Maven's pom.xml

Thanks! Tomer Ben David. it helped me. as I am doing pip install in demo folder as you mentioned npm install

<groupId>org.codehaus.mojo</groupId>
            <artifactId>exec-maven-plugin</artifactId>
            <version>1.3.2</version>
            <executions>
              <execution>
                <goals>
                  <goal>exec</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <executable>pip</executable>
              <arguments><argument>install</argument></arguments>                            
             <workingDirectory>${project.build.directory}/Demo</workingDirectory>
            </configuration>

How can I export Excel files using JavaScript?

I recommend you to generate an open format XML Excel file, is much more flexible than CSV.
Read Generating an Excel file in ASP.NET for more info

Python PIP Install throws TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

I have the same problem when installing a RaspberryPI TFT from Adafruit with pitft.sh / adafruit-pitft.sh.

I am not happy about coding-styles with errors from somewhere to be interpreted somehow - as could be seen by the previous answers.

Remark: The type error exception of retry.py is obviously a bug, caused by an unappropriate assignement and calculation of an instance of the class Reply to an int with the default value of 10 - somewhere in the code... Should be fixed either by adding an inplace-operator, or fixing the erroneous assignment.

So tried to analyse and patch the error itself first. The actual error in my case case is the same - retry.py called by pip.

The installation script adafruit-pitft.sh / pitft.sh tries to apply urllib3 which itself tries to install nested dependencies by pip, so the same error.

adafruit-pitft.sh # or pitft.sh

...

_stacktrace=sys.exc_info()[2]) File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3 none-any.whl/urllib3/util/retry.py", line 228, in increment

total -= 1

TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

For the current distribution(based on debian-9.6.0/stretch):

File "/usr/share/python-wheels/urllib3-1.19.1-py2.py3-none-any.whl/urllib3/util/retry.py", line 315, in increment

total -= 1

TypeError: unsupported operand type(s) for -=: 'Retry' and 'int'

The following - dirty *:) - patch enables a sounding error trace:

# File: retry.py - in *def increment(self, ..* about line 315
# original: total = self.total

# patch: quick-and-dirty-fix
# START:
if isinstance(self.total, Retry):
    self.total = self.total.total

if type(self.total) is not int:
    self.total = 2 # default is 10
# END:

# continue with original:
total = self.total

if total is not None:
    total -= 1

connect = self.connect
read = self.read
redirect = self.redirect
cause = 'unknown'
status = None
redirect_location = None

if error and self._is_connection_error(error):
    # Connect retry?
    if connect is False:
        raise six.reraise(type(error), error, _stacktrace)
    elif connect is not None:
        connect -= 1

The sounding output with the temporary patch is(displayed twice...?):

Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at/

Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at/

Could not find a version that satisfies the requirement evdev (from versions: )

No matching distribution found for evdev

WARNING : Pip failed to install software!

So in my case actually two things cause the error, this may vary in other environments:

  1. Missing evdev => try to install
  2. Failed to connect a repo/dist containing evdev in order to download. => finally give it up

My installation environment is offline from an internal debian+raspbian mirror, thus do not want to set the proxy...

So I proceeded by manual installation of the missing component evdev:

  1. download evdev from PyPI(or e.g. from github.com):

    https://pypi.org/project/evdev/

    https://files.pythonhosted.org/packages/7e/53/374b82dd2ccec240b7388c65075391147524255466651a14340615aabb5f/evdev-1.1.2.tar.gz

  2. Unpack and install manually as root user - for all local accounts, so detected as installed:

    sudo su -

    tar xf evdev-1.1.2.tar.gz

    cd evdev-1.1.2

    python setup.py install

  3. Call install script again:

    adafruit-pitft.sh # or pitft.sh

    ...Answer dialogues...

    ...that's it.

If you proceed online by direct PyPI access:

  1. check your routing + firewall for access to pypi.org

  2. set a proxy if required (http_proxy/https_proxy)

And it works..

Hope this helps in other cases too.

Arno-Can Uestuensoez

----------------------------------------------

See also: issue - 35334: https://bugs.python.org/issue35334

----------------------------------------------

See now also: issue - 1486: https://github.com/urllib3/urllib3/issues/1486

for file: https://github.com/urllib3/urllib3/blob/master/src/urllib3/util/retry.py

Uninstalling an MSI file from the command line without using msiexec

The msi file extension is mapped to msiexec (same way typing a .txt filename on a command prompt launches Notepad/default .txt file handler to display the file).

Thus typing in a filename with an .msi extension really runs msiexec with the MSI file as argument and takes the default action, install. For that reason, uninstalling requires you to invoke msiexec with uninstall switch to unstall it.

How to get the index of a maximum element in a NumPy array along one axis

>>> import numpy as np
>>> a = np.array([[1,2,3],[4,3,1]])
>>> i,j = np.unravel_index(a.argmax(), a.shape)
>>> a[i,j]
4

"No such file or directory" but it exists

Added here for future reference (for users who might fall into the same case): This error happens when working on Windows (which introduces extra characters because of different line separator than Linux system) and trying to run this script (with extra characters inserted) in Linux. The error message is misleading.

In Windows, the line separator is CRLF (\r\n) whereas in linux it is LF (\n). This can be usually be chosen in text editor.

In my case, this happened due to working on Windows and uploading to Unix server for execution.

How do I properly clean up Excel interop objects?

'This sure seems like it has been over-complicated. From my experience, there are just three key things to get Excel to close properly:

1: make sure there are no remaining references to the excel application you created (you should only have one anyway; set it to null)

2: call GC.Collect()

3: Excel has to be closed, either by the user manually closing the program, or by you calling Quit on the Excel object. (Note that Quit will function just as if the user tried to close the program, and will present a confirmation dialog if there are unsaved changes, even if Excel is not visible. The user could press cancel, and then Excel will not have been closed.)

1 needs to happen before 2, but 3 can happen anytime.

One way to implement this is to wrap the interop Excel object with your own class, create the interop instance in the constructor, and implement IDisposable with Dispose looking something like

That will clean up excel from your program's side of things. Once Excel is closed (manually by the user or by you calling Quit) the process will go away. If the program has already been closed, then the process will disappear on the GC.Collect() call.

(I'm not sure how important it is, but you may want a GC.WaitForPendingFinalizers() call after the GC.Collect() call but it is not strictly necessary to get rid of the Excel process.)

This has worked for me without issue for years. Keep in mind though that while this works, you actually have to close gracefully for it to work. You will still get accumulating excel.exe processes if you interrupt your program before Excel is cleaned up (usually by hitting "stop" while your program is being debugged).'

How to change the data type of a column without dropping the column with query?

ALTER tablename MODIFY columnName newColumnType

I'm not sure how it will handle the change from datetime to varchar though, so you may need to rename the column, add a new one with the old name and the correct data type (varchar) and then write an update query to populate the new column from the old.

http://www.1keydata.com/sql/sql-alter-table.html

The container 'Maven Dependencies' references non existing library - STS

Today I had this same problem with another jar. I tried multiple things people said on Stackoverflow, but nothing worked. Eventually I did this:

  1. Close eclipse and any project-app that is running.
  2. Delete the .m2 folder (Users --> [your_username] --> .m2). It's an invisible folder, make sure you are able to view invisible folders.
  3. Restarted Eclipse (I guess it works in other IDE too) and updated my project.

Now it works again for me. Perhaps this solves the problem for someone else too.

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

How to add facebook share button on my website?

For your own specific server or different pages & image button you could use something like this (PHP only)

<a href="http://www.facebook.com/sharer/sharer.php?u=http://'.$_SERVER['SERVER_NAME'].'" target="_blank"><img src="http://i.stack.imgur.com/rffGp.png" /></a>

I cannot share the snippet with this but you will get the idea...

gradient descent using python and numpy

I think your code is a bit too complicated and it needs more structure, because otherwise you'll be lost in all equations and operations. In the end this regression boils down to four operations:

  1. Calculate the hypothesis h = X * theta
  2. Calculate the loss = h - y and maybe the squared cost (loss^2)/2m
  3. Calculate the gradient = X' * loss / m
  4. Update the parameters theta = theta - alpha * gradient

In your case, I guess you have confused m with n. Here m denotes the number of examples in your training set, not the number of features.

Let's have a look at my variation of your code:

import numpy as np
import random

# m denotes the number of examples here, not the number of features
def gradientDescent(x, y, theta, alpha, m, numIterations):
    xTrans = x.transpose()
    for i in range(0, numIterations):
        hypothesis = np.dot(x, theta)
        loss = hypothesis - y
        # avg cost per example (the 2 in 2*m doesn't really matter here.
        # But to be consistent with the gradient, I include it)
        cost = np.sum(loss ** 2) / (2 * m)
        print("Iteration %d | Cost: %f" % (i, cost))
        # avg gradient per example
        gradient = np.dot(xTrans, loss) / m
        # update
        theta = theta - alpha * gradient
    return theta


def genData(numPoints, bias, variance):
    x = np.zeros(shape=(numPoints, 2))
    y = np.zeros(shape=numPoints)
    # basically a straight line
    for i in range(0, numPoints):
        # bias feature
        x[i][0] = 1
        x[i][1] = i
        # our target variable
        y[i] = (i + bias) + random.uniform(0, 1) * variance
    return x, y

# gen 100 points with a bias of 25 and 10 variance as a bit of noise
x, y = genData(100, 25, 10)
m, n = np.shape(x)
numIterations= 100000
alpha = 0.0005
theta = np.ones(n)
theta = gradientDescent(x, y, theta, alpha, m, numIterations)
print(theta)

At first I create a small random dataset which should look like this:

Linear Regression

As you can see I also added the generated regression line and formula that was calculated by excel.

You need to take care about the intuition of the regression using gradient descent. As you do a complete batch pass over your data X, you need to reduce the m-losses of every example to a single weight update. In this case, this is the average of the sum over the gradients, thus the division by m.

The next thing you need to take care about is to track the convergence and adjust the learning rate. For that matter you should always track your cost every iteration, maybe even plot it.

If you run my example, the theta returned will look like this:

Iteration 99997 | Cost: 47883.706462
Iteration 99998 | Cost: 47883.706462
Iteration 99999 | Cost: 47883.706462
[ 29.25567368   1.01108458]

Which is actually quite close to the equation that was calculated by excel (y = x + 30). Note that as we passed the bias into the first column, the first theta value denotes the bias weight.

Recommendations of Python REST (web services) framework?

web2py includes support for easily building RESTful API's, described here and here (video). In particular, look at parse_as_rest, which lets you define URL patterns that map request args to database queries; and smart_query, which enables you to pass arbitrary natural language queries in the URL.

Animate an element's width from 0 to 100%, with it and it's wrapper being only as wide as they need to be, without a pre-set width, in CSS3 or jQuery

I haven't been able to get it to work without specifying a width but the following css worked

.wrapper {
    background: #DDD;
    padding: 10px;
    display: inline-block;
    height: 20px;
    width: auto;
}

.contents {
    background: #c3c;
    overflow: hidden;
    white-space: nowrap;
    display: inline-block;
    visibility: hidden;
    width: 1px;
    -webkit-transition: width 1s ease-in-out, visibility 1s linear;
    -moz-transition: width 1s ease-in-out, visibility 1s linear;
    -o-transition: width 1s ease-in-out, visibility 1s linear;
    transition: width 1s ease-in-out, visibility 1s linear;
}

.wrapper:hover .contents {
    width: 200px;
    visibility: visible;
}

I'm not sure you will be able to get it working without setting a width on it.

IOException: Too many open files

The problem comes from your Java application (or a library you are using).

First, you should read the entire outputs (Google for StreamGobbler), and pronto!

Javadoc says:

The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

Secondly, waitFor() your process to terminate. You then should close the input, output and error streams.

Finally destroy() your Process.

My sources:

How to generate .NET 4.0 classes from xsd?

xsd.exe as mentioned by Marc Gravell. The fastest way to get up and running IMO.

Or if you need more flexibility/options :

xsd2code VS add-in (Codeplex)

Formatting a float to 2 decimal places

string outString= number.ToString("####0.00");

Operand type clash: int is incompatible with date + The INSERT statement conflicted with the FOREIGN KEY constraint

I had the same problem. I tried 'yyyy-mm-dd' format i.e. '2013-26-11' and got rid of this problem...

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

The existing answers have quite broken code. The DNS method does not work at all. Here is code that I used to configure my NIC:

public static class NetworkConfigurator
{
    /// <summary>
    /// Set's a new IP Address and it's Submask of the local machine
    /// </summary>
    /// <param name="ipAddress">The IP Address</param>
    /// <param name="subnetMask">The Submask IP Address</param>
    /// <param name="gateway">The gateway.</param>
    /// <param name="nicDescription"></param>
    /// <remarks>Requires a reference to the System.Management namespace</remarks>
    public static void SetIP(string nicDescription, string[] ipAddresses, string subnetMask, string gateway)
    {
        using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        {
            using (var networkConfigs = networkConfigMng.GetInstances())
            {
                foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
                {
                    using (var newIP = managementObject.GetMethodParameters("EnableStatic"))
                    {
                        // Set new IP address and subnet if needed
                        if (ipAddresses != null || !String.IsNullOrEmpty(subnetMask))
                        {
                            if (ipAddresses != null)
                            {
                                newIP["IPAddress"] = ipAddresses;
                            }

                            if (!String.IsNullOrEmpty(subnetMask))
                            {
                                newIP["SubnetMask"] = Array.ConvertAll(ipAddresses, _ => subnetMask);
                            }

                            managementObject.InvokeMethod("EnableStatic", newIP, null);
                        }

                        // Set mew gateway if needed
                        if (!String.IsNullOrEmpty(gateway))
                        {
                            using (var newGateway = managementObject.GetMethodParameters("SetGateways"))
                            {
                                newGateway["DefaultIPGateway"] = new[] { gateway };
                                newGateway["GatewayCostMetric"] = new[] { 1 };
                                managementObject.InvokeMethod("SetGateways", newGateway, null);
                            }
                        }
                    }
                }
            }
        }
    }

    /// <summary>
    /// Set's the DNS Server of the local machine
    /// </summary>
    /// <param name="nic">NIC address</param>
    /// <param name="dnsServers">Comma seperated list of DNS server addresses</param>
    /// <remarks>Requires a reference to the System.Management namespace</remarks>
    public static void SetNameservers(string nicDescription, string[] dnsServers)
    {
        using (var networkConfigMng = new ManagementClass("Win32_NetworkAdapterConfiguration"))
        {
            using (var networkConfigs = networkConfigMng.GetInstances())
            {
                foreach (var managementObject in networkConfigs.Cast<ManagementObject>().Where(mo => (bool)mo["IPEnabled"] && (string)mo["Description"] == nicDescription))
                {
                    using (var newDNS = managementObject.GetMethodParameters("SetDNSServerSearchOrder"))
                    {
                        newDNS["DNSServerSearchOrder"] = dnsServers;
                        managementObject.InvokeMethod("SetDNSServerSearchOrder", newDNS, null);
                    }
                }
            }
        }
    }
}

Does Java have a path joining method?

This is a start, I don't think it works exactly as you intend, but it at least produces a consistent result.

import java.io.File;

public class Main
{
    public static void main(final String[] argv)
        throws Exception
    {
        System.out.println(pathJoin());
        System.out.println(pathJoin(""));
        System.out.println(pathJoin("a"));
        System.out.println(pathJoin("a", "b"));
        System.out.println(pathJoin("a", "b", "c"));
        System.out.println(pathJoin("a", "b", "", "def"));
    }

    public static String pathJoin(final String ... pathElements)
    {
        final String path;

        if(pathElements == null || pathElements.length == 0)
        {
            path = File.separator;
        }
        else
        {
            final StringBuilder builder;

            builder = new StringBuilder();

            for(final String pathElement : pathElements)
            {
                final String sanitizedPathElement;

                // the "\\" is for Windows... you will need to come up with the 
                // appropriate regex for this to be portable
                sanitizedPathElement = pathElement.replaceAll("\\" + File.separator, "");

                if(sanitizedPathElement.length() > 0)
                {
                    builder.append(sanitizedPathElement);
                    builder.append(File.separator);
                }
            }

            path = builder.toString();
        }

        return (path);
    }
}

How to remove files from git staging area?

You can reset the staging area in a few ways:

  1. Reset HEAD and add all necessary files to check-in again as below:

     git reset HEAD ---> removes all files from the staging area
     git add <files, that are required to be committed>
     git commit -m "<commit message>"
     git push 
    

MySQL, create a simple function

MySQL function example:

Open the mysql terminal:

el@apollo:~$ mysql -u root -pthepassword yourdb
mysql>

Drop the function if it already exists

mysql> drop function if exists myfunc;
Query OK, 0 rows affected, 1 warning (0.00 sec)

Create the function

mysql> create function hello(id INT)
    -> returns CHAR(50)
    -> return 'foobar';
Query OK, 0 rows affected (0.01 sec)

Create a simple table to test it out with

mysql> create table yar (id INT);
Query OK, 0 rows affected (0.07 sec)

Insert three values into the table yar

mysql> insert into yar values(5), (7), (9);
Query OK, 3 rows affected (0.04 sec)
Records: 3  Duplicates: 0  Warnings: 0

Select all the values from yar, run our function hello each time:

mysql> select id, hello(5) from yar;
+------+----------+
| id   | hello(5) |
+------+----------+
|    5 | foobar   |
|    7 | foobar   |
|    9 | foobar   |
+------+----------+
3 rows in set (0.01 sec)

Verbalize and internalize what just happened:

You created a function called hello which takes one parameter. The parameter is ignored and returns a CHAR(50) containing the value 'foobar'. You created a table called yar and added three rows to it. The select statement runs the function hello(5) for each row returned by yar.

Correct way to write line to file?

When you said Line it means some serialized characters which are ended to '\n' characters. Line should be last at some point so we should consider '\n' at the end of each line. Here is solution:

with open('YOURFILE.txt', 'a') as the_file:
    the_file.write("Hello")

in append mode after each write the cursor move to new line, if you want to use w mode you should add \n characters at the end of the write() function:

the_file.write("Hello\n")

Should I use 'has_key()' or 'in' on Python dicts?

Use dict.has_key() if (and only if) your code is required to be runnable by Python versions earlier than 2.3 (when key in dict was introduced).

How to catch an Exception from a thread

I faced the same issue ... little work around (only for implementation not anonymous objects ) ... we can declare the class level exception object as null ... then initialize it inside the catch block for run method ... if there was error in run method,this variable wont be null .. we can then have null check for this particular variable and if its not null then there was exception inside the thread execution.

class TestClass implements Runnable{
    private Exception ex;

        @Override
        public void run() {
            try{
                //business code
               }catch(Exception e){
                   ex=e;
               }
          }

      public void checkForException() throws Exception {
            if (ex!= null) {
                throw ex;
            }
        }
}     

call checkForException() after join()

Jackson and generic type reference

I modified rushidesai1's answer to include a working example.

JsonMarshaller.java

import java.io.*;
import java.util.*;

public class JsonMarshaller<T> {
    private static ClassLoader loader = JsonMarshaller.class.getClassLoader();

    public static void main(String[] args) {
        try {
            JsonMarshallerUnmarshaller<Station> marshaller = new JsonMarshallerUnmarshaller<>(Station.class);
            String jsonString = read(loader.getResourceAsStream("data.json"));
            List<Station> stations = marshaller.unmarshal(jsonString);
            stations.forEach(System.out::println);
            System.out.println(marshaller.marshal(stations));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @SuppressWarnings("resource")
    public static String read(InputStream ios) {
        return new Scanner(ios).useDelimiter("\\A").next(); // Read the entire file
    }
}

Output

Station [id=123, title=my title, name=my name]
Station [id=456, title=my title 2, name=my name 2]
[{"id":123,"title":"my title","name":"my name"},{"id":456,"title":"my title 2","name":"my name 2"}]

JsonMarshallerUnmarshaller.java

import java.io.*;
import java.util.List;

import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;

public class JsonMarshallerUnmarshaller<T> {
    private ObjectMapper mapper;
    private Class<T> targetClass;

    public JsonMarshallerUnmarshaller(Class<T> targetClass) {
        AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();

        mapper = new ObjectMapper();
        mapper.getDeserializationConfig().with(introspector);
        mapper.getSerializationConfig().with(introspector);

        this.targetClass = targetClass;
    }

    public List<T> unmarshal(String jsonString) throws JsonParseException, JsonMappingException, IOException {
        return parseList(jsonString, mapper, targetClass);
    }

    public String marshal(List<T> list) throws JsonProcessingException {
        return mapper.writeValueAsString(list);
    }

    public static <E> List<E> parseList(String str, ObjectMapper mapper, Class<E> clazz)
            throws JsonParseException, JsonMappingException, IOException {
        return mapper.readValue(str, listType(mapper, clazz));
    }

    public static <E> List<E> parseList(InputStream is, ObjectMapper mapper, Class<E> clazz)
            throws JsonParseException, JsonMappingException, IOException {
        return mapper.readValue(is, listType(mapper, clazz));
    }

    public static <E> JavaType listType(ObjectMapper mapper, Class<E> clazz) {
        return mapper.getTypeFactory().constructCollectionType(List.class, clazz);
    }
}

Station.java

public class Station {
    private long id;
    private String title;
    private String name;

    public long getId() {
        return id;
    }

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

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return String.format("Station [id=%s, title=%s, name=%s]", id, title, name);
    }
}

data.json

[{
  "id": 123,
  "title": "my title",
  "name": "my name"
}, {
  "id": 456,
  "title": "my title 2",
  "name": "my name 2"
}]

Http post and get request in angular 6

Update : In angular 7, they are the same as 6

In angular 6

the complete answer found in live example

  /** POST: add a new hero to the database */
  addHero (hero: Hero): Observable<Hero> {
 return this.http.post<Hero>(this.heroesUrl, hero, httpOptions)
  .pipe(
    catchError(this.handleError('addHero', hero))
  );
}
  /** GET heroes from the server */
 getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
  .pipe(
    catchError(this.handleError('getHeroes', []))
  );
}

it's because of pipeable/lettable operators which now angular is able to use tree-shakable and remove unused imports and optimize the app

some rxjs functions are changed

do -> tap
catch -> catchError
switch -> switchAll
finally -> finalize

more in MIGRATION

and Import paths

For JavaScript developers, the general rule is as follows:

rxjs: Creation methods, types, schedulers and utilities

import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';

rxjs/operators: All pipeable operators:

import { map, filter, scan } from 'rxjs/operators';

rxjs/webSocket: The web socket subject implementation

import { webSocket } from 'rxjs/webSocket';

rxjs/ajax: The Rx ajax implementation

import { ajax } from 'rxjs/ajax';

rxjs/testing: The testing utilities

import { TestScheduler } from 'rxjs/testing';

and for backward compatability you can use rxjs-compat

When should you NOT use a Rules Engine?

I would strongly recommend business rules engines like Drools as open source or Commercial Rules Engine such as LiveRules.

  • When you have a lot of business policies which are volatile in nature, it is very hard to maintain that part of the core technology code.
  • The rules engine provides a great flexibility of the framework and easy to change and deploy.
  • Rules engines are not to be used everywhere but need to used when you have lot of policies where changes are inevitable on a regular basis.

List directory in Go

You can try using the ReadDir function in the io/ioutil package. Per the docs:

ReadDir reads the directory named by dirname and returns a list of sorted directory entries.

The resulting slice contains os.FileInfo types, which provide the methods listed here. Here is a basic example that lists the name of everything in the current directory (folders are included but not specially marked - you can check if an item is a folder by using the IsDir() method):

package main

import (
    "fmt"
    "io/ioutil"
     "log"
)

func main() {
    files, err := ioutil.ReadDir("./")
    if err != nil {
        log.Fatal(err)
    }
 
    for _, f := range files {
            fmt.Println(f.Name())
    }
}

python: How do I know what type of exception occurred?

Your question is: "How can I see exactly what happened in the someFunction() that caused the exception to happen?"

It seems to me that you are not asking about how to handle unforeseen exceptions in production code (as many answers assumed), but how to find out what is causing a particular exception during development.

The easiest way is to use a debugger that can stop where the uncaught exception occurs, preferably not exiting, so that you can inspect the variables. For example, PyDev in the Eclipse open source IDE can do that. To enable that in Eclipse, open the Debug perspective, select Manage Python Exception Breakpoints in the Run menu, and check Suspend on uncaught exceptions.

Split string into individual words Java

A regex can also be used to split words.

\w can be used to match word characters ([A-Za-z0-9_]), so that punctuation is removed from the results:

String s = "I want to walk my dog, and why not?";
Pattern pattern = Pattern.compile("\\w+");
Matcher matcher = pattern.matcher(s);
while (matcher.find()) {
    System.out.println(matcher.group());
}

Outputs:

I
want
to
walk
my
dog
and
why
not

See Java API documentation for Pattern

Change x axes scale in matplotlib

The scalar formatter supports collecting the exponents. The docs are as follows:

class matplotlib.ticker.ScalarFormatter(useOffset=True, useMathText=False, useLocale=None) Bases: matplotlib.ticker.Formatter

Tick location is a plain old number. If useOffset==True and the data range is much smaller than the data average, then an offset will be determined such that the tick labels are meaningful. Scientific notation is used for data < 10^-n or data >= 10^m, where n and m are the power limits set using set_powerlimits((n,m)). The defaults for these are controlled by the axes.formatter.limits rc parameter.

your technique would be:

from matplotlib.ticker import ScalarFormatter
xfmt = ScalarFormatter()
xfmt.set_powerlimits((-3,3))  # Or whatever your limits are . . .
{{ Make your plot }}
gca().xaxis.set_major_formatter(xfmt)

To get the exponent displayed in the format x10^5, instantiate the ScalarFormatter with useMathText=True.

After Image

You could also use:

xfmt.set_useOffset(10000)

To get a result like this:

enter image description here

How to code a very simple login system with java

this is my first code on this site try this

import java.util.Scanner;
public class BATM {

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);

    String username;
    String password;

    System.out.println("Log in:");
    System.out.println("username: ");
    username = input.next();

    System.out.println("password: ");
    password = input.next();

    //users check = new users(username, password);

    if(username.equals(username) && password.equals(password)) 
        System.out.println("You are logged in");



}

}

Difference between Console.Read() and Console.ReadLine()?

Console.Read()

  • It only accepts a single character from user input and returns its ASCII Code.
  • The data type should be int. because it returns an integer value as ASCII.
  • ex -> int value = Console.Read();

Console.ReadLine()

  • It read all the characters from user input. (and finish when press enter).
  • It returns a String so data type should be String.
  • ex -> string value = Console.ReadLine();

Console.ReadKey()

  • It read that which key is pressed by the user and returns its name. it does not require to press enter key before entering.
  • It is a Struct Data type which is ConsoleKeyInfo.
  • ex -> ConsoleKeyInfo key = Console.ReadKey();

Linux: copy and create destination dir if it does not exist

This does it for me

cp -vaR ./from ./to

How do I update the GUI from another thread?

My version is to insert one line of recursive "mantra":

For no arguments:

    void Aaaaaaa()
    {
        if (InvokeRequired) { Invoke(new Action(Aaaaaaa)); return; } //1 line of mantra

        // Your code!
    }

For a function that has arguments:

    void Bbb(int x, string text)
    {
        if (InvokeRequired) { Invoke(new Action<int, string>(Bbb), new[] { x, text }); return; }
        // Your code!
    }

THAT is IT.


Some argumentation: Usually it is bad for code readability to put {} after an if () statement in one line. But in this case it is routine all-the-same "mantra". It doesn't break code readability if this method is consistent over the project. And it saves your code from littering (one line of code instead of five).

As you see if(InvokeRequired) {something long} you just know "this function is safe to call from another thread".

How can I check if a jQuery plugin is loaded?

Generally speaking, jQuery plugins are namespaces on the jQuery scope. You could run a simple check to see if the namespace exists:

 if(jQuery().pluginName) {
     //run plugin dependent code
 }

dateJs however is not a jQuery plugin. It modifies/extends the javascript date object, and is not added as a jQuery namespace. You could check if the method you need exists, for example:

 if(Date.today) {
      //Use the dateJS today() method
 }

But you might run into problems where the API overlaps the native Date API.

The absolute uri: http://java.sun.com/jsp/jstl/core cannot be resolved in either web.xml or the jar files deployed with this application

if you use spring boot check in application.propertiese this property is commented or remove it if exist.

server.tomcat.additional-tld-skip-patterns=*.jar

sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

You need to pass in a sequence, but you forgot the comma to make your parameters a tuple:

cursor.execute('INSERT INTO images VALUES(?)', (img,))

Without the comma, (img) is just a grouped expression, not a tuple, and thus the img string is treated as the input sequence. If that string is 74 characters long, then Python sees that as 74 separate bind values, each one character long.

>>> len(img)
74
>>> len((img,))
1

If you find it easier to read, you can also use a list literal:

cursor.execute('INSERT INTO images VALUES(?)', [img])

How to recursively find and list the latest modified files in a directory with subdirectories and times

To find all files whose file status was last changed N minutes ago:

find -cmin -N

For example:

find -cmin -5

How do I set the focus to the first input element in an HTML form independent from the id?

Without third party libs, use something like

  const inputElements = parentElement.getElementsByTagName('input')
  if (inputChilds.length > 0) {
    inputChilds.item(0).focus();
  }

Make sure you consider all form element tags, rule out hidden/disabled ones like in other answers and so on..

Android: How to bind spinner to custom object list?

Works fine for me, the code needed around the getResource() thing is as follows:

spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> spinner, View v,
                int arg2, long arg3) {
            String selectedVal = getResources().getStringArray(R.array.compass_rate_values)[spinner.getSelectedItemPosition()];
            //Do something with the value
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub
        }

    });

Just need to make sure (by yourself) the values in the two arrays are aligned properly!

Checking if sys.argv[x] is defined

It's an ordinary Python list. The exception that you would catch for this is IndexError, but you're better off just checking the length instead.

if len(sys.argv) >= 2:
  startingpoint = sys.argv[1]
else:
  startingpoint = 'blah'

How to write connection string in web.config file and read from it?

Try this After open web.config file in application and add sample db connection in connectionStrings section like this

<connectionStrings>
<add name="yourconnectinstringName" connectionString="Data Source= DatabaseServerName; Integrated Security=true;Initial Catalog= YourDatabaseName; uid=YourUserName; Password=yourpassword; " providerName="System.Data.SqlClient"/>
</connectionStrings >

How to compile multiple java source files in command line

Try the following:

javac file1.java file2.java

How to delete files recursively from an S3 bucket

You might also consider using Amazon S3 Lifecycle to create an expiration for files with the prefix foo/bar1.

Open the S3 browser console and click a bucket. Then click Properties and then LifeCycle.

Create an expiration rule for all files with the prefix foo/bar1 and set the date to 1 day since file was created.

Save and all matching files will be gone within 24 hours.

Just don't forget to remove the rule after you're done!

No API calls, no third party libraries, apps or scripts.

I just deleted several million files this way.

A screenshot showing the Lifecycle Rule window (note in this shot the Prefix has been left blank, affecting all keys in the bucket):

enter image description here

Trim whitespace from a String

Here is how you can do it:

std::string & trim(std::string & str)
{
   return ltrim(rtrim(str));
}

And the supportive functions are implemeted as:

std::string & ltrim(std::string & str)
{
  auto it2 =  std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
  str.erase( str.begin() , it2);
  return str;   
}

std::string & rtrim(std::string & str)
{
  auto it1 =  std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );
  str.erase( it1.base() , str.end() );
  return str;   
}

And once you've all these in place, you can write this as well:

std::string trim_copy(std::string const & str)
{
   auto s = str;
   return ltrim(rtrim(s));
}

Try this

Android: Rotate image in imageview by an angle

I think the best method :)

int angle = 0;
imageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            angle = angle + 90;
            imageView.setRotation(angle);
        }
    });

fstream won't create a file

You need to add some arguments. Also, instancing and opening can be put in one line:

fstream file("test.txt", fstream::in | fstream::out | fstream::trunc);

How can I set the form action through JavaScript?

document.forms[0].action="http://..."

...assuming it is the first form on the page.

How to generate .json file with PHP?

If you're pulling dynamic records it's better to have 1 php file that creates a json representation and not create a file each time.

my_json.php

$array = array(
    'title' => $title,
    'url' => $url
);

echo stripslashes(json_encode($array)); 

Then in your script set the path to the file my_json.php

Validate phone number using javascript

In JavaScript, the below regular expression can be used for a phone number :

^((\+1)?[\s-]?)?\(?[1-9]\d\d\)?[\s-]?[1-9]\d\d[\s-]?\d\d\d\d

e.g; 9999875099 , 8750999912 etc.

Reference : https://techsolutions.filebizz.com/2020/08/regular-expression-for-phone-number-in.html

How can I convert a std::string to int?

My Code:

#include <iostream>
using namespace std;

int main()
{
    string s="32";  //String
    int n=stoi(s);  //Convert to int
    cout << n + 1 << endl;

    return 0;
}

How to make a simple rounded button in Storyboard?

I found the easiest way to do this, is by setting the cornerRadius to half of the height of the view.

button.layer.cornerRadius = button.bounds.size.height/2

Sending commands and strings to Terminal.app with Applescript

As neat solution, try-

$ open -a /Applications/Utilities/Terminal.app  *.py

or

$ open -b com.apple.terminal *.py

For the shell launched, you can go to Preferences > Shell > set it to exit if no error.

That's it.

How to remove focus border (outline) around text/input boxes? (Chrome)

This will definitely work. Orange outline will not show anymore.. Common for all tags:

*:focus {
    outline: none;
}

Specific to some tag, ex: input tag

input:focus {
   outline:none;
}

How to parse JSON boolean value?

Try this:

{
    "ACCOUNT_EXIST": true,
    "MultipleContacts": false
}

boolean success ((Boolean) jsonObject.get("ACCOUNT_EXIST")).booleanValue()

Ignore <br> with CSS?

Note: This solution only works for Webkit browsers, which incorrectly apply pseudo-elements to self-closing tags.

As an addendum to above answers it is worth noting that in some cases one needs to insert a space instead of merely ignoring <br>:

For instance the above answers will turn

Monday<br>05 August

to

Monday05 August

as I had verified while I tried to format my weekly event calendar. A space after "Monday" is preferred to be inserted. This can be done easily by inserting the following in the CSS:

br  {
    content: ' '
}
br:after {
    content: ' '
}

This will make

Monday<br>05 August

look like

Monday 05 August

You can change the content attribute in br:after to ', ' if you want to separate by commas, or put anything you want within ' ' to make it the delimiter! By the way

Monday, 05 August

looks neat ;-)

See here for a reference.

As in the above answers, if you want to make it tag-specific, you can. As in if you want this property to work for tag <h3>, just add a h3 each before br and br:after, for instance.

It works most generally for a pseudo-tag.

Count the number of occurrences of each letter in string

Have checked that many of the answered are with static array, what if suppose I have special character in the string and want a solution with dynamic concept. There can be many other possible solutions, it is one of them.

here is the solutions with the Linked List.

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

struct Node { 
    char data; 
    int counter;
    struct Node* next; 
};

void printLinkList(struct Node* head)
{
    while (head != NULL) { 
        printf("\n%c occur %d", head->data, head->counter);
        head = head->next;
    }
}

int main(void) {
    char *str = "!count all the occurances of character in string!";
    int i = 0;
    char tempChar;
    struct Node* head = NULL; 
    struct Node* node = NULL; 
    struct Node* first = NULL; 

    for(i = 0; i < strlen(str); i++)
    {
        tempChar = str[i];

        head = first;

        if(head == NULL)
        {
            node = (struct Node*)malloc(sizeof(struct Node));
            node->data = tempChar;
            node->counter = 1;
            node->next = NULL;

            if(first == NULL)
            {
                first = node;
            }
        }
        else
        {
            while (head->next != NULL) { 
                if(head->data == tempChar)
                {
                    head->counter = head->counter + 1;
                    break;
                }
                head = head->next;
            }

            if(head->next == NULL)
            {
                if(head->data == tempChar)
                {
                    head->counter = head->counter + 1;
                }
                else
                {
                    node = (struct Node*)malloc(sizeof(struct Node));
                    node->data = tempChar;
                    node->counter = 1;
                    node->next = NULL;
                    head->next = node;
                }
            }
        }
    }

    printLinkList(first);


    return 0;
}

Facebook login message: "URL Blocked: This redirect failed because the redirect URI is not whitelisted in the app’s Client OAuth Settings."

Ok First of all this is a very clear error message. Just look at this many devs miss this including my self. Have a look at the screen shot here please.

enter image description here

Under Products > Facebook Login > Settings

or just go to this url here (Replace YOUR_APP_ID with your app id lol):

https://developers.facebook.com/apps/YOUR_APP_ID/fb-login/settings/

If you are working on localhost:3000 Make sure you have https://localhost:3000/auth/facebook/callback

Ofcourse you don't have to have the status live (Green Switch on top right corner) but in my case, I am deploying to heroku now and will soon replace localhost:3000 with https://myapp.herokuapp.com/auth/facebook/callback

Of course I will update the urls in Settings/Basic & Settings/Advanced and also add a privacy policy url in the basic section.

I am assuming that you have properly configured initializers/devise.rb if you are using devise and you have the proper facebook gem 'omniauth-facebook', '~> 4.0' gem installed and gem 'omniauth', '~> 1.6', and you have the necessary columns in your users table such as uid, image, and provider. That's it.

Viewing full version tree in git

You can try the following:

gitk --all

You can tell gitk what to display using anything that git rev-list understands, so if you just want a few branches, you can do:

gitk master origin/master origin/experiment

... or more exotic things like:

gitk --simplify-by-decoration --all

Select2 doesn't work when embedded in a bootstrap modal

I have the same problem with the select2 in bootstrap modal, and the solution was to remove the overflow-y: auto; and overflow: hidden; from .modal-open and .modal classes

Here is the example of using jQuery to remove the overflow-y:

$('.modal').css('overflow-y','visible');
$('.modal').css('overflow','visible');

How to convert R Markdown to PDF?

Right now (August 2014) You could use RStudio for converting R Markdown to PDF. Basically, RStudio use pandoc to convert Rmd to PDF.

You could change metadata to:

  1. Add table of contents
  2. Change figure options
  3. Change syntax highlighting style
  4. Add LaTeX options
  5. And many more...

For more details - http://rmarkdown.rstudio.com/pdf_document_format.htmlenter image description here